text
stringlengths
13
6.01M
using EmberKernel.Services.EventBus; using EmberKernel.Services.Statistic.DataSource.Variables; using System; using System.Diagnostics.CodeAnalysis; namespace EmberMemoryReader.Abstract.Data { public enum OsuInternalStatus { Menu, Edit, Play, Exit, SelectEdit, SelectPlay, SelectDrawings, Rank, Update, Busy, Unknown, Lobby, MatchSetup, SelectMulti, RankingVs, OnlineSelection, OptionsOffsetWizard, RankingTagCoop, RankingTeam, BeatmapImport, PackageUpdater, Benchmark, Tourney, Charts } [EventNamespace("MemoryReader")] public class GameStatusInfo : Event<GameStatusInfo>, IComparable<GameStatusInfo>, IEquatable<GameStatusInfo> { public bool HasValue { get; set; } [DataSourceVariable] public OsuInternalStatus Status { get; set; } [DataSourceVariable(Name = "GameStatus")] public string StringStatus { get; set; } public int CompareTo([AllowNull] GameStatusInfo other) { return (int)this.Status - (int)other.Status; } public bool Equals([AllowNull] GameStatusInfo other) { return this.Status == other.Status; } } }
using System; using System.Collections.Generic; using System.Text; using DBDiff.Schema.MySQL.Model; namespace DBDiff.Schema.MySQL.Compare { internal static class CompareConstraints { public static Constraints GenerateDiferences(Constraints CamposOrigen, Constraints CamposDestino) { foreach (Constraint node in CamposDestino) { if (!CamposOrigen.Find(node.Name)) { Constraint newNode = node.Clone(CamposOrigen.Parent); newNode.Status = StatusEnum.ObjectStatusType.CreateStatus; CamposOrigen.Add(newNode); } else { if (!Constraint.Compare(CamposOrigen[node.Name], node)) { Constraint newNode = node.Clone(CamposOrigen.Parent); newNode.Status = StatusEnum.ObjectStatusType.AlterStatus; CamposOrigen[node.Name] = newNode; } } } foreach (Constraint node in CamposOrigen) { if (!CamposDestino.Find(node.Name)) { node.Status = StatusEnum.ObjectStatusType.DropStatus; } } return CamposOrigen; } } }
using gView.Framework.Geometry; using System; using System.Collections.Generic; namespace gView.Framework.FDB { public class SpatialIndexNode : ISpatialIndexNode, IComparable { private int _NID = 0, _PID = 0; private short _page; private IGeometry _geom; private List<int> _IDs; #region ISpatialIndexNode Member public int NID { get { return _NID; } set { _NID = value; } } public int PID { get { return _PID; } set { _PID = value; } } public IGeometry Rectangle { get { return _geom; } set { _geom = value; } } public List<int> IDs { get { return _IDs; } set { _IDs = value; } } public short Page { get { return _page; } set { _page = value; } } #endregion #region IComparable Member public int CompareTo(object obj) { return (this.NID < (((ISpatialIndexNode)obj).NID)) ? -1 : 1; //return 0; } #endregion } }
namespace com.Sconit.Entity.SI.SD_SCM { using System; using System.Collections.Generic; [Serializable] public class FlowMaster { #region O/R Mapping Properties public string Code { get; set; } public string Description { get; set; } public Boolean IsActive { get; set; } public com.Sconit.CodeMaster.OrderType Type { get; set; } public string ReferenceFlow { get; set; } public string PartyFrom { get; set; } public string PartyTo { get; set; } //public string ShipFrom { get; set; } //public string ShipTo { get; set; } public string LocationFrom { get; set; } public string LocationTo { get; set; } //public string BillAddress { get; set; } //public string PriceList { get; set; } //public string Dock { get; set; } public string Routing { get; set; } //public string ReturnRouting { get; set; } //public Boolean IsAutoCreate { get; set; } //public Boolean IsAutoRelease { get; set; } //public Boolean IsAutoStart { get; set; } //public Boolean IsAutoShip { get; set; } //public Boolean IsAutoReceive { get; set; } //public Boolean IsAutoBill { get; set; } //public Boolean IsListDet { get; set; } public Boolean IsManualCreateDetail { get; set; } //public Boolean IsListPrice { get; set; } //public Boolean IsPrintOrder { get; set; } //public Boolean IsPrintAsn { get; set; } //public Boolean IsPrintRceipt { get; set; } //public Boolean IsShipExceed { get; set; } //public Boolean IsReceiveExceed { get; set; } public Boolean IsOrderFulfillUC { get; set; } //public Boolean IsShipFulfillUC { get; set; } //public Boolean IsReceiveFulfillUC { get; set; } //public Boolean IsShipScanHu { get; set; } //public Boolean IsReceiveScanHu { get; set; } //public Boolean IsCreatePickList { get; set; } //public Boolean IsInspect { get; set; } //public Boolean IsRejectInspect { get; set; } //public Boolean IsReceiveFifo { get; set; } //public Boolean IsShipByOrder { get; set; } //public Boolean IsAsnUniqueReceive { get; set; } //public Boolean IsMRP { get; set; } //public com.Sconit.CodeMaster.ReceiveGapTo ReceiveGapTo { get; set; } //public string ReceiptTemplate { get; set; } //public string OrderTemplate { get; set; } //public string AsnTemplate { get; set; } //public string HuTemplate { get; set; } //public com.Sconit.CodeMaster.OrderBillTerm BillTerm { get; set; } //public com.Sconit.CodeMaster.CreateHuOption CreateHuOption { get; set; } //public Int32 MaxOrderCount { get; set; } //public com.Sconit.CodeMaster.MRPOption MRPOption { get; set; } //public Boolean IsPause { get; set; } //public DateTime? PauseTime { get; set; } public Boolean IsCheckPartyFromAuthority { get; set; } public Boolean IsCheckPartyToAuthority { get; set; } //public Boolean IsShipFifo { get; set; } //public string ExtraDemandSource { get; set; } //public com.Sconit.CodeMaster.FlowStrategy FlowStrategy { get; set; } //public string PickStrategy { get; set; } #endregion #region public string Bin { get; set; } public DateTime? EffectiveDate { get; set; } public List<FlowDetail> FlowDetails { get; set; } #endregion } }
using System.ComponentModel.DataAnnotations; namespace HotelDatabase.Models { public class Room { [Key] public int RoomNumber { get; set; } [Required] public RoomType RoomType { get; set; } [Required] public BedType BedType { get; set; } public decimal Rate { get; set; } [Required] public RoomStatus RoomStatus { get; set; } public string Notes { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace code { public class leetCodeThree { // 输入: "abcabcbb" //输出: 3 //解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 // 输入: "bbbbb" //输出: 1 //解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 public static void Getlenth() { string str = "abcabcbb"; Dictionary<char, int> dt = new Dictionary<char, int>(); int ans = 0; #region 第一种 for (int i = 0; i < str.Length; i++) { if (dt.ContainsKey(str[i])) { // dt.Remove(str[i]); } else { dt.Add(str[i], i); ans += 1; } } #endregion } public static void reversal(int x) { // x = 123; string ask = ""; while (x != 0) { int i= x % 10; x = x / 10; ask += i.ToString(); } // 95647123 32174659 int cccc = 0; } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace KeepTeamAutotests.Pages { public class NewCandidatePopup : PopupPage { [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[2]/div[1]/div/div/input")] private IWebElement lastNameField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[2]/div[2]/div/div/input")] private IWebElement nameField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[2]/div[3]/div/div/input")] private IWebElement patronimycField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[1]/div/div/div[1]/input")] private IWebElement dateField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[4]/div[1]/div/div/div[1]/div/input")] private IWebElement cityField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[2]/div/div/div/div/div[2]")] private IWebElement sexField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']//*[@id='businessTrips']")] private IWebElement tripCheckBox; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']//*[@id='move']")] private IWebElement moveCheckBox; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[6]/div/div/div/div/div/div/div[2]/div/div/input")] private IWebElement contactField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[6]/div/div/div/div/div/div/div[1]/div/div/div[1]/div/input")] private IWebElement contactTypeField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[5]/div/div/div/textarea")] private IWebElement descriptionField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[4]/div[4]/div/div/div")] private IWebElement skillField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[3]/div/div/input")] private IWebElement paymentField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[8]/div/button")] private IWebElement saveButton; public NewCandidatePopup(PageManager pageManager) : base(pageManager) { pagename = "newcandidatepopup"; } public void setNameField(string name) { setTextField(nameField, name); } public void setDescriptionField(string description) { setTextField(descriptionField, description); } public string getName() { return getTextField(nameField); } public string getDate() { //клик в поле, чтобы убрать лишние записи dateField.Click(); return getTextField(dateField); // return getTextField(dateField,"","января . 45 лет"); } public string getDescription() { return getTextField(descriptionField); } internal void saveClick() { saveButton.Click(); waitSaveDone(); } internal void setLastNameField(string lastname) { setTextField(lastNameField, lastname); } internal string getLastName() { return getTextField(lastNameField); } internal void setCityField(string city) { setSuggestField(cityField, city); } internal void setDateField(string date) { setDateFieldWithDatePicker(dateField, date); } internal string getCity() { return getTextField(cityField); } internal void setPatronimycField(string patronimyc) { setTextField(patronimycField, patronimyc); } internal string getContact() { return getTextField(contactField); } internal string getContactType() { return getTextField(contactTypeField); } internal void setSkill(int skill) { setStarsField(skillField, skill); } internal int getSkill() { return getStarsField(skillField); } internal void clearName() { nameField.Clear(); } internal void clearLastname() { lastNameField.Clear(); } internal void clearDateBirthday() { ClearManual(dateField); } internal void clearCity() { cityField.Clear(); } /* internal void clearFounder() { founderField.Clear(); } */ internal void clearDescription() { descriptionField.Clear(); } /* internal void clearPhone() { phoneField.Clear(); } /* internal void clearFound() { founderField.Clear(); } */ internal void clearSkill() { clearStarsField(skillField); } internal void setMinPay(string MinPay) { setTextField(paymentField, MinPay); } /* internal void setMaxPay(string MaxPay) { setTextField(maxField, MaxPay); } */ /* internal string getMaxPay() { return getTextField(maxField); } */ internal string getPayment() { return getTextField(paymentField,""," Р"); } /* internal void clearMaxPay() { maxField.Clear(); } */ internal void clearPayment() { ClearManual(paymentField);//Firefox чудит, надо очищать вручную } internal string getPatronimyc() { return getTextField(patronimycField); } internal void clearPatronimyc() { patronimycField.Clear(); } internal void setSexField(string sex) { setDropdownByText(sexField, sex); } internal string getSex() { return getDropDownText(sexField); } internal void setTrip(bool p) { setCheckBox(tripCheckBox,p); } internal void setMove(bool p) { setCheckBox(moveCheckBox, p); } internal void setContact(string contact) { setTextField(contactField, contact); } internal void setContactType(string type) { setSuggestField(contactTypeField, type); } internal bool getMove() { return getCheckBox(moveCheckBox); } internal bool getTrip() { return getCheckBox(tripCheckBox); } internal void clearContact() { contactField.Clear(); } internal void clearContactType() { contactTypeField.Clear(); } } }
using Chess.v4.Engine.Interfaces; using Chess.v4.Models; using Common.Responses; using Microsoft.AspNetCore.Mvc; using Omu.ValueInjecter; using Website.Factories; using Website.Models; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Website { [Route("api/[controller]")] public class GameController : Controller { private readonly IGameStateService _gameStateService; public GameController(IGameStateService gameStateService) { _gameStateService = gameStateService; } [HttpGet] [Route("state-info")] public OperationResult<GameStateResource> GetStateInfo([FromQuery] string fen) { var result = _gameStateService.Initialize(fen); if (result.Success) { var gameStateResult = GameStateResourceFactory.ToGameStateResource(result.Result); return OperationResult<GameStateResource>.Ok(gameStateResult.Result); } else { return OperationResult<GameStateResource>.Fail(result.Message); } } [HttpPost] [Route("move")] public OperationResult<GameStateResource> MakeMove([FromBody] MoveRequestResource moveRequest) { var gameStateResult = GameStateResourceFactory.ToGameState(moveRequest.GameState); var result = _gameStateService.MakeMove(gameStateResult.Result, moveRequest.Beginning, moveRequest.Destination, moveRequest.PiecePromotionType); if (result.Success) { var gameStateResourceResult = GameStateResourceFactory.ToGameStateResource(result.Result); return OperationResult<GameStateResource>.Ok(gameStateResourceResult.Result); } else { return OperationResult<GameStateResource>.Fail(result.Message); } } [HttpPost] [Route("goto")] public OperationResult<GameStateResource> GoTo([FromBody] GoToMoveResource goToMoveResource) { var gameStateResult = GameStateResourceFactory.ToGameState(goToMoveResource.GameState); var result = GameStateResourceFactory.MoveToHistoryIndex(_gameStateService, gameStateResult.Result, goToMoveResource.HistoryIndex); if (result.Success) { return OperationResult<GameStateResource>.Ok(result.Result); } else { return OperationResult<GameStateResource>.Fail(result.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace SolutionsAssembly { public class AmicableNumbers :ISolutionsContract { public string ProblemName => "Amicable Numbers"; public string ProblemDescription => @"Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. "; public int ProblemNumber => 21; public string Solution() { return ProblemSolution(10000).ToString(); } private long ProblemSolution(int max) { return IsAmicable(max); } private long IsAmicable(int max) { List<int> amicableList = new List<int>(); for (var n = 1; n < max+1; n++) { if (amicableList.IndexOf(n) > 0) continue; // if we have this number in the amicable list then proceed else skip var properSumList = ProperDevisors(n); // get proper devisors if (properSumList.Count() < 3) continue; // if prime skip var properSum = properSumList.Sum(); if (properSum == n ) continue; var partnerSum = ProperDevisors(properSum).Sum(); // get the partner sum if (n != partnerSum) continue; // if they == then add to list else skip amicableList.Add(n); amicableList.Add(properSumList.Sum()); } return amicableList.Sum(); } private IEnumerable<int> ProperDevisors(int to) { return Enumerable.Range(1, to / 2).Where(divisor => to % divisor == 0).ToList(); ; } #region Euler's Rule private int GetEulerPValue(int n) { var m = n - 1; return (int)((Math.Pow(2, n - m) + 1) * Math.Pow(2, m) - 1); ; } private int GetEulerQValue(int n) { var m = n - 1; return (int)((Math.Pow(2, n - m) + 1) * Math.Pow(2, n) - 1); } private int GetEulerRValue(int n) { var m = n - 1; return (int)(Math.Pow((Math.Pow(2, n - m) + 1), 2) * Math.Pow(2, m + n) - 1); } #endregion private bool IsPrimeQPRValues(int p, int q, int r) { return Dry.DryCode.IsPrime(p) && Dry.DryCode.IsPrime(q) && Dry.DryCode.IsPrime(r); } } }
using Pe.Stracon.SGC.Infraestructura.QueryModel.Base; using System; namespace Pe.Stracon.SGC.Infraestructura.Core.Base { /// <summary> /// Repository contract: for Read a DTO. /// </summary> /// <remarks> /// Creación: GMD 22122014 <br /> /// Modificación: <br /> /// </remarks> public interface IQueryRepository<T> : IDisposable where T : Logic { } }
using System; namespace TexturePacker.Editor.Domain.Entities { [Serializable] public class FrameVector { public float x; public float y; } }
using System; using System.Windows.Forms; using System.IO; using Microsoft.WindowsAPICodePack.Dialogs; namespace LJM_Utils { public partial class RenamerForm : Form { System.Drawing.Point OptionGroupLocation = new System.Drawing.Point(11, 202); int PreviousStrategySelection = -1; public RenamerForm() { InitializeComponent(); // Resize form and move option groups to overlay one another. // Reasoning: keeping everything separated allows for easy design of the controls // when they are intended to all be on top of one another during runtime. this.Width = 360; groupRandomOptions.Location = OptionGroupLocation; groupRegExOptions.Location = OptionGroupLocation; groupLinearOptions.Location = OptionGroupLocation; } private void ValidateRenameProcess(ref bool NoErrorsFound) { // validate given path if (!Directory.Exists(txtInputDirectory.Text)) { NoErrorsFound = false; MessageBox.Show($"The given path \"{txtInputDirectory.Text}\" does not exist.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // validate options for selected strategy switch (comboRenamingStrat.SelectedIndex) { case (int)StrategySelection.Linear: if (txtLinearExample.Text.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { NoErrorsFound = false; } break; case (int)StrategySelection.Random: if (numRandomCharsOption.Value < 1) { NoErrorsFound = false; } break; case (int)StrategySelection.RegEx: // TODO: given pattern containins a capture group NoErrorsFound = false; // not implemented break; default: NoErrorsFound = false; break; } // validate given extensions if (!true) { } // validate combo box selection if (comboRenamingStrat.SelectedItem.ToString() == Vocab.Renaming.ComboDefault) { NoErrorsFound = false; MessageBox.Show($"You must select a renaming strategy.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnRename_Click(object sender, EventArgs e) { bool NoErrorsFound = true; ValidateRenameProcess(ref NoErrorsFound); if (NoErrorsFound) { try { switch (comboRenamingStrat.SelectedItem.ToString()) { case Vocab.Renaming.ComboLinear: { LinearRenamer linearRenamer = new LinearRenamer(txtInputDirectory.Text, getExtInclusions(), txtPrefixOption.Text, txtSuffixOption.Text); linearRenamer.Execute(); MessageBox.Show($"Success! \n{linearRenamer.FileCount} files were renamed.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information); break; } case Vocab.Renaming.ComboRandom: { RandomRenamer randomRenamer = new RandomRenamer(txtInputDirectory.Text, getExtInclusions()); randomRenamer.Execute(); MessageBox.Show($"Success! \n{randomRenamer.FileCount} files were renamed.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information); break; } case Vocab.Renaming.ComboRegEx: { MessageBox.Show("RegEx strategy is WIP and not available.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } default: break; } } catch (Exception thrownException) { MessageBox.Show($"An unhandled exception has occurred: {thrownException.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnClear_Click(object sender, EventArgs e) { txtInputDirectory.Text = ""; txtExtInclusions.Text = ""; txtPrefixOption.Text = ""; txtSuffixOption.Text = ""; numRandomCharsOption.Value = 10; } private void btnUndo_Click(object sender, EventArgs e) { // TODO: write support for logging of renames and functionality to undo logged "runs" // Idea 1: logging folder in temp folder with all rename jobs as separate text // files, timestamped with time since epoch as "job number" // Idea 2: SQLite database thats lists everything } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } private void RenamerForm_Load(object sender, EventArgs e) { comboRenamingStrat.SelectedItem = "Select a strategy..."; } private void btnBrowseForInput_Click(object sender, EventArgs e) { // Folder browser improved dialog source: https://stackoverflow.com/a/41511598 CommonOpenFileDialog dialog = new CommonOpenFileDialog { IsFolderPicker = true, EnsurePathExists = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { txtInputDirectory.Text = dialog.FileName; } } private string[] getExtInclusions() { if (txtExtInclusions.Text.Trim() != "") { return txtExtInclusions.Text.Split(' '); } else { return null; } } public enum StrategySelection { Default = 0, Linear = 1, Random = 2, RegEx = 3 } private void comboRenamingStrat_SelectedIndexChanged(object sender, EventArgs e) { if (PreviousStrategySelection == -1 && comboRenamingStrat.SelectedIndex == 0) { PreviousStrategySelection = 0; } else { // hide previous group switch (PreviousStrategySelection) { case (int)StrategySelection.Default: break; case (int)StrategySelection.Linear: groupLinearOptions.Visible = false; break; case (int)StrategySelection.Random: groupRandomOptions.Visible = false; break; case (int)StrategySelection.RegEx: groupRegExOptions.Visible = false; break; default: break; } // show selected group switch (comboRenamingStrat.SelectedIndex) { case (int)StrategySelection.Default: break; case (int)StrategySelection.Linear: groupLinearOptions.Visible = true; break; case (int)StrategySelection.Random: groupRandomOptions.Visible = true; break; case (int)StrategySelection.RegEx: groupRegExOptions.Visible = true; break; default: break; } } PreviousStrategySelection = comboRenamingStrat.SelectedIndex; } private void txtPrefixOption_TextChanged(object sender, EventArgs e){UpdateLinearExample();} private void txtSuffixOption_TextChanged(object sender, EventArgs e){UpdateLinearExample();} private void UpdateLinearExample() { txtLinearExample.Text = LinearRenamer.ExampleFilename(txtPrefixOption.Text, txtSuffixOption.Text); } private void numRandomCharsOption_ValueChanged(object sender, EventArgs e) { txtRandomExample.Text = RandomRenamer.ExampleFilename((int)numRandomCharsOption.Value); } } }
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; namespace Alabo.Domains.Repositories.EFCore { /// <summary> /// 通过Dapper获取数据 /// https://github.com/StackExchange/Dapper /// 教程:https://www.cnblogs.com/lunawzh/p/6607116.html /// </summary> public static class RepositoryDapperExtensions { private static DbConnection Connection(this IRepositoryContext context) { var con = context; //context.DbContexts.TryGetValue(RuntimeContext.CurrentTenant, // out EfCoreRepositoryContext.InnerDbContext _context); //if (_context is DbContext) { // return (_context as DbContext).Database.GetDbConnection(); //} throw new System.Exception("no DbConnection supported for this context."); } public static T DapperGet<T>(this IRepositoryContext context, string sql, object param = null) where T : class { var connection = context.Connection(); if (connection.State != ConnectionState.Open) { connection.Open(); } var result = connection.QueryFirstOrDefault<T>(sql, param); return result; } public static IEnumerable<T> DapperGetList<T>(this IRepositoryContext context, string sql, object param = null) where T : class { var connection = context.Connection(); if (connection.State != ConnectionState.Open) { connection.Open(); } var result = connection.Query<T>(sql, param); return result; } public static IEnumerable<TReturn> DapperGetList<TFirst, TSecond, TReturn>(this IRepositoryContext context, string sql, Func<TFirst, TSecond, TReturn> map) { var connection = context.Connection(); if (connection.State != ConnectionState.Open) { connection.Open(); } var result = connection.Query(sql, map); return result; } public static TReturn DapperGet<TFirst, TSecond, TReturn>(this IRepositoryContext context, string sql, Func<TFirst, TSecond, TReturn> map) { var connection = context.Connection(); if (connection.State != ConnectionState.Open) { connection.Open(); } var result = connection.Query(sql, map); return result.FirstOrDefault(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager instance = null; private LevelManager levelManager; //[HideInInspector] public bool playersTurn = true; //private int level = 3; // Used as a var to determine difficulty // Use this for initialization // Awake is called first as soon as object has been initialized by Unity, even if // the object has not been enabled (hasn't been rendered or updated) // Start is called after the object is enabled void Awake() { if (instance == null) instance = this; else if (instance != this) Destroy(gameObject); // Destroy the Game Object this script component is attached to // We don't want more than one instance of a GameManager Game Object // When we load a new scene, normally all Game Objects of hierarchy will be destroyed // We want to use GameManager Game Object to keep track of score between scenes, so we want the GameManager // to persist between scenes DontDestroyOnLoad(gameObject); // In Unity, scripts are considered Game Object components // Angle brackets <> are used for taking a type as a parameter // GetComponent returns reference to any component of the type specified of the // Game Object it's called upon // So to access attributes of another script, we don't import that script, we do this // bullshit (i.e. call GetComponent<>) levelManager = GetComponent<LevelManager>(); InitGame(); } void InitGame() { levelManager.SetupScene(); } public void GameOver() { enabled = false; // Disable the GameManager script component } }
using Assets.Scripts.Models; namespace Assets.Scripts.Controllers { public class GroundPlacementItemData { public BaseObject ItemModel; public bool Dropped; public int Amount; public int? Durability; public GroundPlacementItemData(BaseObject itemModel, bool dropped = false, int amount = 1, int? durability = null) { ItemModel = itemModel; Dropped = dropped; Amount = amount; Durability = durability; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2_nyolcadik_feladat { class Program { struct Versenyzo { public string nev; public int elertPont; public int versenyAzonosito; } static void Main(string[] args) { int versenyzokSzama; do { Console.WriteLine("Minimum 3 versenyzőt kell felvinni!"); do { Console.WriteLine("Hány versenyzőt akarsz felvinni?"); } while (!int.TryParse(Console.ReadLine(), out versenyzokSzama)); } while (!(versenyzokSzama >= 3)); Versenyzo[] egyDarabVersenyzoAdatai = new Versenyzo[versenyzokSzama]; for (int i = 0; i < versenyzokSzama; i++) { Console.WriteLine("Kérlek írd be az " + (i + 1) + ". versenyző nevét!"); egyDarabVersenyzoAdatai[i].nev = Console.ReadLine(); Console.WriteLine("Kérlek írd be az " + (i + 1) + ". versenyző által elért pontszámot!"); egyDarabVersenyzoAdatai[i].elertPont = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Kérlek írd be az " + (i + 1) + ". versenyző azonosítóját!"); egyDarabVersenyzoAdatai[i].versenyAzonosito = Convert.ToInt32(Console.ReadLine()); } do { Console.Clear(); Console.WriteLine("A következő gombok a következő parancsokat futtatják:\n 'L' - kilistázza a felvett versenyzőket\n 'D' - kilistázza a dobogósokat\n 'A' - kiadja az átlag pontszámot\n 'K' - kilép a programból"); char bevettParancs = Convert.ToChar(Console.ReadLine()); switch (bevettParancs) { //Felvitt adatok kiiratása case 'L': for (int i = 0; i < egyDarabVersenyzoAdatai.Length; i++) { Console.WriteLine("Név: " + egyDarabVersenyzoAdatai[i].nev + " Elért pontszám: " + egyDarabVersenyzoAdatai[i].elertPont + " Azonosító: " + egyDarabVersenyzoAdatai[i].versenyAzonosito); } break; //Dobogósok kiiratása case 'D': int elso = 0; int masodik = 0; int harmadik = 0; if (egyDarabVersenyzoAdatai[0].elertPont < egyDarabVersenyzoAdatai[1].elertPont) { elso = egyDarabVersenyzoAdatai[2].elertPont; masodik = egyDarabVersenyzoAdatai[1].elertPont; harmadik = egyDarabVersenyzoAdatai[0].elertPont; } else { elso = egyDarabVersenyzoAdatai[0].elertPont; masodik = egyDarabVersenyzoAdatai[1].elertPont; harmadik = egyDarabVersenyzoAdatai[2].elertPont; } #region Nem tudom miez /*for (int i = 3; i < egyDarabVersenyzoAdatai.Length; i++) { if (elso < egyDarabVersenyzoAdatai[i].elertPont) { masodik = elso; elso = egyDarabVersenyzoAdatai[i].elertPont; } else if (masodik < egyDarabVersenyzoAdatai[i].elertPont) { masodik = egyDarabVersenyzoAdatai[i].elertPont; } else if (harmadik < egyDarabVersenyzoAdatai[i].elertPont) { harmadik = egyDarabVersenyzoAdatai[i].elertPont; } }*/ #endregion Console.WriteLine("Az első helyezett pontja: " + elso); Console.WriteLine("A második helyezett pontja: " + masodik); Console.WriteLine("A harmadik helyezett pontja: " + harmadik); break; //Átlag pontszám case 'A': int atlag = 0; for (int i = 1; i < egyDarabVersenyzoAdatai.Length; i++) { atlag = atlag + egyDarabVersenyzoAdatai[i].elertPont; } atlag = atlag / egyDarabVersenyzoAdatai.Length; Console.WriteLine("Az elért pontszámok átlaga: " + atlag); break; //Kilépés case 'K': return; } } while (Console.ReadLine() != "K"); Console.ReadKey(); } } }
namespace Sentry.Extensibility; /// <summary> /// Provides a mechanism to convey network status. /// Used internally by some integrations. Not intended for public usage. /// </summary> /// <remarks> /// This must be public because we use it in Sentry.Maui, which can't use InternalsVisibleTo /// because MAUI assemblies are not strong-named. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public interface INetworkStatusListener { /// <summary> /// Gets a value that indicates whether the network is online. /// </summary> bool Online { get; } /// <summary> /// Asynchronously waits for the network to come online. /// </summary> /// <param name="cancellationToken">A token which cancels waiting.</param> Task WaitForNetworkOnlineAsync(CancellationToken cancellationToken); }
using System; using System.Windows.Forms; namespace WindowsFileManager { public partial class TextEditorForm : Form { private TextEditorController Controller = new TextEditorController(); public TextEditorForm(string path) { InitializeComponent(); Controller.LoadFile(path, richTextBox1, currentFileName); } private void TextEditor_Load(object sender, EventArgs e) { } private void NewToolStripMenuItem_Click(object sender, EventArgs e) { Controller.NewFile(richTextBox1, currentFileName); } private void OpenToolStripMenuItem_Click(object sender, EventArgs e) { Controller.OpenFile(richTextBox1, currentFileName); } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { Controller.SaveFile(richTextBox1, currentFileName); } private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { Controller.SaveFileAs(richTextBox1, currentFileName); } private void ExitToolStripMenuItem_Click(object sender, EventArgs e) { if (Controller.Close(richTextBox1, currentFileName)) { this.Close(); } } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Made by Denis Kochetkov, K-26", "About"); } private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { Controller.CheckTextBox(richTextBox1, currentFileName); } private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) { Controller.CheckTextBox(richTextBox1, currentFileName); } private void inverseRegisterToolStripMenuItem_Click(object sender, EventArgs e) { Controller.InverseRegister(richTextBox1); } private void mergeHTMLToolStripMenuItem_Click(object sender, EventArgs e) { Controller.MergeHTML(richTextBox1, currentFileName); } private void TextEditorForm_KeyDown(object sender, KeyEventArgs e) { if (e.Control) { if (e.KeyCode == Keys.S) { Controller.SaveFile(richTextBox1, currentFileName); } else if (e.KeyCode == Keys.N) { Controller.NewFile(richTextBox1, currentFileName); } else if (e.KeyCode == Keys.O) { Controller.OpenFile(richTextBox1, currentFileName); } } } private void correctMistakesToolStripMenuItem_Click(object sender, EventArgs e) { Controller.CorrectMistakes(richTextBox1); } } }
namespace WitsmlExplorer.Api.Jobs.Common { public class LogReference { public string WellUid { get; set; } public string WellboreUid { get; set; } public string LogUid { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class animmenu : MonoBehaviour { private bool toggle = true; public void MainMenuanim() { if (toggle==true) { GetComponent<Animator>().Play("MainMenuAnim"); toggle = false; } else if(toggle==false) { GetComponent<Animator>().Play("closemenu"); toggle = true; } } }
using GameManager; using TMPro; using UnityEngine; public class allowAbility : MonoBehaviour { public bool attack; public bool sprinting; public bool crouching; [SerializeField] private GameObject canvas; [SerializeField] private TextMeshProUGUI text; private bool changed = false; private PlayerMovement playerMovement; private string button; private string ability; private void Start() { if (sprinting && !GameManager_Master.Instance.hasSprint) { this.enabled = false; } else if (attack && !GameManager_Master.Instance.hasAttack) { this.enabled = false; } else if (crouching && !GameManager_Master.Instance.hasCrouch) { this.enabled = false; } } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { playerMovement = other.GetComponent<PlayerMovement>(); if (playerMovement != null) { if (sprinting) { playerMovement.allowSprinting = true; GameManager_Master.Instance.hasSprint = true; changed = true; button = "SHIFT"; ability = "Sprint"; } else if (attack) { playerMovement.allowAttack = true; GameManager_Master.Instance.hasAttack = true; changed = true; button = "CTRL or Left Click"; ability = "Attack"; } else if (crouching) { playerMovement.allowCrouch = true; GameManager_Master.Instance.hasCrouch = true; changed = true; button = "ALT or Right Click"; ability = "Crouch"; } if (changed) { canvas.SetActive(true); text.SetText("You can now press " + button + " to " + ability); playerMovement.enabled = false; Time.timeScale = 0; } } changed = false; } } }
using System.Web.UI; using System.Web.UI.WebControls; using HTB.Database; namespace HTB.v2.intranetx.global_files { public partial class CtlLookupDealer : UserControl { public string ComponentName = ""; public void SetComponentName(string name) { ComponentName = name; } public void SetNextFocusableComponentId(string componentId) { hdnNextFocusId.Value = componentId; } public string GetDealerID() { return hdnDealerId.Value; } public void SetDealer(tblAutoDealer dealer) { txtDealerSearch.Text = dealer.AutoDealerName; lblDealerAddress.Text = "<strong>Addresse</strong>: " + dealer.AutoDealerStrasse + ", " + dealer.AutoDealerPLZ + ", " + dealer.AutoDealerOrt; hdnDealerId.Value = dealer.AutoDealerID.ToString(); } public TextBox GetTextBox() { return txtDealerSearch; } public void Clear() { txtDealerSearch.Text = ""; lblDealerAddress.Text = ""; hdnDealerId.Value = ""; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class newCube : MonoBehaviour { // Use this for initialization void Start () { print(GetComponent<Transform>().position); int myNumber = 5; GetComponent<Renderer>().material.color = Color.red; } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Facade { class LegacyFacade { SistemaFacturacion s = new SistemaFacturacion(); SistemaDespacho d = new SistemaDespacho(); public DateTime CalcularFechaPago(Factura f) { s.EstablecerFechaDePago(f); d.PlanificarDespacho(f.FechaPago); return f.FechaPago; } } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Different types of usages for an Atom Collection Reference. /// </summary> public class AtomCollectionReferenceUsage { public const int COLLECTION = 0; public const int COLLECTION_INSTANCER = 1; } /// <summary> /// Reference of type `AtomCollection`. Inherits from `AtomBaseReference`. /// </summary> [Serializable] public class AtomCollectionReference : AtomBaseReference, IGetValue<IAtomCollection> { /// <summary> /// Get value as an `IAtomCollection`. Needed in order to inject Collection References into the Variable Instancer class. /// </summary> /// <returns>The value as an `IAtomList`.</returns> public IAtomCollection GetValue() => Collection != null ? Collection.GetValue() : null; /// <summary> /// Get the value for the Reference. /// </summary> /// <value>The value of type `AtomCollection`.</value> public AtomCollection Collection { get { switch (_usage) { case (AtomCollectionReferenceUsage.COLLECTION_INSTANCER): return _instancer == null ? default(AtomCollection) : _instancer.Variable; case (AtomCollectionReferenceUsage.COLLECTION): default: return _collection; } } } /// <summary> /// Variable used if `Usage` is set to `COLLECTION`. /// </summary> [SerializeField] private AtomCollection _collection = default(AtomCollection); /// <summary> /// Variable Instancer used if `Usage` is set to `COLLECTION_INSTANCER`. /// </summary> [SerializeField] private AtomCollectionInstancer _instancer = default(AtomCollectionInstancer); } }
namespace com.Sconit.Web.Controllers.INP { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using com.Sconit.Entity.INP; using com.Sconit.Service; using com.Sconit.Web.Models; using com.Sconit.Web.Models.SearchModels.INP; using com.Sconit.Utility; using Telerik.Web.Mvc; using com.Sconit.Entity.MD; using com.Sconit.Entity.INV; using com.Sconit.Entity.SYS; using System; using AutoMapper; using com.Sconit.Service.Impl; using com.Sconit.Entity.Exception; using com.Sconit.Entity.CUST; using System.Text; using com.Sconit.Entity; using com.Sconit.PrintModel.INP; using com.Sconit.Utility.Report; using com.Sconit.Entity.ORD; public class InspectionOrderController : WebAppBaseController { // // GET: /InspectionOrder/ //public IGenericMgr genericMgr { get; set; } public IInspectMgr inspectMgr { get; set; } //public ISystemMgr systemMgr { get; set; } //public IOrderMgr orderMgr { get; set; } //public IReportGen reportGen { get; set; } private static string selectStatement = "select i from InspectMaster as i"; private static string selectCountStatement = "select count(*) from InspectMaster as i"; private static string selectInspectDetailCountStatement = "select count(*) from InspectDetail as id"; private static string selectInspectDetailSearchModelStatement = "select id from InspectDetail as id "; private static string selectInspectDetailStatement = "select i from InspectDetail as i where i.InspectNo=?"; private static string selectJudgeInspectDetailStatement = "select i from InspectDetail as i where i.InspectNo=? and i.IsJudge=False"; private static string InspectResultSelectStatement = "select i from InspectResult as i"; private static string InspectResultSelectCountStatement = "select count(*) from InspectResult as i"; #region view [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] public ActionResult Index() { return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] [GridAction] public ActionResult List(GridCommand command, InspectMasterSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { TempData["_AjaxMessage"] = ""; } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } if (searchCacheModel.isBack == true) { ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page; } ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] [GridAction(EnableCustomBinding = true)] public ActionResult _AjaxList(GridCommand command, InspectMasterSearchModel searchModel) { this.GetCommand(ref command, searchModel); if (!this.CheckSearchModelIsNull(searchModel)) { return PartialView(new GridModel(new List<InspectMaster>())); } SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel, string.Empty); return PartialView(GetAjaxPageData<InspectMaster>(searchStatementModel, command)); } [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] public ActionResult Edit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { return View("Edit", string.Empty, id); } } [HttpGet] [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] public ActionResult _Edit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { InspectMaster inspectMaster = this.genericMgr.FindById<InspectMaster>(id); return PartialView(inspectMaster); } } [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] public ActionResult InspectionOrderDetailEdit(string inspectNo) { InspectMaster inspectMaster = this.genericMgr.FindById<InspectMaster>(inspectNo); if (inspectMaster.Type == com.Sconit.CodeMaster.InspectType.Barcode) { ViewBag.HideHuId = false; } else { ViewBag.HideHuId = true; } ViewBag.inspectNo = inspectNo; return PartialView(); } [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_View")] public ActionResult _InspectionOrderDetailList(string inspectNo) { IList<InspectDetail> inspectDetailList = genericMgr.FindAll<InspectDetail>(selectInspectDetailStatement, inspectNo); IList<FailCode> failCodeList = genericMgr.FindAll<FailCode>(); foreach (InspectDetail inspectDetail in inspectDetailList) { foreach (FailCode failCode in failCodeList) { if (inspectDetail.FailCode == failCode.Code) { inspectDetail.FailCode = failCode.CodeDescription; } } if (!string.IsNullOrWhiteSpace(inspectDetail.HuId)) { Hu huData = genericMgr.FindById<Hu>(inspectDetail.HuId); inspectDetail.ExpireDate = huData.ExpireDate; inspectDetail.SupplierLotNo = huData.SupplierLotNo; } } return View(new GridModel(inspectDetailList)); } [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_View,Url_InspectionOrder_Judge")] public ActionResult InspectionResult(GridCommand command, InspectResultSearchModel searchModel) { ViewBag.Item = searchModel.Item; TempData["InspectResultSearchModel"] = searchModel; ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return PartialView(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_InspectionOrder_View,Url_InspectionOrder_Judge")] public ActionResult _AjaxInspectionResultList(GridCommand command, InspectResultSearchModel searchModel) { SearchStatementModel searchStatementModel = this.InspectResultPrepareSearchStatement(command, searchModel); GridModel<InspectResult> list = GetAjaxPageData<InspectResult>(searchStatementModel, command); IList<FailCode> failCodeList = genericMgr.FindAll<FailCode>(); foreach (InspectResult inspectResult in list.Data) { foreach (FailCode failCode in failCodeList) { if (inspectResult.FailCode == failCode.Code) { inspectResult.FailCodeDescription = failCode.CodeDescription; inspectResult.CurrentFailCode = inspectResult.FailCode; inspectResult.CurrentIsHandle = inspectResult.IsHandle; } } if (!string.IsNullOrWhiteSpace(inspectResult.HuId)) { Hu huData = genericMgr.FindById<Hu>(inspectResult.HuId); inspectResult.ExpireDate = huData.ExpireDate; inspectResult.SupplierLotNo = huData.SupplierLotNo; } } return PartialView(list); } #endregion #region new [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult New() { if (TempData["InspectDetailList"] != null) { TempData["InspectDetailList"] = null; } return View(); } [AcceptVerbs(HttpVerbs.Post)] [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public JsonResult New(string region, string locationFrom, [Bind(Prefix = "inserted")]IEnumerable<InspectDetail> insertedInspectDetails) { BusinessException businessException = new BusinessException(); try { ViewBag.Region = region; ViewBag.LocationFrom = locationFrom; #region orderDetailList if (string.IsNullOrEmpty(locationFrom)) { throw new BusinessException(Resources.INP.InspectDetail.Errors_InspectDetail_LocationRequired); } IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); if (insertedInspectDetails != null && insertedInspectDetails.Count() > 0) { int i = 1; foreach (InspectDetail inspectDetail in insertedInspectDetails) { if (string.IsNullOrEmpty(inspectDetail.Item)) { businessException.AddMessage(Resources.EXT.ControllerLan.Con_ItemCanNotBeEmpty + (i++) + Resources.EXT.ControllerLan.Con_RowItemCanNotBeEmpty); continue; } if (inspectDetail.InspectQty <= 0) { businessException.AddMessage(Resources.EXT.ControllerLan.Con_ItemCanNotBeEmpty + (i++) + Resources.EXT.ControllerLan.Con_InspectionQuantityMustGreaterThenZero); continue; } //if (string.IsNullOrEmpty(inspectDetail.FailCode)) //{ // businessException.AddMessage("第" + (i++) + "失效代码为必填。"); // continue; //} Item item = this.genericMgr.FindById<Item>(inspectDetail.Item); inspectDetail.ItemDescription = item.Description; inspectDetail.UnitCount = item.UnitCount; inspectDetail.ReferenceItemCode = item.ReferenceCode; inspectDetail.Uom = item.Uom; inspectDetail.LocationFrom = locationFrom; inspectDetail.CurrentLocation = locationFrom; inspectDetail.BaseUom = item.Uom; inspectDetail.UnitQty = 1; inspectDetailList.Add(inspectDetail); } } #endregion if (businessException.HasMessage) { throw businessException; } if (inspectDetailList != null && inspectDetailList.Count == 0) { throw new BusinessException(Resources.INP.InspectDetail.Errors_InspectDetail_Required); } InspectMaster inspectMaster = new InspectMaster(); inspectMaster.Region = region; inspectMaster.InspectDetails = inspectDetailList; inspectMaster.Type = com.Sconit.CodeMaster.InspectType.Quantity; inspectMaster.IsATP = false; inspectMgr.CreateAndReject(inspectMaster); SaveSuccessMessage(Resources.INP.InspectMaster.InspectMaster_Added); return Json(new object[] { inspectMaster.InspectNo }); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult _InspectionOrderDetail() { //IList<Item> items = genericMgr.FindAll<Item>(selecItemStatement, true); //ViewData.Add("items", items); IList<Uom> uoms = genericMgr.FindAll<Uom>(); ViewData.Add("uoms", uoms); return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult _SelectBatchEditing() { IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); return View(new GridModel(inspectDetailList)); } [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult _WebInspectDetail(string itemCode) { if (!string.IsNullOrEmpty(itemCode)) { IList<WebOrderDetail> webOrderDetailList = new List<WebOrderDetail>(); WebOrderDetail webOrderDetail = new WebOrderDetail(); Item item = genericMgr.FindById<Item>(itemCode); if (item != null) { webOrderDetail.Item = item.Code; webOrderDetail.ItemDescription = item.Description; webOrderDetail.UnitCount = item.UnitCount; webOrderDetail.Uom = item.Uom; webOrderDetail.ReferenceItemCode = item.ReferenceCode; } return this.Json(webOrderDetail); } return null; } #region New ByScanHu [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public void ItemHuIdScan(string HuId) { IList<InspectDetail> InspectDetailList = (IList<InspectDetail>)TempData["InspectDetailList"]; try { InspectDetailList = inspectMgr.AddInspectDetail(HuId, InspectDetailList); } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.GetMessages()[0].GetMessageString()); } TempData["InspectDetailList"] = InspectDetailList; } public ActionResult _InspectionOrderDetailScanHu() { return PartialView(); } [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult _SelectInspectionOrderDetail() { IList<InspectDetail> InspectionDetailList = new List<InspectDetail>(); if (TempData["InspectDetailList"] != null) { InspectionDetailList = (IList<InspectDetail>)TempData["InspectDetailList"]; } TempData["InspectDetailList"] = InspectionDetailList; return PartialView(new GridModel(InspectionDetailList)); } [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public ActionResult _DeleteInspectionDetail(string HuId) { IList<InspectDetail> InspectDetailList = (IList<InspectDetail>)TempData["InspectDetailList"]; IList<InspectDetail> q = InspectDetailList.Where(v => v.HuId != HuId).ToList(); TempData["InspectDetailList"] = q; return PartialView(new GridModel(q)); } public void _CleanInspectionDetail() { if (TempData["InspectDetailList"] != null) { TempData["InspectDetailList"] = null; } } [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public string CreateInspectionDetail(string ItemStr, string HuIdStr, string LocationStr, string InspectQtyStr, string FailCodeStr, string NoteStr) { try { if (!string.IsNullOrEmpty(ItemStr)) { string[] itemArray = ItemStr.Split(','); string[] huidArray = HuIdStr.Split(','); string[] locationArray = LocationStr.Split(','); string[] inspectqtyArray = InspectQtyStr.Split(','); string[] falicodeArray = FailCodeStr.Split(','); string[] noteArray = NoteStr.Split(','); IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); int i = 0; foreach (string itemcode in itemArray) { InspectDetail inspectDetail = new InspectDetail(); Item item = this.genericMgr.FindById<Item>(itemcode); inspectDetail.ItemDescription = item.Description; inspectDetail.UnitCount = item.UnitCount; inspectDetail.ReferenceItemCode = item.ReferenceCode; inspectDetail.Uom = item.Uom; inspectDetail.BaseUom = item.Uom; inspectDetail.UnitQty = 1; inspectDetail.LocationFrom = locationArray[i]; inspectDetail.CurrentLocation = locationArray[i]; inspectDetail.FailCode = falicodeArray[i]; inspectDetail.Note = noteArray[i]; inspectDetail.HuId = huidArray[i]; inspectDetail.InspectQty = Convert.ToDecimal(inspectqtyArray[i]); i++; inspectDetailList.Add(inspectDetail); } if (inspectDetailList != null && inspectDetailList.Count == 0) { throw new BusinessException(Resources.INP.InspectDetail.Errors_InspectDetail_Required); } InspectMaster inspectMaster = new InspectMaster(); inspectMaster.InspectDetails = inspectDetailList; inspectMaster.Type = com.Sconit.CodeMaster.InspectType.Barcode; inspectMaster.IsATP = false; inspectMgr.CreateInspectMaster(inspectMaster); SaveSuccessMessage(Resources.INP.InspectMaster.InspectMaster_Added); this._CleanInspectionDetail(); return inspectMaster.InspectNo; } else { throw new BusinessException(Resources.INP.InspectDetail.Errors_InspectDetail_Required); } } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.GetMessages()[0].GetMessageString()); return string.Empty; } } #endregion #endregion #region Judge [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult JudgeIndex() { return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] [GridAction] public ActionResult JudgeList(GridCommand command, InspectMasterSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel); if (searchCacheModel.isBack == true) { ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page; } ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] [GridAction(EnableCustomBinding = true)] public ActionResult _AjaxJudgeList(GridCommand command, InspectMasterSearchModel searchModel) { string replaceFrom = "_AjaxJudgeList"; string replaceTo = "JudgeList"; this.GetCommand(ref command, searchModel, replaceFrom, replaceTo); string whereStatement = " where i.Status in ( " + (int)com.Sconit.CodeMaster.InspectStatus.Submit + "," + (int)com.Sconit.CodeMaster.InspectStatus.InProcess + ")"; SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel, whereStatement); return PartialView(GetAjaxPageData<InspectMaster>(searchStatementModel, command)); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult JudgeEdit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { return View("JudgeEdit", string.Empty, id); } } [HttpGet] [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult _JudgeEdit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { InspectMaster inspectMaster = this.genericMgr.FindById<InspectMaster>(id); inspectMaster.InspectStatusDescription = systemMgr.GetCodeDetailDescription(com.Sconit.CodeMaster.CodeMaster.InspectStatus, ((int)inspectMaster.Status).ToString()); return PartialView(inspectMaster); } } [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult InspectionOrderDetailJudge(string inspectNo, com.Sconit.CodeMaster.InspectType inspectType) { ViewBag.inspectNo = inspectNo; ViewBag.inspectType = inspectType; return PartialView(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult InspectionOrderDetailJudgeWithHu(string inspectNo) { ViewBag.inspectNo = inspectNo; return PartialView(); } [AcceptVerbs(HttpVerbs.Post)] [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public ActionResult _SelectJudgeBatchEditing(string inspectNo, com.Sconit.CodeMaster.InspectType inspectType) { IList<InspectDetail> inspectDetailList = genericMgr.FindAll<InspectDetail>(selectJudgeInspectDetailStatement, inspectNo); if (inspectType == Sconit.CodeMaster.InspectType.Barcode) { inspectDetailList = inspectDetailList.GroupBy(p => p.Item, (k, g) => new { k, g }).Select(p => { var inspectDetail = p.g.First(); inspectDetail.InspectQty = p.g.Sum(q => q.InspectQty); inspectDetail.QualifyQty = p.g.Sum(q => q.QualifyQty); inspectDetail.RejectQty = p.g.Sum(q => q.RejectQty); return inspectDetail; }).ToList(); } foreach (var inspectDetail in inspectDetailList) { inspectDetail.CurrentQty = inspectDetail.InspectQty - inspectDetail.QualifyQty - inspectDetail.RejectQty; if (!string.IsNullOrWhiteSpace(inspectDetail.HuId)) { Hu huData = genericMgr.FindById<Hu>(inspectDetail.HuId); inspectDetail.ExpireDate = huData.ExpireDate; inspectDetail.SupplierLotNo = huData.SupplierLotNo; } } return View(new GridModel(inspectDetailList)); } [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_SaveInspectResult")] public string SaveInspectResult([Bind(Prefix = "updated")]IEnumerable<InspectResult> updatedInspectResults) { try { inspectMgr.SaveInspectResult(updatedInspectResults.ToList()); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_InspectionResultSavedSuccessfully); return string.Empty; } catch (Exception ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.Message); return string.Empty; } } [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public JsonResult Judge(string inspectNo, com.Sconit.CodeMaster.InspectType inspectType, [Bind(Prefix = "updated")]IEnumerable<InspectDetail> updatedInspectDetails) { try { updatedInspectDetails = updatedInspectDetails.Where(d => d.CurrentQty > 0 && !string.IsNullOrWhiteSpace(d.JudgeFailCode)); if (updatedInspectDetails == null || updatedInspectDetails.Count() == 0) { throw new BusinessException(Resources.EXT.ControllerLan.Con_LackJudgeDetail); } List<InspectDetail> inspectDetailList = new List<InspectDetail>(); if (inspectType == Sconit.CodeMaster.InspectType.Barcode) { var huInspectDetailList = genericMgr.FindAll<InspectDetail>(selectJudgeInspectDetailStatement, inspectNo) .GroupBy(p => p.Item, (k, g) => new { k, g }).ToDictionary(d => d.k, d => d.g); foreach (var updatedInspectDetail in updatedInspectDetails) { inspectDetailList.AddRange(huInspectDetailList.ValueOrDefault(updatedInspectDetail.Item) .Select(p => { p.CurrentQty = p.CurrentInspectQty; p.JudgeFailCode = updatedInspectDetail.JudgeFailCode; p.CurrentInspectResultNote = updatedInspectDetail.CurrentInspectResultNote; return p; })); } } else { inspectDetailList = updatedInspectDetails.ToList(); } inspectMgr.JudgeInspectDetail(inspectDetailList); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_InspectionOrderJudgeSuccessfully, inspectNo); return Json(inspectNo); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } //[HttpPost] //[SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] //public string JudgeQualify(string inspectNo, string idStr) //{ // string failCodeStr = string.Empty; // return BatchJudge(inspectNo, idStr, true, failCodeStr, string.Empty); //} [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public string JudgeReject(string inspectNo, string idStr, string failCodeStr, string notes) { return BatchJudge(inspectNo, idStr, failCodeStr, notes); } [HttpPost] [SconitAuthorize(Permissions = "Url_InspectionOrder_Judge")] public JsonResult JudgeHu(string inspectNo, string idStr, string failCodeStr, string notes) { try { string[] idArr = idStr.Split(','); string[] noteArr = null; if (!string.IsNullOrEmpty(notes)) { noteArr = notes.Split(','); } string[] failCodeArr = null; if (!string.IsNullOrEmpty(failCodeStr)) { failCodeArr = failCodeStr.Split(','); } IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); for (int i = 0; i < idArr.Length; i++) { InspectDetail inspectDetail = genericMgr.FindById<InspectDetail>(Convert.ToInt32(idArr[i])); inspectDetail.CurrentQty = inspectDetail.InspectQty; if (failCodeArr != null) { inspectDetail.JudgeFailCode = failCodeArr[i]; } if (noteArr != null) { inspectDetail.CurrentInspectResultNote = noteArr[i]; } inspectDetailList.Add(inspectDetail); } inspectMgr.JudgeInspectDetail(inspectDetailList); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_InspectionOrderJudgeSuccessfully, inspectNo); return Json(inspectNo); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } #endregion #region transfer [GridAction] [SconitAuthorize(Permissions = "Url_InspectionOrder_Transfer")] public ActionResult Transfer() { return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Transfer")] public ActionResult _TransferDetailList(string inspectNo) { IList<InspectDetail> inspectDetailList = genericMgr.FindAll<InspectDetail>(selectJudgeInspectDetailStatement, inspectNo); return PartialView(inspectDetailList); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Transfer")] public JsonResult CreateInspectTransfer(string location, string idStr, string qtyStr) { try { #region 检查库位 if (string.IsNullOrEmpty(location)) { throw new BusinessException(Resources.EXT.ControllerLan.Con_LocationCanNotBeEmpty); } Location locTo = genericMgr.FindById<Location>(location); #endregion if (string.IsNullOrEmpty(idStr)) { throw new BusinessException(Resources.EXT.ControllerLan.Con_InspectionDetailCanNotBeEmpty); } string[] idArr = idStr.Split(','); IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); foreach (string id in idArr) { InspectDetail inspetDetail = genericMgr.FindById<InspectDetail>(Convert.ToInt32(id)); inspectDetailList.Add(inspetDetail); } orderMgr.CreateInspectTransfer(locTo, inspectDetailList); object obj = new { SuccessMessage = string.Format(Resources.INP.InspectMaster.InspectMaster_Transfered) }; return Json(obj); } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.GetMessages()[0].GetMessageString()); return Json(null); } } #endregion #region detail [SconitAuthorize(Permissions = "Url_InspectionOrder_Detail")] public ActionResult DetailIndex() { return View(); } [SconitAuthorize(Permissions = "Url_InspectionOrder_Detail")] public ActionResult DetailList(GridCommand command, InspectMasterSearchModel searchModel) { if (this.CheckSearchModelIsNull(searchModel)) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel); IList<InspectDetail> InspectDetailList = new List<InspectDetail>(); InspectDetailList = GetDetailList(command, searchModel); int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage)); if (InspectDetailList.Count > value) { SaveWarningMessage(string.Format(Resources.EXT.ControllerLan.Con_DataExceedRow, value)); } return View(InspectDetailList.Take(value)); } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); return View(new List<InspectDetail>()); } //return View(list.Take(value)); } #region 明细导出 private List<InspectDetail> GetDetailList(GridCommand command, InspectMasterSearchModel searchModel) { TempData["_AjaxMessage"] = ""; var failCodeDic = this.genericMgr.FindAll<FailCode>().ToDictionary(d => d.Code, d => d); string hql = PrepareDetailSearchStatement(command, searchModel); IList<InspectDetail> InspectDetailList = new List<InspectDetail>(); IList<object[]> objectList = this.queryMgr.FindAllWithNativeSql<object[]>(hql); InspectDetailList = (from tak in objectList select new InspectDetail { Id = (int)tak[0], InspectNo = (string)tak[1], Sequence = (int)tak[2], Item = (string)tak[3], ItemDescription = (string)tak[4], ReferenceItemCode = (string)tak[5], UnitCount = (decimal)tak[6], Uom = (string)tak[7], BaseUom = (string)tak[8], UnitQty = (decimal)tak[9], HuId = (string)tak[10], LotNo = (string)tak[11], LocationFrom = (string)tak[12], CurrentLocation = (string)tak[13], InspectQty = (decimal)tak[14], QualifyQty = (decimal)tak[15], RejectQty = (decimal)tak[16], IsJudge = (bool)tak[17], CreateUserId = (int)tak[18], CreateUserName = (string)tak[19], CreateDate = (DateTime)tak[20], LastModifyUserId = (int)tak[21], LastModifyUserName = (string)tak[22], LastModifyDate = (DateTime)tak[23], Version = (int)tak[24], ManufactureParty = (string)tak[25], WMSSeq = (string)tak[26], IpDetailSequence = (int)tak[27], ReceiptDetailSequence = (int)tak[28], Note = (string)tak[29], FailCode = (string)tak[30], FailCodeDescription = string.IsNullOrWhiteSpace((string)tak[30]) ? null : failCodeDic.ValueOrDefault((string)tak[30]).CodeDescription, HandledQty = (decimal)tak[31], }).ToList(); return (List<InspectDetail>)InspectDetailList; } [SconitAuthorize(Permissions = "Url_InspectionOrder_Detail")] public void ExportXLS(InspectMasterSearchModel searchModel) { int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage)); GridCommand command = new GridCommand(); command.Page = 1; command.PageSize = !this.CheckSearchModelIsNull(searchModel) ? 0 : value; IList<InspectDetail> InspectDetailList = new List<InspectDetail>(); InspectDetailList = GetDetailList(command, searchModel); if (InspectDetailList.Count > value) { SaveWarningMessage(string.Format(Resources.EXT.ControllerLan.Con_DataExceedRow, value)); } ExportToXLS<InspectDetail>("InspectOrderDetail.xls", InspectDetailList); } #endregion #region 打印导出 public void SaveToClient(string inspectNo) { InspectMaster inspectMaster = queryMgr.FindById<InspectMaster>(inspectNo); IList<InspectDetail> inspectDetails = queryMgr.FindAll<InspectDetail>("select id from InspectDetail as id where id.InspectNo=?", inspectNo); inspectMaster.InspectDetails = inspectDetails; PrintInspectMaster printInspectMaster = Mapper.Map<InspectMaster, PrintInspectMaster>(inspectMaster); var failCodeDic = this.genericMgr.FindAll<FailCode>().ToDictionary(d => d.Code, d => d); var inspectResults = this.genericMgr.FindAll<InspectResult>(" from InspectResult as i where i.InspectNo=? ", inspectNo).ToDictionary(d=>d.InspectDetailId,d=>d); foreach (var inspectDetail in printInspectMaster.InspectDetails) { inspectDetail.FailCode = inspectResults.ValueOrDefault(inspectDetail.Id) == null ? inspectDetail.FailCode : inspectResults.ValueOrDefault(inspectDetail.Id).FailCode; if (!string.IsNullOrWhiteSpace(inspectDetail.FailCode)) { inspectDetail.FailCode = failCodeDic[inspectDetail.FailCode].CodeDescription; } } IList<object> data = new List<object>(); data.Add(printInspectMaster); data.Add(printInspectMaster.InspectDetails); //string reportFileUrl = reportGen.WriteToFile(orderMaster.OrderTemplate, data); reportGen.WriteToClient("InspectOrder.xls", data, inspectMaster.InspectNo + ".xls"); //return reportFileUrl; //reportGen.WriteToFile(orderMaster.OrderTemplate, data); } public string Print(string inspectNo) { InspectMaster inspectMaster = queryMgr.FindById<InspectMaster>(inspectNo); IList<InspectDetail> inspectDetails = queryMgr.FindAll<InspectDetail>("select id from InspectDetail as id where id.InspectNo=?", inspectNo); inspectMaster.InspectDetails = inspectDetails; PrintInspectMaster printInspectMaster = Mapper.Map<InspectMaster, PrintInspectMaster>(inspectMaster); IList<object> data = new List<object>(); var failCodeDic = this.genericMgr.FindAll<FailCode>().ToDictionary(d => d.Code, d => d); foreach (var inspectDetail in printInspectMaster.InspectDetails) { //Exception occurs when "FailCode" is null ,here eliminate exception since null value is rational inspectDetail.FailCode = this.genericMgr.FindAll<InspectResult>(" from InspectResult as i where i.InspectDetailId=? ", inspectDetail.Id).FirstOrDefault().FailCode ?? inspectDetail.FailCode; if (!string.IsNullOrWhiteSpace(inspectDetail.FailCode)) { inspectDetail.FailCode = failCodeDic[inspectDetail.FailCode].CodeDescription; } } data.Add(printInspectMaster); data.Add(printInspectMaster.InspectDetails); string reportFileUrl = reportGen.WriteToFile("InspectOrder.xls", data); //reportGen.WriteToClient(orderMaster.OrderTemplate, data, orderMaster.OrderTemplate); return reportFileUrl; //reportGen.WriteToFile(orderMaster.OrderTemplate, data); } #endregion #endregion #region private method private SearchStatementModel InspectResultPrepareSearchStatement(GridCommand command, InspectResultSearchModel searchModel) { string whereStatement = "where i.InspectNo = '" + searchModel.InspectNo + "'"; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("Item", searchModel.Item, HqlStatementHelper.LikeMatchMode.Start, "i", ref whereStatement, param); if (command.SortDescriptors.Count > 0) { if (command.SortDescriptors[0].Member == "JudgeResultDescription") { command.SortDescriptors[0].Member = "JudgeResult"; } else if (command.SortDescriptors[0].Member == "DefectDescription") { command.SortDescriptors[0].Member = "Defect"; } } string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = InspectResultSelectCountStatement; searchStatementModel.SelectStatement = InspectResultSelectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } private string PrepareDetailSearchStatement(GridCommand command, InspectMasterSearchModel searchModel) { StringBuilder Sb = new StringBuilder(); string whereStatement = "select detailResult.*,isnull(rest.handleQty,0) from ( select * from INP_InspectDet as id where 1=1"; if (searchModel.IpNo != null || searchModel.ReceiptNo != null || searchModel.WMSNo != null) { whereStatement += " and exists (select 1 from INP_InspectMstr as i where i.InpNo= id.InpNo "; } if (searchModel.IpNo != null && searchModel.IpNo != "") { whereStatement += " and i.IpNo='" + searchModel.IpNo + "'"; } if (searchModel.WMSNo != null && searchModel.WMSNo != "") { whereStatement += " and i.WMSNo='" + searchModel.WMSNo + "'"; } if (searchModel.ReceiptNo != null && searchModel.ReceiptNo != "") { whereStatement += " and i.RecNo='" + searchModel.ReceiptNo + "'"; } if (searchModel.IpNo != null || searchModel.ReceiptNo != null || searchModel.WMSNo != null) { whereStatement += ")"; } Sb.Append(whereStatement); if (searchModel.InspectNo != null) { Sb.Append(string.Format(" and id.InpNo = '{0}'", searchModel.InspectNo)); } if (!string.IsNullOrEmpty(searchModel.Item)) { Sb.Append(string.Format(" and id.Item ='{0}'", searchModel.Item)); } if (searchModel.CreateUserName != null) { Sb.Append(string.Format(" and id.CreateUserNm = '{0}'", searchModel.CreateUserName)); } if (searchModel.StartDate != null & searchModel.EndDate != null) { Sb.Append(string.Format(" and id.CreateDate between '{0}' and '{1}'", new object[] { searchModel.StartDate, searchModel.EndDate })); } else if (searchModel.StartDate != null & searchModel.EndDate == null) { Sb.Append(string.Format(" and id.CreateDate >= '{0}'", searchModel.StartDate)); } else if (searchModel.StartDate == null & searchModel.EndDate != null) { Sb.Append(string.Format(" and id.CreateDate <= '{0}'", searchModel.EndDate)); } Sb.Append(@" ) as detailResult left join (select ir.inpdetid,sum(ir.HandleQty) as handleQty from INP_InspectResult as ir group by inpdetid) as rest on detailResult.Id=rest.inpdetid order by detailResult.CreateDate desc"); return Sb.ToString(); } private SearchStatementModel PrepareSearchStatement(GridCommand command, InspectMasterSearchModel searchModel, string whereStatement) { IList<object> param = new List<object>(); SecurityHelper.AddRegionPermissionStatement(ref whereStatement, "i", "Region"); HqlStatementHelper.AddLikeStatement("InspectNo", searchModel.InspectNo, HqlStatementHelper.LikeMatchMode.End, "i", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("CreateUserName", searchModel.CreateUserName, HqlStatementHelper.LikeMatchMode.Start, "i", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Status", searchModel.Status, "i", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Region", searchModel.Region, "i", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Type", searchModel.Type, "i", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("IpNo", searchModel.IpNo, HqlStatementHelper.LikeMatchMode.End, "i", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("WMSNo", searchModel.WMSNo, HqlStatementHelper.LikeMatchMode.End, "i", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("ReceiptNo", searchModel.ReceiptNo, HqlStatementHelper.LikeMatchMode.End, "i", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Type", searchModel.Type, "i", ref whereStatement, param); if (searchModel.StartDate != null & searchModel.EndDate != null) { HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.StartDate, searchModel.EndDate, "i", ref whereStatement, param); } else if (searchModel.StartDate != null & searchModel.EndDate == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartDate, "i", ref whereStatement, param); } else if (searchModel.StartDate == null & searchModel.EndDate != null) { HqlStatementHelper.AddLeStatement("CreateDate", searchModel.EndDate, "i", ref whereStatement, param); } if (command.SortDescriptors.Count > 0) { if (command.SortDescriptors[0].Member == "InspectTypeDescription") { command.SortDescriptors[0].Member = "Type"; } else if (command.SortDescriptors[0].Member == "InspectStatusDescription") { command.SortDescriptors[0].Member = "Status"; } } string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); if (command.SortDescriptors.Count == 0) { sortingStatement = " order by i.CreateDate desc"; } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } private string BatchJudge(string inspectNo, string idStr, string failCodeStr, string notes) { try { string[] idArr = idStr.Split(','); string[] noteArr = null; if (!string.IsNullOrEmpty(notes)) { noteArr = notes.Split(','); } string[] failCodeArr = null; if (!string.IsNullOrEmpty(failCodeStr)) { failCodeArr = failCodeStr.Split(','); } IList<InspectDetail> inspectDetailList = new List<InspectDetail>(); for (int i = 0; i < idArr.Length; i++) { InspectDetail inspectDetail = genericMgr.FindById<InspectDetail>(Convert.ToInt32(idArr[i])); inspectDetail.CurrentQty = inspectDetail.InspectQty; if (failCodeArr != null) { inspectDetail.JudgeFailCode = failCodeArr[i]; } if (noteArr != null) { inspectDetail.CurrentInspectResultNote = noteArr[i]; } inspectDetailList.Add(inspectDetail); } inspectMgr.JudgeInspectDetail(inspectDetailList); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_JudgeSuccessfully); return inspectNo; } catch (Exception ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.Message); return string.Empty; } } #endregion [SconitAuthorize(Permissions = "Url_InspectionOrder_New")] public string CreateRefReceiptNoInspectMaster(string ReceiptNo) { try { IList<ReceiptMaster> receiptList = genericMgr.FindAll<ReceiptMaster>(string.Format("from ReceiptMaster r where r.ReceiptNo='{0}' ", ReceiptNo)); if (receiptList.Count == 0) { throw new BusinessException(Resources.EXT.ControllerLan.Con_ReceiveOrderNumberNotExits); } ReceiptMaster receiptEntity = receiptList[0]; receiptEntity.ReceiptDetails = genericMgr.FindAll<ReceiptDetail>(string.Format(" from ReceiptDetail r where r.ReceiptNo='{0}'", ReceiptNo)); foreach (ReceiptDetail ReceiptDetailEntity in receiptEntity.ReceiptDetails) { ReceiptDetailEntity.IsInspect = true; ReceiptDetailEntity.ReceiptLocationDetails = genericMgr.FindAll<ReceiptLocationDetail>(string.Format(" from ReceiptLocationDetail r where r.ReceiptNo='{0}'", ReceiptNo)); } InspectMaster inspectMaster = inspectMgr.TransferReceipt2Inspect(receiptEntity); inspectMgr.CreateInspectMaster(inspectMaster); return string.Format(Resources.EXT.ControllerLan.Con_InspectionOrderNumberGeneratedSuccessfully, inspectMaster.InspectNo); } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; string messages = ""; for (int i = 0; i < ex.GetMessages().Count; i++) { messages += ex.GetMessages()[i].GetMessageString(); } Response.Write(messages); return string.Empty; } } } }
using System.Collections.Generic; using System.Globalization; using Infrastructure.ApplicationSettings; namespace Tests.Utils.ApplicationSettings { /// <summary> /// Application settings class used to overwrite application settings from config from code. /// By default values from config are used /// </summary> public class TestApplicationSettings : IApplicationSettings { public TestApplicationSettings() { // Set defaults based on application settings from config var applicationSettingsFromConfig = new Infrastructure.ApplicationSettings.ApplicationSettings(); CoolOffPeriod = applicationSettingsFromConfig.CoolOffPeriod; ExpirationPeriodNewPasswordrequest = applicationSettingsFromConfig.ExpirationPeriodNewPasswordrequest; MaxLoginAttempts = applicationSettingsFromConfig.MaxLoginAttempts; PasswordPolicy = applicationSettingsFromConfig.PasswordPolicy; ConnectionString = applicationSettingsFromConfig.ConnectionString; Environment = applicationSettingsFromConfig.Environment; WindowsServiceMailSenderName = applicationSettingsFromConfig.WindowsServiceMailSenderName; ApplicationVersion = applicationSettingsFromConfig.ApplicationVersion; SmtpHost = applicationSettingsFromConfig.SmtpHost; SmtpPort = applicationSettingsFromConfig.SmtpPort; SmtpUsername = applicationSettingsFromConfig.SmtpUsername; SmtpPassword = applicationSettingsFromConfig.SmtpPassword; DefaultCulture = applicationSettingsFromConfig.DefaultCulture; AcceptedCultures = applicationSettingsFromConfig.AcceptedCultures; SmtpSslEnabled = applicationSettingsFromConfig.SmtpSslEnabled; WebMessageQueueAddress = applicationSettingsFromConfig.WebMessageQueueAddress; MailSenderMessageQueueAddress = applicationSettingsFromConfig.MailSenderMessageQueueAddress; } public int CoolOffPeriod { get; set; } public int ExpirationPeriodNewPasswordrequest { get; set; } public int MaxLoginAttempts { get; set; } public string PasswordPolicy { get; set; } public string ConnectionString { get; set; } public string Environment { get; set; } public string WindowsServiceMailSenderName { get; set; } public string ApplicationVersion { get; set; } public string SmtpHost { get; set; } public int SmtpPort { get; set; } public string SmtpUsername { get; set; } public string SmtpPassword { get; set; } public bool SmtpSslEnabled { get; set; } public string WebMessageQueueAddress { get; set; } public string MailSenderMessageQueueAddress { get; set; } public CultureInfo DefaultCulture { get; set; } public IEnumerable<CultureInfo> AcceptedCultures { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DTO { public class BancaColecao : List<Banca> { } }
using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using KartObjects; namespace KartLib.Reports { public class BaseReportViewer : Entity { protected string FnameReport; public ReportSession ReportSession; public List<Assortment> SelectedAssortments; public List<GoodGroup> SelectedGroodGroups; public List<Warehouse> SelectedWarehouses; /// <summary> /// Путь к папке отчетов /// </summary> protected string ReportPath; /// <summary> /// Для корректной работы отчетов? /// </summary> protected BindingSource DataSource; /// <summary> /// Ссылка на родительскую форму /// </summary> protected Form ParentForm; /// <summary> /// Конструктор /// </summary> /// <param name="parentForm"></param> /// <param name="reportPath"></param> public BaseReportViewer(Form parentForm, string reportPath) { SelectedGroodGroups = new List<GoodGroup>(); SelectedWarehouses = new List<Warehouse>(); SelectedAssortments = new List<Assortment>(); ParentForm = parentForm; ReportPath = reportPath; DataSource = new BindingSource(); } public override string FriendlyName { get { return "Базовый класс работы с отчетами"; } } public long? IdSupplier { get; set; } /// <summary> /// Имя файла отчета /// </summary> public string ReportFileName { get; set; } /// <summary> /// Сохранение в базу сложных входных параметров /// </summary> protected virtual void PrepareComplexParams() { if (SelectedWarehouses.Count > 0) { foreach (var rep in SelectedWarehouses.Select(wh => new ReportExtParam { IdParam = wh.Id, IdReportSession = ReportSession.IdSession, typeParam = TypeExtParam.Warehouse })) { Saver.SaveToDb(rep); } } if (SelectedGroodGroups.Count > 0) { foreach (var rep in SelectedGroodGroups.Select(gg => new ReportExtParam { IdParam = gg.Id, IdReportSession = ReportSession.IdSession, typeParam = TypeExtParam.GoodGroup })) { Saver.SaveToDb(rep); } } if (SelectedAssortments.Count > 0) { foreach (var rep in SelectedAssortments.Select(a => new ReportExtParam { IdParam = a.Id, IdReportSession = ReportSession.IdSession, typeParam = TypeExtParam.Assortment })) { Saver.SaveToDb(rep); } } } /// <summary> /// Вывод отчета /// </summary> /// <param name="doc"></param> public virtual void ShowReport(SimpleDbEntity doc) { } } }
namespace ShapesGraphics.Enums { public enum ShapeType { Circle = 0, Rectangle = 1, Trapezium = 2 } }
using GraphicalEditor.Constants; using GraphicalEditor.Enumerations; using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Shapes; namespace GraphicalEditor.Models.MapObjectRelated { public class MapObjectType : INotifyPropertyChanged { public TypeOfMapObject TypeOfMapObject { get; set; } public MapObjectType() { } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName = null) { PropertyChangedEventHandler _handler = this.PropertyChanged; if (_handler != null) { var e = new PropertyChangedEventArgs(propertyName); _handler(this, e); } } public string ObjectTypeFullName { get { switch (TypeOfMapObject) { case TypeOfMapObject.BUILDING: return "Building"; case TypeOfMapObject.EXAMINATION_ROOM: return "ExaminationRoom"; case TypeOfMapObject.OPERATION_ROOM: return "OperationRoom"; case TypeOfMapObject.WAITING_ROOM: return "WaitingRoom"; case TypeOfMapObject.PARKING: return "Parking"; case TypeOfMapObject.RESTAURANT: return "Restaurant"; case TypeOfMapObject.HOSPITALIZATION_ROOM: return "HospitalizationRoom"; case TypeOfMapObject.WC: return "WC"; case TypeOfMapObject.ROAD: return "Road"; default: return "Object"; } } set { switch (value.Trim()) { case "Building": TypeOfMapObject = TypeOfMapObject.BUILDING; break; case "ExaminationRoom": TypeOfMapObject = TypeOfMapObject.EXAMINATION_ROOM; break; case "OperationRoom": TypeOfMapObject = TypeOfMapObject.OPERATION_ROOM; break; case "WaitingRoom": TypeOfMapObject = TypeOfMapObject.WAITING_ROOM; break; case "Parking": TypeOfMapObject = TypeOfMapObject.PARKING; break; case "Restaurant": TypeOfMapObject = TypeOfMapObject.RESTAURANT; break; case "HospitalizationRoom": TypeOfMapObject = TypeOfMapObject.HOSPITALIZATION_ROOM; break; case "WC": TypeOfMapObject = TypeOfMapObject.WC; break; case "Road": TypeOfMapObject = TypeOfMapObject.ROAD; break; default: break; } } } public string ObjectTypeNameAbbreviation { get { switch (TypeOfMapObject) { case TypeOfMapObject.BUILDING: return "Z"; case TypeOfMapObject.EXAMINATION_ROOM: return "SP"; case TypeOfMapObject.OPERATION_ROOM: return "OS"; case TypeOfMapObject.WAITING_ROOM: return "Č"; case TypeOfMapObject.PARKING: return "P"; case TypeOfMapObject.RESTAURANT: return "R"; case TypeOfMapObject.HOSPITALIZATION_ROOM: return "SO"; case TypeOfMapObject.WC: return "WC"; case TypeOfMapObject.ROAD: return ""; default: return "O"; } } } public MapObjectType(TypeOfMapObject mapObjectType) { TypeOfMapObject = mapObjectType; } public SolidColorBrush ObjectTypeColor { get { switch (TypeOfMapObject) { case TypeOfMapObject.BUILDING: return Brushes.White; case TypeOfMapObject.EXAMINATION_ROOM: return Brushes.Lavender; case TypeOfMapObject.OPERATION_ROOM: return Brushes.LightCyan; case TypeOfMapObject.WAITING_ROOM: return Brushes.Honeydew; case TypeOfMapObject.PARKING: return Brushes.CornflowerBlue; case TypeOfMapObject.RESTAURANT: return Brushes.BlanchedAlmond; case TypeOfMapObject.HOSPITALIZATION_ROOM: return Brushes.Aquamarine; case TypeOfMapObject.WC: return Brushes.LightYellow; case TypeOfMapObject.ROAD: return Brushes.LightGray; default: return Brushes.Moccasin; } } } public List<String> AllMapObjectTypes { get { List<String> allMapObjectTypes = new List<String>(); Array typesOfMapObjects = Enum.GetValues(typeof(TypeOfMapObject)); foreach (TypeOfMapObject enumValue in typesOfMapObjects) { MapObjectType value = new MapObjectType(enumValue); allMapObjectTypes.Add(value.ObjectTypeFullName); } return allMapObjectTypes; } } public List<MapObjectType> AllMapObjectTypesAvailableToChange { get { List<MapObjectType> allMapObjectTypesAvailableToChange = new List<MapObjectType>(); Array typesOfMapObjects = Enum.GetValues(typeof(TypeOfMapObject)); foreach (TypeOfMapObject mapObjectType in typesOfMapObjects) { if (mapObjectType != TypeOfMapObject.BUILDING && mapObjectType != TypeOfMapObject.ROAD) { MapObjectType singleTypeOfMapObject = new MapObjectType(mapObjectType); allMapObjectTypesAvailableToChange.Add(singleTypeOfMapObject); } } return allMapObjectTypesAvailableToChange; } } public static List<MapObjectType> AllMapObjectTypesAvailableForSearch { get { List<MapObjectType> allMapObjectTypesAvailableToChange = new List<MapObjectType>(); Array typesOfMapObjects = Enum.GetValues(typeof(TypeOfMapObject)); foreach (TypeOfMapObject mapObjectType in typesOfMapObjects) { if (mapObjectType != TypeOfMapObject.ROAD) { MapObjectType singleTypeOfMapObject = new MapObjectType(mapObjectType); allMapObjectTypesAvailableToChange.Add(singleTypeOfMapObject); } } return allMapObjectTypesAvailableToChange; } } public static List<TypeOfMapObject> AllRoomTypes() { List<TypeOfMapObject> roomObjectTypes = new List<TypeOfMapObject>(); roomObjectTypes.Add(TypeOfMapObject.EXAMINATION_ROOM); roomObjectTypes.Add(TypeOfMapObject.OPERATION_ROOM); roomObjectTypes.Add(TypeOfMapObject.HOSPITALIZATION_ROOM); return roomObjectTypes; } public void SetStrokeColorAndThickness(Rectangle rectangle) { if (TypeOfMapObject != TypeOfMapObject.ROAD) { rectangle.Stroke = Brushes.Black; rectangle.StrokeThickness = AllConstants.RECTANGLE_STROKE_THICKNESS; } } } }
using FluentValidation; using SFA.DAS.ProviderCommitments.Web.Models; namespace SFA.DAS.ProviderCommitments.Web.Validators { public class DraftApprenticeshipRequestValidator : AbstractValidator<DraftApprenticeshipRequest> { public DraftApprenticeshipRequestValidator() { RuleFor(model => model.CohortId).GreaterThan(0); RuleFor(model => model.CohortReference).NotEmpty(); RuleFor(model => model.DraftApprenticeshipId).GreaterThan(0); RuleFor(model => model.DraftApprenticeshipHashedId).NotEmpty(); } } }
using System; using pjank.BossaAPI; namespace pjank.BossaAPI.MarketMonitor { /// <summary> /// /// Poniżej najprostszy przykład odbioru bieżących notowań za pośrednictwem tej biblioteki. /// /// W tych kilku linijkach (nie licząc komentarzy ;)) mamy w pełni funkcjonalny program konsolowy, /// wyświetlający bieżące notowania dowolnych instrumentów (podanych w argumentach wywołania programu). /// /// Przykład użycia: /// TestApp3.exe PKOBP PEKAO GETIN BRE BZWBK WIG20 FW20M12 /// /// </summary> class MarketMonitor { /// <summary> /// Główna funkcja programu. /// </summary> /// <param name="args"> /// lista przekazanych parametrów: podawane po spacji symbole kolejnych intrumentów /// </param> public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Nie podano parametrów, włączam przykładową listę instrumentów..."); args = new[] { "WIG20", "KGHM", "FW20M12" }; } try { // podłączenie naszego handlera pod zdarzenie aktualizacji danych Bossa.OnUpdate += Bossa_OnUpdate; // aktywacja subskrypcji dla wybranych instrumentów // (praktycznie wystarczy dowolne odwołanie do danego symbolu na liście Instruments[...], // automatycznie uwzględnia również wszelkie instrumenty znajdujące się już na rachunku) foreach (var symbol in args) { Console.WriteLine("dodaję: {0}", symbol); Bossa.Instruments[symbol].UpdatesEnabled = true; } Console.WriteLine(); // uruchomienie połączenia z NOL'em Bossa.ConnectNOL3(); // czekamy na naciśnięcie dowolnego klawisza (w tle będzie odpalał Bossa_OnUpdate) Console.ReadKey(true); // zakończenie połączenia z NOL'em Bossa.Disconnect(); } catch (Exception e) { // przechwycenie ew. błędów (np. komunikacji z NOL'em) - wyświetlenie komunikatu Console.WriteLine(e.Message); } } /// <summary> /// Zdarzenie wywoływane przy aktualizacji danych rynkowych lub stanu rachunku. /// </summary> /// <param name="obj">zmieniony obiekt: BosInstrument lub BosAccount</param> /// <param name="e">dodatkowe parametry, aktualnie nieużywane</param> private static void Bossa_OnUpdate(object obj, EventArgs e) { var ins = obj as BosInstrument; if (ins != null) // wyświetlenie w kolejnym wierszu bieżących notowań { Console.WriteLine("{0,-10} [ {1,-8} {2,8} ] {3}", ins.Symbol, ins.BuyOffers.BestPrice, ins.SellOffers.BestPrice, ins.Trades.Last); } } } }
using System; namespace Week3a { class MainClass { public static void Main(string[] args) { const string USERNAME = "emiliokyp"; const string PASSWORD = "password"; Console.WriteLine("Please enter your username and password"); string username = Console.ReadLine(); string password = Console.ReadLine(); if (username == USERNAME && password == PASSWORD) { Console.WriteLine("Welcome, " + username); } else { Console.WriteLine("Incorrect login details"); } Console.ReadLine(); //pause Console.Clear(); Console.WriteLine("Enter a number between 0 and 10"); string input = Console.ReadLine(); int result = int.Parse(input); if (result == 2 || result == 7) { Console.WriteLine("you guessed a good number"); } else { Console.WriteLine("Better luck next time"); } Console.ReadLine(); Console.Clear(); Console.WriteLine("Please enter your favourite colour"); var colour = Console.ReadLine().ToLower(); if (colour == "black" || colour == "white" || colour =="grey") { Console.WriteLine("Thats a shade not a colour..."); } else { Console.WriteLine("neat"); } Console.ReadLine(); //pause Console.Clear(); Console.WriteLine("Please enter a valid email address"); var email = Console.ReadLine(); Console.WriteLine("Please confirm your email address"); var emailConfirm = Console.ReadLine(); if (email != emailConfirm) { Console.WriteLine("Emails did not match, please try again"); } else { Console.WriteLine("Email address confirmed"); } Console.ReadLine(); //pause Console.Clear(); } } }
using System; namespace UseFul.Uteis { public class DateRange { public DateTime Start { get; private set; } public DateTime End { get; private set; } public static DateRange Today(DateTime date) { DateRange range = new DateRange {Start = DateTime.Now}; range.End = range.Start; return range; } public static DateRange Yesterday(DateTime date) { DateRange range = new DateRange {Start = DateTime.Now.AddDays(-1)}; range.End = range.Start; return range; } public static DateRange ThisYear(DateTime date) { DateRange range = new DateRange {Start = new DateTime(date.Year, 1, 1)}; range.End = range.Start.AddYears(1).AddSeconds(-1); return range; } public static DateRange LastYear(DateTime date) { DateRange range = new DateRange {Start = new DateTime(date.Year - 1, 1, 1)}; range.End = range.Start.AddYears(1).AddSeconds(-1); return range; } public static DateRange ThisMonth(DateTime date) { DateRange range = new DateRange {Start = new DateTime(date.Year, date.Month, 1)}; range.End = range.Start.AddMonths(1).AddSeconds(-1); return range; } public static DateRange LastMonth(DateTime date) { DateRange range = new DateRange {Start = new DateTime(date.Year, date.Month, 1).AddMonths(-1)}; range.End = range.Start.AddMonths(1).AddSeconds(-1); return range; } public static DateRange ThisWeek(DateTime date) { DateRange range = new DateRange {Start = date.Date.AddDays(-(int) date.DayOfWeek)}; range.End = range.Start.AddDays(7).AddSeconds(-1); return range; } public static DateRange LastWeek(DateTime date) { DateRange range = ThisWeek(date); range.Start = range.Start.AddDays(-7); range.End = range.End.AddDays(-7); return range; } public static DateRange TwoLastWeek(DateTime date) { DateRange range = ThisWeek(date); range.Start = range.Start.AddDays(-14); range.End = range.End.AddDays(-14); return range; } public static DateRange ThreeLastWeek(DateTime date) { DateRange range = ThisWeek(date); range.Start = range.Start.AddDays(-21); range.End = range.End.AddDays(-21); return range; } public static DateRange FourLastWeek(DateTime date) { DateRange range = ThisWeek(date); range.Start = range.Start.AddDays(-28); range.End = range.End.AddDays(-28); return range; } } }
using Entities.Models; using System; using System.Collections.Generic; using System.Text; namespace Contracts { public interface IPhoneNumberRepository { PhoneNumber GetPhoneNumber(int id, bool trackChanges); IEnumerable<PhoneNumber> GetPhoneNumbersByPerson(Person person, bool trackChanges); } }
using SocialMedia.Data; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialMedia.Models { //NO public class PostCreate { [Required] [MaxLength(100, ErrorMessage = "Title is too long.")] public string Title { get; set; } public string Text { get; set; } } }
using System; using System.Net; using System.Net.Sockets; namespace TCPProxy { /// <summary> /// http://blog.brunogarcia.com/2012/10/simple-tcp-forwarder-in-c.html /// </summary> public class TCPForwarder { private readonly Socket MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /// <summary> /// /// </summary> /// <param name="local">Local listening IP and Port</param> /// <param name="remote">Remote IP and Port</param> public void Start(IPEndPoint local, IPEndPoint remote) { MainSocket.Bind(local); MainSocket.Listen(10); while (true) { var source = MainSocket.Accept(); var destination = new TCPForwarder(); var state = new State(source, destination.MainSocket); destination.Connect(remote, source); source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state); } } private void Connect(EndPoint remoteEndpoint, Socket destination) { var state = new State(MainSocket, destination); MainSocket.Connect(remoteEndpoint); MainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state); } private static void OnDataReceive(IAsyncResult result) { var state = (State)result.AsyncState; try { var bytesRead = state.SourceSocket.EndReceive(result); if (bytesRead > 0) { state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None); state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state); } } catch { state.DestinationSocket.Close(); state.SourceSocket.Close(); } } } }
using System.Threading.Tasks; namespace NeuralNetwork.Core { static class Feedforward { internal static float[] GetOutputSignalOfSample(float[] inputSignal, float[][] neuronWeights, ActivationFunc activationFunc, float[] isBiasNeuron) { int _synapsesCount = neuronWeights.Length; int _neuronsCount = neuronWeights[0].Length; float[] _outputSignals = new float[_neuronsCount]; float[][] _neuronWeightsT = TransposeArray(neuronWeights); for (int neuron = 0; neuron < _neuronsCount; neuron++) { float _inputSignalForNeuron = 0; for (int synapse = 0; synapse < _synapsesCount; synapse++) { _inputSignalForNeuron += inputSignal[synapse] * _neuronWeightsT[neuron][synapse] + (isBiasNeuron != null ? isBiasNeuron[neuron] : 0); } _outputSignals[neuron] = NeuralMath.GetApproximateByFunction(_inputSignalForNeuron, activationFunc); } return _outputSignals; } internal static float[][] GetOutputSignalsOfAllSamples(float[][] inputSignals, float[][] neuronWeights, ActivationFunc activationFunc, float[] isBiasNeuron) { int _synapsesCount = neuronWeights.Length; int _neuronsCount = neuronWeights[0].Length; float[][] _outputSignals = new float[inputSignals.Length][]; float[][] _neuronWeightsT = TransposeArray(neuronWeights); Parallel.For(0, inputSignals.Length, numberOfActiveDataset => { float _inputSignalForNeuron; if (_outputSignals[numberOfActiveDataset] == null) _outputSignals[numberOfActiveDataset] = new float[_neuronsCount]; for (int neuron = 0; neuron < _neuronsCount; neuron++) { _inputSignalForNeuron = SumAllSynapseSignals(numberOfActiveDataset, neuron, _synapsesCount); _outputSignals[numberOfActiveDataset][neuron] = NeuralMath.GetApproximateByFunction(_inputSignalForNeuron, activationFunc); } }); return _outputSignals; float SumAllSynapseSignals(int currentSet, int neuron, int synapsesOfNeuron) { float _inputSignal = 0; for (int synapse = 0; synapse < synapsesOfNeuron; synapse++) { _inputSignal += inputSignals[currentSet][synapse] * _neuronWeightsT[neuron][synapse] + (isBiasNeuron != null ? isBiasNeuron[neuron] : 0); } return _inputSignal; } } private static float[][] TransposeArray(float[][] arrayForTranspose) { float[][] _arrayT = new float[arrayForTranspose[0].Length][]; for (int i = 0; i < arrayForTranspose.Length; i++) { for (int j = 0; j < arrayForTranspose[i].Length; j++) { if (_arrayT[j] == null) _arrayT[j] = new float[arrayForTranspose.Length]; _arrayT[j][i] = arrayForTranspose[i][j]; } } return _arrayT; } } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Infra.Data.EntityConfig { public class RegimesConfig: EntityTypeConfiguration<Regimes> { public RegimesConfig() { HasKey(p => p.RegimesId) .Property(p => p.RegimesId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); Property(p => p.Descricao) .HasMaxLength(30); Property(p => p.Censec) .HasMaxLength(30); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class End : MonoBehaviour { public AudioSource ding; private GameController gameControllerScript; private Timer timerScript; private bool hasKey; public GameObject ClosedPortal; public Text needKeyText; // Start is called before the first frame update void Start() { ding = GetComponent<AudioSource>(); GameObject gameControllerObject = GameObject.FindWithTag("GameController"); if (gameControllerObject != null) { // I got the game controller object! gameControllerScript = gameControllerObject.GetComponent<GameController>(); if (gameControllerScript == null) { // There is no GameController script on my game controller object Debug.Log("Cannot find GameController script on GameController object"); } } if (gameControllerObject != null) { // I got the game controller object! timerScript = gameControllerObject.GetComponent<Timer>(); if (timerScript == null) { // There is no GameController script on my game controller object Debug.Log("Cannot find Timer script on GameController object"); } } } void OnTriggerEnter2D(Collider2D co) { if (co.name == "Sol") { if (hasKey == true) { Destroy(co.gameObject); timerScript.Finish(); gameControllerScript.Win(); } else { ding.Play(); needKeyText.gameObject.SetActive(true); } } } void OnTriggerExit2D(Collider2D co) { needKeyText.gameObject.SetActive(false); } public void KeyGrab() { ClosedPortal.gameObject.SetActive(false); hasKey = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserNamespace { [Serializable] public class User { public int CardNumber { get; set; } = 7; public string Name { get; set; } public string Id { get; set; } public User() { Name = "您"; Id = "Local User"; } public User(string n, string i) { Name = n; Id = i; } public bool Equals(User usr) { return this.Id == usr.Id; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper.DBContext; using EBS.Domain.Entity; using EBS.Infrastructure.Extension; using EBS.Infrastructure; namespace EBS.Domain.Service { public class StorePurchaseOrderService { IDBContext _db; BillSequenceService _sequenceService; StoreInventoryService _storeInventoryService; public StorePurchaseOrderService(IDBContext dbContext) { this._db = dbContext; _sequenceService = new BillSequenceService(_db); _storeInventoryService = new StoreInventoryService(_db); } public List<StorePurchaseOrder> SplitOrderItem(StorePurchaseOrder model) { var splitNumber = 10; List<StorePurchaseOrderItem> items = new List<StorePurchaseOrderItem>(); List<StorePurchaseOrder> entitys = new List<StorePurchaseOrder>(); foreach (var item in model.Items) { if (items.Count == splitNumber) { StorePurchaseOrder entity = new StorePurchaseOrder(); entity.SetItems(items); entitys.Add(entity); items = new List<StorePurchaseOrderItem>(); // 重新分配一个 } var product = _db.Table.Find<Product>(item.ProductId); if (model.OrderType == ValueObject.OrderType.Refund) { //检查库存 var inventoryModel = _db.Table.Find<StoreInventory>(n => n.ProductId == item.ProductId && n.StoreId == model.StoreId); if (item.Quantity > inventoryModel.Quantity) { throw new FriendlyException(string.Format("商品{0}退货数量{1} > 库存数{2}", product.Code, item.Quantity, inventoryModel.Quantity)); } } else { if (item.Quantity <= 0) { throw new FriendlyException(string.Format("{0}:数量不能小于等于0", product.Code)); } } var itemProduct = items.FirstOrDefault(n => n.ProductId == item.ProductId); if (itemProduct == null) { items.Add(item); } else { itemProduct.Quantity += item.Quantity; } } if (items.Count > 0 && items.Count <= splitNumber) { StorePurchaseOrder entity = new StorePurchaseOrder(); entity.SetItems(items); entitys.Add(entity); } return entitys; } public void UpdateWithItem(StorePurchaseOrder model) { if (_db.Table.Exists<StorePurchaseOrderItem>(n => n.StorePurchaseOrderId == model.Id)) { _db.Delete<StorePurchaseOrderItem>(n => n.StorePurchaseOrderId == model.Id); } _db.Insert<StorePurchaseOrderItem>(model.Items.ToArray()); _db.Update(model); } } }
using System.Collections.Generic; using System.Linq; using TwilightShards.Common; namespace ClimatesOfFerngillRebuild { public class FerngillClimateTimeSpan { public string BeginSeason; public string EndSeason; public int BeginDay; public int EndDay; public double EveningFogChance; public List<WeatherParameters> WeatherChances; public FerngillClimateTimeSpan() { this.WeatherChances = new List<WeatherParameters>(); } public FerngillClimateTimeSpan(string BeginSeason, string EndSeason, int BeginDay, int EndDay, List<WeatherParameters> wp) { this.BeginSeason = BeginSeason; this.EndSeason = EndSeason; this.BeginDay = BeginDay; this.EndDay = EndDay; this.WeatherChances = new List<WeatherParameters>(); foreach (WeatherParameters w in wp) { this.WeatherChances.Add(new WeatherParameters(w)); } } public FerngillClimateTimeSpan(FerngillClimateTimeSpan CTS) { this.BeginSeason = CTS.BeginSeason; this.EndSeason = CTS.EndSeason; this.BeginDay = CTS.BeginDay; this.EndDay = CTS.EndDay; this.WeatherChances = new List<WeatherParameters>(); foreach (WeatherParameters w in CTS.WeatherChances) this.WeatherChances.Add(new WeatherParameters(w)); } public void AddWeatherChances(WeatherParameters wp) { if (this.WeatherChances is null) WeatherChances = new List<WeatherParameters>(); WeatherChances.Add(new WeatherParameters(wp)); } public double RetrieveOdds(MersenneTwister dice, string weather, int day) { double Odd = 0; List<WeatherParameters> wp = this.WeatherChances.Where(w => w.WeatherType == weather).ToList(); if (wp.Count == 0) return 0; Odd = wp[0].BaseValue + (wp[0].ChangeRate * day); RangePair range = new RangePair(wp[0].VariableLowerBound, wp[0].VariableHigherBound); Odd = Odd + range.RollInRange(dice); //sanity check. if (Odd < 0) Odd = 0; if (Odd > 1) Odd = 1; return Odd; } public double RetrieveTemp(MersenneTwister dice, string temp, int day) { double Temp = 0; List<WeatherParameters> wp = this.WeatherChances.Where(w => w.WeatherType == temp).ToList<WeatherParameters>(); if (wp.Count == 0) return 0; Temp = wp[0].BaseValue + (wp[0].ChangeRate * day); RangePair range = new RangePair(wp[0].VariableLowerBound, wp[0].VariableHigherBound); Temp = Temp + range.RollInRange(dice); return Temp; } } }
using NUnit.Framework; using Juicy.DirtCheapDaemons.Http; namespace Juicy.DirtCheapDaemons.UnitTest.Http { [TestFixture] public class InlineHandlerTests { [Test] public void ShouldCallLambdaWithReqResp() { IRequest req = new Request(); IResponse resp = new Response(); bool called = false; var h = new InlineHandler((request, response) => { Assert.AreSame(req, request); Assert.AreSame(resp, response); called = true; }); h.Respond(req, resp); Assert.IsTrue(called); } } }
using System.Text; using StrategyPattern.Core; namespace StrategyPattern.Strategies { public class MarkdownStrategy : IListStrategy { public void Start(StringBuilder sb) { } public void End(StringBuilder sb) { } public void AddListItem(StringBuilder sb, string item) { sb.AppendLine($" * {item}"); } } }
using Anywhere2Go.DataAccess; using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.Object; using log4net; using log4net.Repository.Hierarchy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.Business.Master { public class CarPartyLogic { private static readonly ILog logger = LogManager.GetLogger(typeof(CarPartyLogic)); MyContext _context = null; public CarPartyLogic() { _context = new MyContext(); } public CarPartyLogic(MyContext context) { _context = context; } public BaseResult<bool?> DeleteCarParty(Guid CarPartyId, Authentication auth) { string user = auth != null ? auth.first_name + " " + auth.last_name : ""; BaseResult<bool?> resultDelete = new BaseResult<bool?>(); try { var req = new Repository<CarParty>(_context); var reqTask = new Repository<DataAccess.Entity.Task>(_context); var CarParty = req.Find(t => t.CarPartyId == CarPartyId && t.IsActive).FirstOrDefault(); if (CarParty != null) { CarParty.IsActive = false; CarParty.UpdateDate = DateTime.Now; CarParty.UpdateBy = user; foreach (var item in CarParty.CarPartyDamages.Where(t => t.CarPartyId == CarPartyId)) { item.IsActive = false; item.UpdateBy = user; item.UpdateDate = DateTime.Now; } var task = reqTask.Find(t => t.taskId == CarParty.TaskId).FirstOrDefault(); if (task != null) { task.updateDate = DateTime.Now; task.updateBy = user; } req.SaveChanges(); resultDelete.Result = true; } } catch (Exception ex) { resultDelete.StatusCode = Constant.ErrorCode.SystemError; resultDelete.Message = Constant.ErrorMessage.SystemError; resultDelete.SystemErrorMessage = ex.Message; } return resultDelete; } public BaseResult<CarPartyModel> AddEditCarParty(CarParty model, Authentication auth) { BaseResult<CarPartyModel> res = new BaseResult<CarPartyModel>(); using (var con = _context.Database.BeginTransaction()) { try { string user = auth != null ? auth.first_name + " " + auth.last_name : ""; var req = new Repository<DataAccess.Entity.Task>(_context); var task = req.Find(t => t.taskId == model.TaskId).FirstOrDefault(); CarPartyModel carPartyModel = new CarPartyModel(); if (task != null) { var reqCarParty = new Repository<CarParty>(_context); var carPartyReq = task.CarParties.Find(t => t.CarPartyId == model.CarPartyId); if (carPartyReq != null) { carPartyReq.CarRegis = model.CarRegis; carPartyReq.PolicyInsurerId = model.PolicyInsurerId; carPartyReq.CarRegisProvinceCode = model.CarRegisProvinceCode; carPartyReq.ActNo = model.ActNo; carPartyReq.PolicyType = model.PolicyType; if (model.PolicyStartDate != null) carPartyReq.PolicyStartDate = model.PolicyStartDate; if (model.CarBrandId != null) carPartyReq.CarBrandId = model.CarBrandId; if (model.CarModelId != null) carPartyReq.CarModelId = model.CarModelId; if (model.CarColorId != 0) carPartyReq.CarColorId = model.CarColorId; if (model.PolicyEndDate != null) carPartyReq.PolicyEndDate = model.PolicyEndDate; if (model.CarTypeID != 0) carPartyReq.CarTypeID = model.CarTypeID; carPartyReq.PolicyOwner = model.PolicyOwner; carPartyReq.PolicyDriver1 = model.PolicyDriver1; carPartyReq.PolicyDriver2 = model.PolicyDriver2; carPartyReq.CarDriverGender = model.CarDriverGender; carPartyReq.CarChassis = model.CarChassis; carPartyReq.PolicyNo = model.PolicyNo; carPartyReq.CarDriverBirthday = model.CarDriverBirthday; carPartyReq.CarDriverAge = model.CarDriverAge; carPartyReq.CarDriverIdCard = model.CarDriverIdCard; carPartyReq.CarDriverAddress = model.CarDriverAddress; carPartyReq.CarDriverTel = model.CarDriverTel; carPartyReq.CarDriverRelation = model.CarDriverRelation; carPartyReq.CarDriverLicenseCardTypeId = model.CarDriverLicenseCardTypeId; carPartyReq.CarDriverLicenseCard = model.CarDriverLicenseCard; if (model.CarDriverLicenseCardExpireDate != null) carPartyReq.CarDriverLicenseCardExpireDate = model.CarDriverLicenseCardExpireDate; if (model.CarDriverLicenseCardIssuedDate != null) carPartyReq.CarDriverLicenseCardIssuedDate = model.CarDriverLicenseCardIssuedDate; carPartyReq.SummaryDamageCar = model.SummaryDamageCar; carPartyReq.UpdateDate = DateTime.Now; carPartyReq.UpdateBy = user; task.updateDate = DateTime.Now; task.updateBy = user; carPartyReq.CarCapacityCode = model.CarCapacityCode; carPartyReq.CarDriverTitleCode = model.CarDriverTitleCode; carPartyReq.CarDriverFirstName = model.CarDriverFirstName; carPartyReq.CarDriverLastName = model.CarDriverLastName; carPartyReq.CarDriverProvinceCode = model.CarDriverProvinceCode; carPartyReq.CarDriverAmphurCode = model.CarDriverAmphurCode; carPartyReq.CarDriverDistrictCode = model.CarDriverDistrictCode; carPartyReq.CarDriverRelationCode = model.CarDriverRelationCode; carPartyReq.CarDriverAddress = model.CarDriverAddress; req.SaveChanges(); CarParty tempCP = new CarParty(); tempCP.CarPartyId = carPartyReq.CarPartyId; carPartyModel.CarParty = tempCP; res.Result = carPartyModel; } else { model.CreateDate = DateTime.Now; model.CreateBy = user; model.IsActive = true; model.UpdateDate = DateTime.Now; model.UpdateBy = user; task.CarParties.Add(model); task.updateDate = DateTime.Now; task.updateBy = user; req.SaveChanges(); CarParty tempCP = new CarParty(); tempCP.CarPartyId = model.CarPartyId; carPartyModel.CarParty = tempCP; res.Result = carPartyModel; } con.Commit(); } else { res.StatusCode = Constant.ErrorCode.ExistingData; res.Message = Constant.ErrorMessage.ExistingData; } } catch (Exception ex) { con.Rollback(); res.StatusCode = Constant.ErrorCode.SystemError; res.Message = Constant.ErrorMessage.SystemError; res.SystemErrorMessage = ex.Message; logger.Error(string.Format("Method = {0},User = {1}", "AddEditCarParty"), ex); } } return res; } public CarParty GetCarPartyById(Guid Id) { var req = new Repository<CarParty>(_context); CarParty carParty = new CarParty(); var temp = req.Find(t => t.CarPartyId == Id).FirstOrDefault(); if (temp !=null) { carParty.PolicyInsurerId = temp.PolicyInsurerId; if (!string.IsNullOrEmpty(temp.PolicyInsurerId)) { carParty.PolicyInsurer = new Insurer(); carParty.PolicyInsurer.InsID = temp.PolicyInsurer.InsID; carParty.PolicyInsurer.InsName = temp.PolicyInsurer.InsName; } // carParty.ActNo=t carParty.CarBrand = temp.CarBrand; carParty.CarBrandId = temp.CarBrandId; carParty.CarChassis = temp.CarChassis; carParty.CarColor = temp.CarColor; carParty.CarColorId = temp.CarColorId; carParty.CarDriverAddress = temp.CarDriverAddress; carParty.CarDriverAge = temp.CarDriverAge; carParty.CarDriverBirthday = temp.CarDriverBirthday; carParty.CarDriverGender = temp.CarDriverGender; carParty.CarDriverIdCard = temp.CarDriverIdCard; carParty.CarDriverLicenseCard = temp.CarDriverLicenseCard; carParty.CarDriverLicenseCardExpireDate = temp.CarDriverLicenseCardExpireDate; carParty.CarDriverLicenseCardIssuedDate = temp.CarDriverLicenseCardIssuedDate; carParty.CarDriverLicenseCardType = temp.CarDriverLicenseCardType; carParty.CarDriverLicenseCardTypeId = temp.CarDriverLicenseCardTypeId; carParty.CarDriverName = temp.CarDriverName; carParty.CarDriverRelation = temp.CarDriverRelation; carParty.CarDriverTel = temp.CarDriverTel; carParty.CarEngine = temp.CarEngine; carParty.CarMile = temp.CarMile; carParty.CarModel = temp.CarModel; carParty.CarModelId = temp.CarModelId; carParty.CarPartyDamages = temp.CarPartyDamages; carParty.CarPartyId = temp.CarPartyId; carParty.CarRegis = temp.CarRegis; carParty.CarRegisProvince = temp.CarRegisProvince; carParty.CarRegisProvinceCode = temp.CarRegisProvinceCode; carParty.CarType = temp.CarType; carParty.CarTypeID = temp.CarTypeID; carParty.CarYear = temp.CarYear; carParty.IsActive = temp.IsActive; carParty.PolicyClaimNo = temp.PolicyClaimNo; carParty.PolicyDriver1 = temp.PolicyDriver1; carParty.PolicyDriver2 = temp.PolicyDriver2; carParty.PolicyEndDate = temp.PolicyEndDate; carParty.PolicyNo = temp.PolicyNo; carParty.PolicyOwner = temp.PolicyOwner; carParty.PolicyStartDate = temp.PolicyStartDate; carParty.PolicyType = temp.PolicyType; carParty.SummaryDamageCar = temp.SummaryDamageCar; carParty.TaskId = temp.TaskId; carParty.CarDriverTitleCode = temp.CarDriverTitleCode; carParty.CarDriverFirstName = temp.CarDriverFirstName; carParty.CarDriverLastName = temp.CarDriverLastName; carParty.CarDriverRelationCode = temp.CarDriverRelationCode; carParty.CarDriverProvinceCode = temp.CarDriverProvinceCode; carParty.CarDriverAmphurCode = temp.CarDriverAmphurCode; carParty.CarDriverDistrictCode = temp.CarDriverDistrictCode; carParty.CarCapacityCode = temp.CarCapacityCode; carParty.CarDriverAddress = temp.CarDriverAddress; } return carParty; } } }
/* Dataphor © Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Text; namespace Alphora.Dataphor.DAE.Device.SQL { using System.Collections.Generic; using Alphora.Dataphor.DAE.Compiling; using Alphora.Dataphor.DAE.Connection; using Alphora.Dataphor.DAE.Language; using Alphora.Dataphor.DAE.Language.SQL; using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Runtime.Instructions; using Alphora.Dataphor.DAE.Schema; using Alphora.Dataphor.DAE.Server; using Alphora.Dataphor.DAE.Streams; using D4 = Alphora.Dataphor.DAE.Language.D4; using Alphora.Dataphor.DAE.Compiling.Visitors; /* Meta Data tags controlling SQL translation and reconciliation -> Storage.Name -> indicates that the object on which it appears should be identified by the value of the tag when referenced within the device Storage.DomainName -> indicates that the column on which it appears should be declared to be of the given domain name. This can be used to specify a user-defined domain in the target system without having to declare a type in D4 Storage.NativeDomainName -> used to indicate the underlying native domain name for a given column, type, or type map. This tag is used to manage device reconciliation. Storage.Schema -> indicates that the object on which it appears should be schema qualified by the value of the tag when referenced within the device Storage.Length -> indicates the storage length for translated scalar types Storage.Precision -> indicates the storage precision for exact numeric data in translated scalar types Storage.Scale -> indicates the storage scale for exact numeric data in translated scalar types Storage.Deferred -> indicates that the values for the column or scalar type on which it appears should be read entirely as overflow Storage.Enforced -> indicates that the constraint on which it appears is enforced by the device and should not be enforced by the DAE // Deprecated, replaced by DAE.Enforced (opposite semantics) Storage.IsImposedKey -> indicates that the key on which it appears was imposed by catalog reconciliation and must be ensured with a distinct clause in select statements referencing the owning table Storage.IsClustered -> Indicates that the key on which it appears should be defined as a clustered index // Deprecated, replaced by DAE.IsClustered, same semantics Storage.ShouldReconcile -> Indicates that the object on which it appears should be reconciled with the target system. Basic Data type mapping -> These data type mappings are provided for by the SQLScalarType descendent classes in this namespace. They are not registered by the base SQLDevice. It is up to each device to decide whether the mapping is appropriate and take the necessary action to establish the mapping. DAE Type | ANSI SQL Type | Translation Handler ------------|-------------------------------------------------------------------|------------------------ Boolean | integer (0 or 1) | SQLBoolean Byte | smallint | SQLByte SByte | smallint | SQLSByte Short | smallint | SQLShort UShort | integer | SQLUShort Integer | integer | SQLInteger UInteger | bigint | SQLUInteger Long | bigint | SQLLong ULong | decimal(20, 0) | SQLULong Decimal | decimal(Storage.Precision, Storage.Scale) | SQLDecimal DateTime | date | SQLDateTime TimeSpan | bigint | SQLTimeSpan Date | date | SQLDate Time | time | SQLTime Money | decimal(28, 8) | SQLMoney Guid | char(36) | SQLGuid String | varchar(Storage.Length) | SQLString SQLDateTime | date | SQLDateTime SQLText | clob | SQLText Binary | blob | SQLBinary D4 to SQL translation -> Retrieve - select expression with single table in the from clause Restrict - adds a where clause to the expression, if it exists, conjoins to the existing clause Project - if there is already a select list, push the entire expression to a nested from clause Extend - add the extend columns to the current select list Rename - should translate to aliasing in most cases Adorn - ignored Aggregate - if there is already a select list, push the entire expression to a nested from clause Union - add the right side of the expression to a union expression (always distinct) Difference - unsupported Join (all flavors) - add the right side of the expression to a nested from clause if necessary Order - skip unless this is the outer node Browse - unsupported CreateTable - direct translation AlterTable - direct translation DropTable - direct translation Basic Operator Mapping -> Arithmetic operators -> + - * / % ** (-) Comparison operators -> = <> > >= < <= ?= like between matches Logical operators -> and or xor not Bitwise operators -> & | ^ ~ << >> Existential operators -> exists in Relational operators -> retrieve restrict project rename extend aggregate order union join Aggregate operators -> sum min max avg count all any String operators -> Length Copy Pos Upper Lower Guid operators -> NewGuid Conversion operators -> ToXXX Datetime operators -> Date Time Now Today DayOfMonth DayOfWeek DayOfYear DaysInMonth IsLeapYear AddMonths AddYears Null handling operators -> IsNull IfNull Conditional operators -> when case Catalog Importing -> Catalog description expects that the GetDeviceTablesExpression return result sets in the following form: // This result is expected to be ordered by TableSchema, TableName, OrdinalPosition (order in the table) TableSchema varchar(128), TableName varchar(128), ColumnName varchar(128), OrdinalPosition integer, TableTitle varchar(128), // if available, else default to TableName ColumnTitle varchar(128), // if available, else default to ColumnName NativeDomainName varchar(128), // this should be the native scalar type name DomainName varchar(128), // user-defined domain name, if available (nil if the column uses a native domain name) Length integer, // fixed length column size IsNullable integer, // 0 = false, 1 = true IsDeferred integer, // 0 = false, 1 = true, indicates whether deferred read should be used to access data in this column Catalog description expects that the GetDeviceIndexesExpression return result sets in the following form: // This result is expected to be ordered by TableSchema, TableName, IndexName, OrdinalPosition (order in the index) TableSchema varchar(128), TableName varchar(128), IndexName varchar(128), ColumnName varchar(128), OrdinalPosition integer, IsUnique integer, // 0 = false, 1 = true IsDescending integer, // 0 = false, 1 = true Catalog description expects that the GetDeviceForeignKeysExpression return result sets in the following form: // This result is expected to be ordered by ConstraintSchema, ConstraintName, OrdinalPosition ConstraintSchema varchar(128), ConstraintName varchar(128), SourceTableSchema varchar(128), SourceTableName varchar(128), SourceColumnName varchar(128), TargetTableSchema varchar(128), TargetTableName varchar(128), TargetColumnName varchar(128) OrdinalPosition integer These expressions are requested by the default implementation of GetDeviceCatalog. This behavior can be overridden as necessary by descendent devices to provide support for database specific catalog features. */ public abstract class SQLDevice : Device { public const string SQLDateTimeScalarType = "SQLDevice.SQLDateTime"; public const string SQLTimeScalarType = "SQLDevice.SQLTime"; public const string SQLTextScalarType = "SQLDevice.SQLText"; public const string SQLITextScalarType = "SQLDevice.SQLIText"; public SQLDevice(int iD, string name) : base(iD, name) { SetMaxIdentifierLength(); _supportsTransactions = true; } // Schema private string _schema = String.Empty; public string Schema { get { return _schema; } set { _schema = value == null ? String.Empty : value; } } private bool _useStatementTerminator = true; public bool UseStatementTerminator { get { return _useStatementTerminator; } set { _useStatementTerminator = value; } } private bool _useParametersForCursors = false; public bool UseParametersForCursors { get { return _useParametersForCursors; } set { _useParametersForCursors = value; } } private bool _shouldNormalizeWhitespace = true; public bool ShouldNormalizeWhitespace { get { return _shouldNormalizeWhitespace; } set { _shouldNormalizeWhitespace = value; } } private bool _useQuotedIdentifiers = true; public bool UseQuotedIdentifiers { set { _useQuotedIdentifiers = value;} get { return _useQuotedIdentifiers;} } private bool _useTransactions = true; /// <summary>Indicates whether or not to use transactions through the CLI of the target system.</summary> public bool UseTransactions { set { _useTransactions = value; } get { return _useTransactions; } } private bool _useQualifiedNames = false; /// <summary>Indicates whether or not to use the fully qualified name of an object in D4 to produce the storage name for the object.</summary> /// <remarks>Qualifiers will be replaced with underscores in the resulting storage name.</remarks> public bool UseQualifiedNames { get { return _useQualifiedNames; } set { _useQualifiedNames = value; } } private bool _supportsAlgebraicFromClause = true; /// <summary>Indicates whether or not the dialect supports an algebraic from clause.</summary> public bool SupportsAlgebraicFromClause { get { return _supportsAlgebraicFromClause; } set { _supportsAlgebraicFromClause = value; } } private string _onExecuteConnectStatement; /// <summary>A D4 expression denoting an SQL statement in the target dialect to be executed on all new execute connections.</summary> /// <remarks>The statement will be executed in its own transaction, not the transactional context of the spawning process.</remarks> public string OnExecuteConnectStatement { get { return _onExecuteConnectStatement; } set { _onExecuteConnectStatement = value; } } private string _onBrowseConnectStatement; /// <summary>A D4 expression denoting an SQL statement in the target dialect to be executed on all new browse connections.</summary> /// <remarks>The statement will be executed in its own transaction, not the transactional context of the spawning process.</remarks> public string OnBrowseConnectStatement { get { return _onBrowseConnectStatement; } set { _onBrowseConnectStatement = value; } } private bool _supportsSubSelectInSelectClause = true; public bool SupportsSubSelectInSelectClause { get { return _supportsSubSelectInSelectClause; } set { _supportsSubSelectInSelectClause = value; } } private bool _supportsSubSelectInWhereClause = true; public bool SupportsSubSelectInWhereClause { get { return _supportsSubSelectInWhereClause; } set { _supportsSubSelectInWhereClause = value; } } private bool _supportsSubSelectInGroupByClause = true; public bool SupportsSubSelectInGroupByClause { get { return _supportsSubSelectInGroupByClause; } set { _supportsSubSelectInGroupByClause = value; } } private bool _supportsSubSelectInHavingClause = true; public bool SupportsSubSelectInHavingClause { get { return _supportsSubSelectInHavingClause; } set { _supportsSubSelectInHavingClause = value; } } private bool _supportsSubSelectInOrderByClause = true; public bool SupportsSubSelectInOrderByClause { get { return _supportsSubSelectInOrderByClause; } set { _supportsSubSelectInOrderByClause = value; } } // True if the device supports nesting in the from clause. // This is also used to determine whether an extend whose source has introduced columns (an add following another add), will nest the resulting expression, or use replacement referencing to avoid the nesting. private bool _supportsNestedFrom = true; public bool SupportsNestedFrom { get { return _supportsNestedFrom; } set { _supportsNestedFrom = value; } } private bool _supportsNestedCorrelation = true; public bool SupportsNestedCorrelation { get { return _supportsNestedCorrelation; } set { _supportsNestedCorrelation = value; } } // True if the device supports the use of expressions in the order by clause private bool _supportsOrderByExpressions = false; public bool SupportsOrderByExpressions { get { return _supportsOrderByExpressions; } set { _supportsOrderByExpressions = value; } } // True if the device supports the ISO standard syntax "NULLS FIRST/LAST" in the order by clause private bool _supportsOrderByNullsFirstLast = false; public bool SupportsOrderByNullsFirstLast { get { return _supportsOrderByNullsFirstLast; } set { _supportsOrderByNullsFirstLast = value; } } // True if the order by clause is processed as part of the query context // If this is false the order must be specified in terms of the result set columns, rather than the range variable columns within the query private bool _isOrderByInContext = true; public bool IsOrderByInContext { get { return _isOrderByInContext; } set { _isOrderByInContext = value; } } // True if insert statements should be constructed using a values clause, false to use a select expression private bool _useValuesClauseInInsert = true; public bool UseValuesClauseInInsert { get { return _useValuesClauseInInsert; } set { _useValuesClauseInInsert = value; } } private int _commandTimeout = -1; /// <summary>The amount of time in seconds to wait before timing out waiting for a command to complete.</summary> /// <remarks> /// The default value for this property is -1, indicating that the default timeout value for the connectivity /// implementation used by the device should be used. Beyond that, the interpretation of this value depends on /// the connectivity implementation used by the device. For most implementations, a value of 0 indicates an /// infinite timeout. /// </remarks> public int CommandTimeout { get { return _commandTimeout; } set { _commandTimeout = value; } } #if USEISTRING private bool FIsCaseSensitive; public bool IsCaseSensitive { get { return FIsCaseSensitive; } set { FIsCaseSensitive = value; } } #endif public virtual ErrorSeverity ExceptionOccurred(Exception exception) { return ErrorSeverity.Application; } protected int _maxIdentifierLength = int.MaxValue; public int MaxIdentifierLength { get { return _maxIdentifierLength; } set { _maxIdentifierLength = value; } } protected virtual void SetMaxIdentifierLength() {} // verify that all types in the given table are mapped into this device public override void CheckSupported(Plan plan, TableVar tableVar) { // verify that the types of all columns have type maps foreach (Schema.Column column in tableVar.DataType.Columns) if (!(column.DataType is Schema.ScalarType) || (ResolveDeviceScalarType(plan, (Schema.ScalarType)column.DataType) == null)) if (Compiler.CouldGenerateDeviceScalarTypeMap(plan, this, (Schema.ScalarType)column.DataType)) { D4.AlterDeviceStatement statement = new D4.AlterDeviceStatement(); statement.DeviceName = Name; // BTR 1/18/2007 -> This really should be being marked as generated, however doing so // changes the dependency reporting for scalar type maps, and causes some catalog dependency errors, // so I cannot justify making this change in this version. Perhaps at some point, but not now... statement.CreateDeviceScalarTypeMaps.Add(new D4.DeviceScalarTypeMap(column.DataType.Name)); plan.ExecuteNode(Compiler.Compile(plan, statement)); ResolveDeviceScalarType(plan, (Schema.ScalarType)column.DataType); // Reresolve to attach a dependency to the generated map } else throw new SchemaException(SchemaException.Codes.UnsupportedScalarType, tableVar.Name, Name, column.DataType.Name, column.Name); foreach (Schema.Key key in tableVar.Keys) foreach (Schema.TableVarColumn column in key.Columns) if (!SupportsComparison(plan, column.DataType)) throw new SchemaException(SchemaException.Codes.UnsupportedKeyType, tableVar.Name, Name, column.DataType.Name, column.Name); } public override D4.ClassDefinition GetDefaultOperatorClassDefinition(D4.MetaData metaData) { if ((metaData != null) && (metaData.Tags.Contains("Storage.TranslationString"))) return new D4.ClassDefinition ( "SQLDevice.SQLUserOperator", new D4.ClassAttributeDefinition[] { new D4.ClassAttributeDefinition("TranslationString", metaData.Tags["Storage.TranslationString"].Value), new D4.ClassAttributeDefinition("ContextLiteralParameterIndexes", D4.MetaData.GetTag(metaData, "Storage.ContextLiteralParameterIndexes", "")) } ); return null; } public override D4.ClassDefinition GetDefaultSelectorClassDefinition() { return new D4.ClassDefinition("SQLDevice.SQLScalarSelector"); } public override D4.ClassDefinition GetDefaultReadAccessorClassDefinition() { return new D4.ClassDefinition("SQLDevice.SQLScalarReadAccessor"); } public override D4.ClassDefinition GetDefaultWriteAccessorClassDefinition() { return new D4.ClassDefinition("SQLDevice.SQLScalarWriteAccessor"); } public override DeviceCapability Capabilities { get { return DeviceCapability.RowLevelInsert | DeviceCapability.RowLevelUpdate | DeviceCapability.RowLevelDelete; } } protected override void InternalRegister(ServerProcess process) { base.InternalRegister(process); RegisterSystemObjectMaps(process); } protected void RunScript(ServerProcess process, string script) { // Note that this is also used to load the internal system catalog. IServerScript localScript = ((IServerProcess)process).PrepareScript(script); try { localScript.Execute(null); } finally { ((IServerProcess)process).UnprepareScript(localScript); } } protected virtual void RegisterSystemObjectMaps(ServerProcess process) {} // Emitter public virtual TextEmitter Emitter { get { SQLTextEmitter emitter = InternalCreateEmitter(); emitter.UseStatementTerminator = UseStatementTerminator; emitter.UseQuotedIdentifiers = UseQuotedIdentifiers; return emitter; } } protected virtual SQLTextEmitter InternalCreateEmitter() { return new SQLTextEmitter(); } // Prepare protected override DevicePlan CreateDevicePlan(Plan plan, PlanNode planNode) { return new SQLDevicePlan(plan, this, planNode); } protected override DevicePlanNode InternalPrepare(DevicePlan plan, PlanNode planNode) { SQLDevicePlan devicePlan = (SQLDevicePlan)plan; if (planNode is TableNode) { devicePlan.DevicePlanNode = new TableSQLDevicePlanNode(planNode); } else if (planNode.DataType is Schema.IRowType) { var rowDeviceNode = new RowSQLDevicePlanNode(planNode); var rowType = (Schema.IRowType)planNode.DataType; for (var index = 0; index < rowType.Columns.Count; index++) { if (rowType.Columns[index].DataType is IScalarType) { rowDeviceNode.MappedTypes.Add((SQLScalarType)ResolveDeviceScalarType(devicePlan.Plan, (ScalarType)rowType.Columns[index].DataType)); } else { rowDeviceNode.MappedTypes.Add(null); // The expression will not be supported anyway, so report nothing for the type map. } } devicePlan.DevicePlanNode = rowDeviceNode; } else if (planNode.DataType is Schema.IScalarType) { var scalarDeviceNode = new ScalarSQLDevicePlanNode(planNode); scalarDeviceNode.MappedType = (SQLScalarType)ResolveDeviceScalarType(devicePlan.Plan, (ScalarType)planNode.DataType); devicePlan.DevicePlanNode = scalarDeviceNode; } else { devicePlan.DevicePlanNode = new SQLDevicePlanNode(planNode); } if (!((planNode is TableNode) || (planNode.DataType is Schema.IRowType))) { devicePlan.PushScalarContext(); devicePlan.CurrentQueryContext().IsSelectClause = true; } try { if ((planNode.DataType != null) && planNode.DataType.Is(plan.Plan.Catalog.DataTypes.SystemBoolean)) devicePlan.EnterContext(true); try { devicePlan.DevicePlanNode.Statement = Translate(devicePlan, planNode); if (devicePlan.IsSupported) { if (planNode.DataType != null) { if (planNode.DataType.Is(plan.Plan.Catalog.DataTypes.SystemBoolean)) { devicePlan.DevicePlanNode.Statement = new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( (Expression)devicePlan.DevicePlanNode.Statement, new ValueExpression(1) ) }, new CaseElseExpression(new ValueExpression(0)) ); } // Ensure that the statement is a unary select expression for the device Cursors... if ((planNode is TableNode) && (devicePlan.DevicePlanNode.Statement is QueryExpression) && (((QueryExpression)devicePlan.DevicePlanNode.Statement).TableOperators.Count > 0)) devicePlan.DevicePlanNode.Statement = NestQueryExpression(devicePlan, ((TableNode)planNode).TableVar, devicePlan.DevicePlanNode.Statement); if (!(devicePlan.DevicePlanNode.Statement is SelectStatement)) { if (!(devicePlan.DevicePlanNode.Statement is QueryExpression)) { if (!(devicePlan.DevicePlanNode.Statement is SelectExpression)) { SelectExpression selectExpression = new SelectExpression(); selectExpression.SelectClause = new SelectClause(); selectExpression.SelectClause.Columns.Add(new ColumnExpression((Expression)devicePlan.DevicePlanNode.Statement, "dummy1")); selectExpression.FromClause = new CalculusFromClause(GetDummyTableSpecifier()); devicePlan.DevicePlanNode.Statement = selectExpression; } QueryExpression queryExpression = new QueryExpression(); queryExpression.SelectExpression = (SelectExpression)devicePlan.DevicePlanNode.Statement; devicePlan.DevicePlanNode.Statement = queryExpression; } SelectStatement selectStatement = new SelectStatement(); selectStatement.QueryExpression = (QueryExpression)devicePlan.DevicePlanNode.Statement; devicePlan.DevicePlanNode.Statement = selectStatement; } if (planNode is TableNode) { devicePlan.DevicePlanNode.Statement = TranslateOrder(devicePlan, (TableNode)planNode, (SelectStatement)devicePlan.DevicePlanNode.Statement, false); ((TableSQLDevicePlanNode)devicePlan.DevicePlanNode).IsAggregate = devicePlan.CurrentQueryContext().IsAggregate; if (!devicePlan.IsSupported) return null; } } return devicePlan.DevicePlanNode; } return null; } finally { if ((planNode.DataType != null) && planNode.DataType.Is(plan.Plan.Catalog.DataTypes.SystemBoolean)) devicePlan.ExitContext(); } } finally { // TODO: This condition is different than the push context above, is this intentional? if (!(planNode is TableNode)) devicePlan.PopScalarContext(); } } public virtual void DetermineCursorBehavior(Plan plan, TableNode tableNode) { tableNode.RequestedCursorType = plan.CursorContext.CursorType; tableNode.CursorType = plan.CursorContext.CursorType; tableNode.CursorCapabilities = CursorCapability.Navigable | (plan.CursorContext.CursorCapabilities & CursorCapability.Updateable) | (plan.CursorContext.CursorCapabilities & CursorCapability.Elaborable); tableNode.CursorIsolation = plan.CursorContext.CursorIsolation; // Ensure that the node has an order that is a superset of some key Schema.Key clusteringKey = Compiler.FindClusteringKey(plan, tableNode.TableVar); if ((tableNode.Order == null) && (clusteringKey.Columns.Count > 0)) tableNode.Order = Compiler.OrderFromKey(plan, clusteringKey); if (tableNode.Order != null) { // Ensure that the order is unique bool orderUnique = false; Schema.OrderColumn newColumn; foreach (Schema.Key key in tableNode.TableVar.Keys) if (Compiler.OrderIncludesKey(plan, tableNode.Order, key)) { orderUnique = true; break; } if (!orderUnique) foreach (Schema.TableVarColumn column in Compiler.FindClusteringKey(plan, tableNode.TableVar).Columns) if (!tableNode.Order.Columns.Contains(column.Name)) { newColumn = new Schema.OrderColumn(column, true); newColumn.Sort = Compiler.GetSort(plan, column.DataType); newColumn.IsDefaultSort = true; tableNode.Order.Columns.Add(newColumn); } else { if (!System.Object.ReferenceEquals(tableNode.Order.Columns[column.Name].Sort, ((ScalarType)tableNode.Order.Columns[column.Name].Column.DataType).UniqueSort)) tableNode.Order.Columns[column.Name].Sort = Compiler.GetUniqueSort(plan, (ScalarType)column.DataType); } } } /// <summary> /// This method returns a valid identifier for the specific SQL system in which it is called. If overloaded, it must be completely deterministic. /// </summary> /// <param name="identifier">The identifier to check</param> /// <returns>A valid identifier, based as close as possible to AIdentifier</returns> public string EnsureValidIdentifier(string identifier) { return EnsureValidIdentifier(identifier, _maxIdentifierLength); } public virtual unsafe string EnsureValidIdentifier(string identifier, int maxLength) { // first check to see if it is not reserved if (IsReservedWord(identifier)) { identifier += "_DAE"; } // Replace all double underscores with triple underscores identifier = identifier.Replace("__", "___"); // Replace all qualifiers with double underscores identifier = identifier.Replace(".", "__"); // then check to see if it has a name longer than AMaxLength characters if (identifier.Length > maxLength) { byte[] byteArray = new byte[4]; fixed (byte* array = &byteArray[0]) { *((int*)array) = identifier.GetHashCode(); } string stringValue = Convert.ToBase64String(byteArray); identifier = identifier.Substring(0, maxLength - stringValue.Length) + stringValue; } // replace invalid characters identifier = identifier.Replace("+", "_"); identifier = identifier.Replace("/", "_"); identifier = identifier.Replace("=", "_"); return identifier; } protected virtual bool IsReservedWord(string word) { return false; } public string ToSQLIdentifier(string identifier) { return EnsureValidIdentifier(identifier); } public virtual string ToSQLIdentifier(string identifier, D4.MetaData metaData) { return D4.MetaData.GetTag(metaData, "Storage.Name", ToSQLIdentifier(identifier)); } //public virtual string ToSQLIdentifier(string AIdentifier, D4.MetaData AMetaData) public virtual string ToSQLIdentifier(Schema.Object objectValue) { if ((objectValue is CatalogObject) && (((CatalogObject)objectValue).Library != null) && !UseQualifiedNames) return ToSQLIdentifier(DAE.Schema.Object.RemoveQualifier(objectValue.Name, ((CatalogObject)objectValue).Library.Name), objectValue.MetaData); else return ToSQLIdentifier(objectValue.Name, objectValue.MetaData); } public virtual string ConvertNonIdentifierCharacter(char invalidChar) { switch (invalidChar) { case '#' : return "POUND"; case '~' : return "TILDE"; case '%' : return "PERCENT"; case '^' : return "CARET"; case '&' : return "AMP"; case '(' : return "LPAR"; case ')' : return "RPAR"; case '-' : return "HYPHEN"; case '{' : return "LBRACE"; case '}' : return "RBRACE"; case '\'' : return "APOS"; case '.' : return "PERIOD"; case '\\' : return "BSLASH"; case '/' : return "FSLASH"; case '`' : return "ACCENT"; default : return Convert.ToUInt16(invalidChar).ToString(); } } public virtual string FromSQLIdentifier(string identifier) { StringBuilder localIdentifier = new StringBuilder(); for (int index = 0; index < identifier.Length; index++) if (!Char.IsLetterOrDigit(identifier[index]) && (identifier[index] != '_')) localIdentifier.Append(ConvertNonIdentifierCharacter(identifier[index])); else localIdentifier.Append(identifier[index]); identifier = localIdentifier.ToString(); if (D4.ReservedWords.Contains(identifier) || ((identifier.Length > 0) && Char.IsDigit(identifier[0]))) identifier = String.Format("_{0}", identifier); return identifier; } public virtual SelectExpression FindSelectExpression(Statement statement) { if (statement is QueryExpression) return ((QueryExpression)statement).SelectExpression; else if (statement is SelectExpression) return (SelectExpression)statement; else throw new SQLException(SQLException.Codes.InvalidStatementClass); } /// <remarks> In some contexts (such as an add) it is desireable to nest contexts to avoid duplicating entire /// extend expressions. Such contexts should pass true to ANestIfSupported. Theoretically, each such context /// could detect references to the introduced columns before nesting, but for now their presence is used. </remarks> public virtual SelectExpression EnsureUnarySelectExpression(SQLDevicePlan devicePlan, TableVar tableVar, Statement statement, bool nestIfSupported) { if ((statement is QueryExpression) && (((QueryExpression)statement).TableOperators.Count > 0)) return NestQueryExpression(devicePlan, tableVar, statement); else if (nestIfSupported && devicePlan.Device.SupportsNestedFrom && (devicePlan.CurrentQueryContext().AddedColumns.Count > 0)) { devicePlan.TranslationMessages.Add(new Schema.TranslationMessage("The query is being nested to avoid unnecessary repetition of column expressions.")); return NestQueryExpression(devicePlan, tableVar, statement); } else return FindSelectExpression(statement); } public virtual SelectExpression NestQueryExpression(SQLDevicePlan devicePlan, TableVar tableVar, Statement statement) { if (!devicePlan.Device.SupportsNestedFrom) { devicePlan.IsSupported = false; devicePlan.TranslationMessages.Add(new Schema.TranslationMessage("Plan is not supported because the device does not support nesting in the from clause.")); } if (((devicePlan.CurrentQueryContext().ReferenceFlags & SQLReferenceFlags.HasCorrelation) != 0) && !devicePlan.Device.SupportsNestedCorrelation) { devicePlan.IsSupported = false; devicePlan.TranslationMessages.Add(new Schema.TranslationMessage("Plan is not supported because the device does not support nested correlation.")); } SQLRangeVar rangeVar = new SQLRangeVar(devicePlan.GetNextTableAlias()); foreach (TableVarColumn column in tableVar.Columns) { SQLRangeVarColumn nestedRangeVarColumn = devicePlan.CurrentQueryContext().GetRangeVarColumn(column.Name); SQLRangeVarColumn rangeVarColumn = new SQLRangeVarColumn(column, rangeVar.Name, nestedRangeVarColumn.Alias); rangeVar.Columns.Add(rangeVarColumn); } devicePlan.PopQueryContext(); devicePlan.PushQueryContext(); devicePlan.CurrentQueryContext().RangeVars.Add(rangeVar); SelectExpression selectExpression = devicePlan.Device.FindSelectExpression(statement); SelectExpression newSelectExpression = new SelectExpression(); if (selectExpression.FromClause is AlgebraicFromClause) newSelectExpression.FromClause = new AlgebraicFromClause(new TableSpecifier((Expression)statement, rangeVar.Name)); else newSelectExpression.FromClause = new CalculusFromClause(new TableSpecifier((Expression)statement, rangeVar.Name)); newSelectExpression.SelectClause = new SelectClause(); foreach (TableVarColumn column in tableVar.Columns) newSelectExpression.SelectClause.Columns.Add(devicePlan.CurrentQueryContext().GetRangeVarColumn(column.Name).GetColumnExpression()); return newSelectExpression; } protected virtual Statement FromScalar(SQLDevicePlan devicePlan, PlanNode planNode) { SQLScalarType scalarType = (SQLScalarType)ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType); if (planNode.IsLiteral && planNode.IsDeterministic && !scalarType.UseParametersForLiterals) { object tempValue = devicePlan.Plan.EvaluateLiteralArgument(planNode, planNode.Description); Expression valueExpression = null; if (tempValue == null) valueExpression = new CastExpression(new ValueExpression(null, TokenType.Nil), scalarType.ParameterDomainName()); else valueExpression = new ValueExpression(scalarType.ParameterFromScalar(devicePlan.Plan.ValueManager, tempValue)); if (planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean) && devicePlan.IsBooleanContext()) return new BinaryExpression(new ValueExpression(1), "iEqual", valueExpression); else return valueExpression; } else { string parameterName = String.Format("P{0}", devicePlan.DevicePlanNode.PlanParameters.Count + 1); SQLPlanParameter planParameter = new SQLPlanParameter ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(), null, SQLDirection.In, GetParameterMarker(scalarType) ), planNode, scalarType ); devicePlan.DevicePlanNode.PlanParameters.Add(planParameter); devicePlan.CurrentQueryContext().ReferenceFlags |= SQLReferenceFlags.HasParameters; if (planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean) && devicePlan.IsBooleanContext()) return new BinaryExpression(new ValueExpression(1), "iEqual", new QueryParameterExpression(parameterName)); else return new QueryParameterExpression(parameterName); } } public string GetParameterMarker(SQLScalarType scalarType, TableVarColumn column) { return GetParameterMarker(scalarType, column.MetaData); } public string GetParameterMarker(SQLScalarType scalarType) { return GetParameterMarker(scalarType, (D4.MetaData)null); } public virtual string GetParameterMarker(SQLScalarType scalarType, D4.MetaData metaData) { return null; } protected virtual Statement TranslateStackReference(SQLDevicePlan devicePlan, StackReferenceNode node) { return FromScalar(devicePlan, new StackReferenceNode(node.DataType, node.Location - devicePlan.Stack.Count)); } protected virtual Statement TranslateStackColumnReference(SQLDevicePlan devicePlan, StackColumnReferenceNode node) { // If this is referencing an item on the device plan stack, translate as an identifier, // otherwise, translate as a query parameter if (node.Location < devicePlan.Stack.Count) { Expression expression = new QualifiedFieldExpression(); SQLRangeVarColumn rangeVarColumn = null; if (DAE.Schema.Object.Qualifier(node.Identifier) == Keywords.Left) rangeVarColumn = devicePlan.CurrentJoinContext().LeftQueryContext.FindRangeVarColumn(DAE.Schema.Object.Dequalify(node.Identifier)); else if (DAE.Schema.Object.Qualifier(node.Identifier) == Keywords.Right) rangeVarColumn = devicePlan.CurrentJoinContext().RightQueryContext.FindRangeVarColumn(DAE.Schema.Object.Dequalify(node.Identifier)); else rangeVarColumn = devicePlan.FindRangeVarColumn(node.Identifier, false); if (rangeVarColumn == null) { devicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the reference to column ""{0}"" is out of context.", node.Identifier), node)); devicePlan.IsSupported = false; } else expression = rangeVarColumn.GetExpression(); if (devicePlan.IsBooleanContext()) return new BinaryExpression(expression, "iEqual", new ValueExpression(1)); // <> 0 is more robust, but = 1 is potentially more efficient return expression; } else { #if USECOLUMNLOCATIONBINDING return FromScalar(ADevicePlan, new StackColumnReferenceNode(ANode.Identifier, ANode.DataType, ANode.Location - ADevicePlan.Stack.Count, ANode.ColumnLocation)); #else return FromScalar(devicePlan, new StackColumnReferenceNode(node.Identifier, node.DataType, node.Location - devicePlan.Stack.Count)); #endif } } protected virtual Statement TranslateExtractColumnNode(SQLDevicePlan devicePlan, ExtractColumnNode node) { StackReferenceNode sourceNode = node.Nodes[0] as StackReferenceNode; if (sourceNode != null) { if (sourceNode.Location < devicePlan.Stack.Count) { Expression expression = new QualifiedFieldExpression(); SQLRangeVarColumn rangeVarColumn = null; if (DAE.Schema.Object.EnsureUnrooted(sourceNode.Identifier) == Keywords.Left) rangeVarColumn = devicePlan.CurrentJoinContext().LeftQueryContext.FindRangeVarColumn(node.Identifier); else if (DAE.Schema.Object.EnsureUnrooted(sourceNode.Identifier) == Keywords.Right) rangeVarColumn = devicePlan.CurrentJoinContext().RightQueryContext.FindRangeVarColumn(node.Identifier); else rangeVarColumn = devicePlan.FindRangeVarColumn(DAE.Schema.Object.Qualify(node.Identifier, sourceNode.Identifier), false); if (rangeVarColumn == null) { devicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the reference to column ""{0}"" is out of context.", node.Identifier), node)); devicePlan.IsSupported = false; } else expression = rangeVarColumn.GetExpression(); if (devicePlan.IsBooleanContext()) return new BinaryExpression(expression, "iEqual", new ValueExpression(1)); // <> 0 is more robust, but = 1 is potentially more efficient return expression; } else return FromScalar(devicePlan, new StackColumnReferenceNode(node.Identifier, node.DataType, sourceNode.Location - devicePlan.Stack.Count)); } else { Statement statement = Translate(devicePlan, node.Nodes[0]); if (devicePlan.IsSupported) { SelectExpression expression = FindSelectExpression(statement); ColumnExpression columnExpression = expression.SelectClause.Columns[ToSQLIdentifier(((Schema.IRowType)node.Nodes[0].DataType).Columns[node.Identifier].Name)]; expression.SelectClause.Columns.Clear(); expression.SelectClause.Columns.Add(columnExpression); if (node.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean)) if (!devicePlan.IsBooleanContext()) statement = new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( (Expression)statement, new ValueExpression(1) ) }, new CaseElseExpression(new ValueExpression(0)) ); else statement = new BinaryExpression((Expression)statement, "iEqual", new ValueExpression(1)); } return statement; } } protected virtual string TooManyRowsOperator() { return "DAE_TooManyRows"; } protected virtual Statement TranslateExtractRowNode(SQLDevicePlan devicePlan, ExtractRowNode node) { // Row extraction cannot be supported unless each column in the row being extracted has a map for equality comparison. Otherwise, the SQL Server // will complain that the 'blob column' cannot be used the given context (such as a subquery). foreach (Schema.Column column in ((Schema.IRowType)node.DataType).Columns) if (!SupportsEqual(devicePlan.Plan, column.DataType)) { devicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not support equality comparison for values of type ""{0}"" for column ""{1}"".", column.DataType.Name, column.Name), node)); devicePlan.IsSupported = false; return new CallExpression(); } // If the indexer is based on a key, Row extraction is translated as the expression // Otherwise, row extraction is translated as the expression, plus a where clause that counts the result and calls DAE_TooManyRows if the count is > 1 // DAE_TooManyRows throws a TOO_MANY_ROWS exception, which is caught by the SQL Device and converted to an Application 105199, just as if it had been evaluated by the DAE // Note that in the case of MSSQL Server, the error is thrown by attempting to cast the message to an int. if (node.IsSingleton) { return TranslateExpression(devicePlan, node.Nodes[0], false); } else { Expression countExpression = TranslateExpression(devicePlan, node.Nodes[0], false); SelectExpression countSelectExpression = NestQueryExpression(devicePlan, ((TableNode)node.Nodes[0]).TableVar, countExpression); countSelectExpression.SelectClause = new SelectClause(); AggregateCallExpression countCallExpression = new AggregateCallExpression(); countCallExpression.Identifier = "Count"; countCallExpression.Expressions.Add(new QualifiedFieldExpression("*")); countSelectExpression.SelectClause.Columns.Add(new ColumnExpression(countCallExpression)); Expression extractionCondition = new BinaryExpression ( new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( new BinaryExpression ( countSelectExpression, "iGreater", new ValueExpression(1) ), new CallExpression(TooManyRowsOperator(), new Expression[] { new ValueExpression(1) }) ) }, new CaseElseExpression(new ValueExpression(1)) ), "iEqual", new ValueExpression(1) ); // Reset the query context and retranslate the source devicePlan.PopQueryContext(); devicePlan.PushQueryContext(); Expression sourceExpression = TranslateExpression(devicePlan, node.Nodes[0], false); SelectExpression selectExpression = EnsureUnarySelectExpression(devicePlan, ((TableNode)node.Nodes[0]).TableVar, sourceExpression, false); if (selectExpression.WhereClause == null) selectExpression.WhereClause = new WhereClause(); if (selectExpression.WhereClause.Expression == null) selectExpression.WhereClause.Expression = extractionCondition; else selectExpression.WhereClause.Expression = new BinaryExpression(selectExpression.WhereClause.Expression, "iAnd", extractionCondition); return selectExpression; } } protected virtual Statement TranslateValueNode(SQLDevicePlan devicePlan, ValueNode node) { if (node.DataType.IsGeneric && ((node.Value == null) || (node.Value == DBNull.Value))) return new ValueExpression(null); return FromScalar(devicePlan, node); } protected virtual Statement TranslateAsNode(SQLDevicePlan devicePlan, AsNode node) { return new CastExpression((Expression)Translate(devicePlan, node.Nodes[0]), ((SQLScalarType)devicePlan.Device.ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)node.DataType)).ParameterDomainName()); } public virtual Expression TranslateExpression(SQLDevicePlan devicePlan, PlanNode node, bool isBooleanContext) { devicePlan.EnterContext(isBooleanContext); try { if (!isBooleanContext && node.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean)) { // case when <expression> then 1 else 0 end devicePlan.EnterContext(true); try { return new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( (Expression)Translate(devicePlan, node), new ValueExpression(1) ) }, new CaseElseExpression(new ValueExpression(0)) ); } finally { devicePlan.ExitContext(); } } else return (Expression)Translate(devicePlan, node); } finally { devicePlan.ExitContext(); } } protected virtual Statement TranslateConditionNode(SQLDevicePlan devicePlan, ConditionNode node) { return new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( TranslateExpression(devicePlan, node.Nodes[0], true), TranslateExpression(devicePlan, node.Nodes[1], false) ) }, new CaseElseExpression(TranslateExpression(devicePlan, node.Nodes[2], false)) ); } protected virtual Statement TranslateConditionedCaseNode(SQLDevicePlan devicePlan, ConditionedCaseNode node) { CaseExpression caseExpression = new CaseExpression(); foreach (ConditionedCaseItemNode localNode in node.Nodes) { if (localNode.Nodes.Count == 2) caseExpression.CaseItems.Add ( new CaseItemExpression ( TranslateExpression(devicePlan, localNode.Nodes[0], true), TranslateExpression(devicePlan, localNode.Nodes[1], false) ) ); else caseExpression.ElseExpression = new CaseElseExpression(TranslateExpression(devicePlan, localNode.Nodes[0], false)); } return caseExpression; } protected virtual Statement TranslateSelectedConditionedCaseNode(SQLDevicePlan devicePlan, SelectedConditionedCaseNode node) { CaseExpression caseExpression = new CaseExpression(); caseExpression.Expression = TranslateExpression(devicePlan, node.Nodes[0], false); for (int index = 2; index < node.Nodes.Count; index++) { ConditionedCaseItemNode localNode = (ConditionedCaseItemNode)node.Nodes[index]; if (localNode.Nodes.Count == 2) caseExpression.CaseItems.Add ( new CaseItemExpression ( TranslateExpression(devicePlan, localNode.Nodes[0], false), TranslateExpression(devicePlan, localNode.Nodes[1], false) ) ); else caseExpression.ElseExpression = new CaseElseExpression(TranslateExpression(devicePlan, localNode.Nodes[0], false)); } return caseExpression; } public virtual TableSpecifier GetDummyTableSpecifier() { SelectExpression selectExpression = new SelectExpression(); selectExpression.SelectClause = new SelectClause(); selectExpression.SelectClause.Columns.Add(new ColumnExpression(new ValueExpression(0), "dummy1")); return new TableSpecifier(selectExpression, "dummy1"); } protected virtual Statement TranslateListNode(SQLDevicePlan devicePlan, ListNode node) { if (!devicePlan.CurrentQueryContext().IsListContext) { devicePlan.TranslationMessages.Add(new Schema.TranslationMessage(@"Plan is not supported because the device only supports list expressions as the right argument to an invocation of the membership operator (in).", node)); devicePlan.IsSupported = false; return new CallExpression(); } ListExpression listExpression = new ListExpression(); foreach (PlanNode localNode in node.Nodes) listExpression.Expressions.Add(TranslateExpression(devicePlan, localNode, false)); return listExpression; } protected virtual Statement TranslateRowSelectorNode(SQLDevicePlan devicePlan, RowSelectorNode node) { SelectExpression selectExpression = new SelectExpression(); selectExpression.SelectClause = new SelectClause(); if (_supportsAlgebraicFromClause) selectExpression.FromClause = new AlgebraicFromClause(GetDummyTableSpecifier()); else selectExpression.FromClause = new CalculusFromClause(GetDummyTableSpecifier()); devicePlan.PushScalarContext(); try { for (int index = 0; index < node.DataType.Columns.Count; index++) { SQLRangeVarColumn rangeVarColumn = devicePlan.FindRangeVarColumn(node.DataType.Columns[index].Name, false); if (rangeVarColumn != null) { rangeVarColumn.Expression = TranslateExpression(devicePlan, node.Nodes[index], false); selectExpression.SelectClause.Columns.Add(rangeVarColumn.GetColumnExpression()); } else selectExpression.SelectClause.Columns.Add(new ColumnExpression(TranslateExpression(devicePlan, node.Nodes[index], false), ToSQLIdentifier(node.DataType.Columns[index].Name))); } devicePlan.CurrentQueryContext().ParentContext.ReferenceFlags |= devicePlan.CurrentQueryContext().ReferenceFlags; } finally { devicePlan.PopScalarContext(); } return selectExpression; } protected virtual Statement TranslateTableSelectorNode(SQLDevicePlan devicePlan, TableSelectorNode node) { QueryExpression queryExpression = new QueryExpression(); devicePlan.CurrentQueryContext().RangeVars.Add(new SQLRangeVar(devicePlan.GetNextTableAlias())); SQLRangeVar rangeVar = new SQLRangeVar(devicePlan.GetNextTableAlias()); foreach (TableVarColumn column in node.TableVar.Columns) devicePlan.CurrentQueryContext().AddedColumns.Add(new SQLRangeVarColumn(column, String.Empty, devicePlan.Device.ToSQLIdentifier(column), devicePlan.Device.ToSQLIdentifier(column.Name))); foreach (PlanNode localNode in node.Nodes) { Statement statement = Translate(devicePlan, localNode); if (devicePlan.IsSupported) { SelectExpression selectExpression = devicePlan.Device.FindSelectExpression(statement); if (queryExpression.SelectExpression == null) queryExpression.SelectExpression = selectExpression; else queryExpression.TableOperators.Add(new TableOperatorExpression(TableOperator.Union, false, selectExpression)); } } return queryExpression; } protected virtual Statement TranslateInsertNode(SQLDevicePlan devicePlan, InsertNode node) { if (devicePlan.Plan.ServerProcess.NonLogged) CheckCapability(DeviceCapability.NonLoggedOperations); InsertStatement statement = new InsertStatement(); statement.InsertClause = new InsertClause(); statement.InsertClause.TableExpression = new TableExpression(); BaseTableVar target = (BaseTableVar)((TableVarNode)node.Nodes[1]).TableVar; statement.InsertClause.TableExpression.TableSchema = D4.MetaData.GetTag(target.MetaData, "Storage.Schema", Schema); statement.InsertClause.TableExpression.TableName = ToSQLIdentifier(target); foreach (Column column in ((TableNode)node.Nodes[0]).DataType.Columns) statement.InsertClause.Columns.Add(new InsertFieldExpression(ToSQLIdentifier(column.Name))); statement.Values = TranslateExpression(devicePlan, node.Nodes[0], false); return statement; } protected virtual Statement TranslateUpdateNode(SQLDevicePlan devicePlan, UpdateNode node) { if (devicePlan.Plan.ServerProcess.NonLogged) CheckCapability(DeviceCapability.NonLoggedOperations); BaseTableVar target = ((BaseTableVar)((TableVarNode)node.Nodes[0]).TableVar); UpdateStatement statement = new UpdateStatement(); statement.UpdateClause = new UpdateClause(); statement.UpdateClause.TableExpression = new TableExpression(); statement.UpdateClause.TableExpression.TableSchema = D4.MetaData.GetTag(target.MetaData, "Storage.Schema", Schema); statement.UpdateClause.TableExpression.TableName = ToSQLIdentifier(target); devicePlan.Stack.Push(new Symbol(String.Empty, target.DataType.RowType)); try { for (int index = 1; index < node.Nodes.Count; index++) { UpdateFieldExpression fieldExpression = new UpdateFieldExpression(); UpdateColumnNode columnNode = (UpdateColumnNode)node.Nodes[index]; #if USECOLUMNLOCATIONBINDING fieldExpression.FieldName = ToSQLIdentifier(target.DataType.Columns[columnNode.ColumnLocation].Name); #else fieldExpression.FieldName = ToSQLIdentifier(target.DataType.Columns[columnNode.ColumnName].Name); #endif fieldExpression.Expression = TranslateExpression(devicePlan, columnNode.Nodes[0], false); statement.UpdateClause.Columns.Add(fieldExpression); } } finally { devicePlan.Stack.Pop(); } return statement; } protected virtual Statement TranslateDeleteNode(SQLDevicePlan devicePlan, DeleteNode node) { if (devicePlan.Plan.ServerProcess.NonLogged) CheckCapability(DeviceCapability.NonLoggedOperations); DeleteStatement statement = new DeleteStatement(); statement.DeleteClause = new DeleteClause(); statement.DeleteClause.TableExpression = new TableExpression(); BaseTableVar target = (BaseTableVar)((TableVarNode)node.Nodes[0]).TableVar; statement.DeleteClause.TableExpression.TableSchema = D4.MetaData.GetTag(target.MetaData, "Storage.Schema", Schema); statement.DeleteClause.TableExpression.TableName = ToSQLIdentifier(target); return statement; } protected virtual string GetIndexName(string tableName, Key key) { if ((key.MetaData != null) && key.MetaData.Tags.Contains("Storage.Name")) return key.MetaData.Tags["Storage.Name"].Value; else { StringBuilder indexName = new StringBuilder(); indexName.AppendFormat("UIDX_{0}", tableName); foreach (TableVarColumn column in key.Columns) indexName.AppendFormat("_{0}", (column.Name)); return EnsureValidIdentifier(indexName.ToString()); } } protected virtual string GetIndexName(string tableName, Order order) { if ((order.MetaData != null) && order.MetaData.Tags.Contains("Storage.Name")) return order.MetaData.Tags["Storage.Name"].Value; else { StringBuilder indexName = new StringBuilder(); indexName.AppendFormat("IDX_{0}", tableName); foreach (OrderColumn column in order.Columns) indexName.AppendFormat("_{0}", (column.Column.Name)); return EnsureValidIdentifier(indexName.ToString()); } } protected virtual Statement TranslateCreateIndex(SQLDevicePlan plan, TableVar tableVar, Key key) { CreateIndexStatement index = new CreateIndexStatement(); index.IsUnique = !key.IsSparse; index.IsClustered = key.Equals(Compiler.FindClusteringKey(plan.Plan, tableVar)); index.TableSchema = D4.MetaData.GetTag(tableVar.MetaData, "Storage.Schema", Schema); index.TableName = ToSQLIdentifier(tableVar); index.IndexSchema = D4.MetaData.GetTag(key.MetaData, "Storage.Schema", String.Empty); index.IndexName = GetIndexName(index.TableName, key); OrderColumnDefinition columnDefinition; foreach (TableVarColumn column in key.Columns) { columnDefinition = new OrderColumnDefinition(); columnDefinition.ColumnName = ToSQLIdentifier(column); columnDefinition.Ascending = true; index.Columns.Add(columnDefinition); } return index; } protected virtual Statement TranslateDropIndex(SQLDevicePlan plan, TableVar tableVar, Key key) { DropIndexStatement statement = new DropIndexStatement(); statement.IndexSchema = D4.MetaData.GetTag(key.MetaData, "Storage.Schema", String.Empty); statement.IndexName = GetIndexName(ToSQLIdentifier(tableVar), key); return statement; } protected virtual Statement TranslateCreateIndex(SQLDevicePlan plan, TableVar tableVar, Order order) { CreateIndexStatement index = new CreateIndexStatement(); index.IsClustered = Convert.ToBoolean(D4.MetaData.GetTag(order.MetaData, "DAE.IsClustered", "false")); index.TableSchema = D4.MetaData.GetTag(tableVar.MetaData, "Storage.Schema", Schema); index.TableName = ToSQLIdentifier(tableVar); index.IndexSchema = D4.MetaData.GetTag(order.MetaData, "Storage.Schema", String.Empty); index.IndexName = GetIndexName(index.TableName, order); OrderColumnDefinition columnDefinition; foreach (OrderColumn column in order.Columns) { columnDefinition = new OrderColumnDefinition(); columnDefinition.ColumnName = ToSQLIdentifier(column.Column); columnDefinition.Ascending = column.Ascending; index.Columns.Add(columnDefinition); } return index; } protected virtual Statement TranslateDropIndex(SQLDevicePlan plan, TableVar tableVar, Order order) { DropIndexStatement statement = new DropIndexStatement(); statement.IndexSchema = D4.MetaData.GetTag(order.MetaData, "Storage.Schema", String.Empty); statement.IndexName = GetIndexName(ToSQLIdentifier(tableVar), order); return statement; } protected virtual Statement TranslateCreateTable(SQLDevicePlan plan, TableVar tableVar) { Batch batch = new Batch(); CreateTableStatement statement = new CreateTableStatement(); statement.TableSchema = D4.MetaData.GetTag(tableVar.MetaData, "Storage.Schema", Schema); statement.TableName = ToSQLIdentifier(tableVar); foreach (TableVarColumn column in tableVar.Columns) { if (Convert.ToBoolean(D4.MetaData.GetTag(column.MetaData, "Storage.ShouldReconcile", "true"))) { SQLScalarType sQLScalarType = (SQLScalarType)ResolveDeviceScalarType(plan.Plan, (Schema.ScalarType)column.DataType); if (sQLScalarType == null) throw new SchemaException(SchemaException.Codes.DeviceScalarTypeNotFound, column.DataType.ToString()); statement.Columns.Add ( new ColumnDefinition ( ToSQLIdentifier(column), sQLScalarType.DomainName(column), column.IsNilable ) ); } } batch.Statements.Add(statement); foreach (Key key in tableVar.Keys) if (Convert.ToBoolean(D4.MetaData.GetTag(key.MetaData, "Storage.ShouldReconcile", (key.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateCreateIndex(plan, tableVar, key)); foreach (Order order in tableVar.Orders) if (Convert.ToBoolean(D4.MetaData.GetTag(order.MetaData, "Storage.ShouldReconcile", (order.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateCreateIndex(plan, tableVar, order)); return batch; } protected virtual Statement TranslateCreateTableNode(SQLDevicePlan devicePlan, CreateTableNode node) { return TranslateCreateTable(devicePlan, node.Table); } protected bool AltersStorageTags(D4.AlterMetaData alterMetaData) { if (alterMetaData == null) return false; for (int index = 0; index < alterMetaData.DropTags.Count; index++) if (alterMetaData.DropTags[index].Name.IndexOf("Storage") == 0) return true; for (int index = 0; index < alterMetaData.AlterTags.Count; index++) if (alterMetaData.AlterTags[index].Name.IndexOf("Storage") == 0) return true; for (int index = 0; index < alterMetaData.CreateTags.Count; index++) if (alterMetaData.CreateTags[index].Name.IndexOf("Storage") == 0) return true; return false; } protected virtual Statement TranslateAlterTableNode(SQLDevicePlan devicePlan, AlterTableNode node) { Batch batch = new Batch(); string tableSchema = D4.MetaData.GetTag(node.TableVar.MetaData, "Storage.Schema", Schema); string tableName = ToSQLIdentifier(node.TableVar); if (node.AlterTableStatement.DropColumns.Count > 0) { foreach (D4.DropColumnDefinition column in node.AlterTableStatement.DropColumns) { TableVarColumn tableVarColumn = null; SchemaLevelDropColumnDefinition schemaLevelDropColumnDefinition = column as SchemaLevelDropColumnDefinition; if (schemaLevelDropColumnDefinition != null) tableVarColumn = schemaLevelDropColumnDefinition.Column; else tableVarColumn = node.TableVar.Columns[node.TableVar.Columns.IndexOfName(column.ColumnName)]; if (Convert.ToBoolean(D4.MetaData.GetTag(tableVarColumn.MetaData, "Storage.ShouldReconcile", "true"))) { AlterTableStatement statement = new AlterTableStatement(); statement.TableSchema = tableSchema; statement.TableName = tableName; statement.DropColumns.Add(new DropColumnDefinition(ToSQLIdentifier(tableVarColumn))); batch.Statements.Add(statement); } } } if (node.AlterTableStatement.AlterColumns.Count > 0) { foreach (D4.AlterColumnDefinition alterColumnDefinition in node.AlterTableStatement.AlterColumns) { TableVarColumn column = node.TableVar.Columns[alterColumnDefinition.ColumnName]; if (Convert.ToBoolean(D4.MetaData.GetTag(column.MetaData, "Storage.ShouldReconcile", "true"))) { // The assumption being made here is that the type of the column in the table var has already been changed to the new type, the presence of the type specifier is just to indicate that the alter should be performed // This assumption will likely need to be revisited when (if) we actually start supporting changing the type of a column if (alterColumnDefinition.ChangeNilable || (alterColumnDefinition.TypeSpecifier != null) || AltersStorageTags(alterColumnDefinition.AlterMetaData)) { AlterTableStatement statement = new AlterTableStatement(); statement.TableSchema = tableSchema; statement.TableName = tableName; statement.AlterColumns.Add(new AlterColumnDefinition(ToSQLIdentifier(column), ((SQLScalarType)ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)column.DataType)).DomainName(column), column.IsNilable)); batch.Statements.Add(statement); } } } } if (node.AlterTableStatement.CreateColumns.Count > 0) { foreach (D4.ColumnDefinition columnDefinition in node.AlterTableStatement.CreateColumns) { TableVarColumn column = node.TableVar.Columns[columnDefinition.ColumnName]; if (Convert.ToBoolean(D4.MetaData.GetTag(column.MetaData, "Storage.ShouldReconcile", "true"))) { AlterTableStatement statement = new AlterTableStatement(); statement.TableSchema = tableSchema; statement.TableName = tableName; statement.AddColumns.Add(new ColumnDefinition(ToSQLIdentifier(column), ((SQLScalarType)ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)column.DataType)).DomainName(column), true)); batch.Statements.Add(statement); } } } foreach (D4.DropKeyDefinition keyDefinition in node.AlterTableStatement.DropKeys) { Schema.Key key = null; SchemaLevelDropKeyDefinition schemaLevelDropKeyDefinition = keyDefinition as SchemaLevelDropKeyDefinition; if (schemaLevelDropKeyDefinition != null) key = schemaLevelDropKeyDefinition.Key; else key = Compiler.FindKey(devicePlan.Plan, node.TableVar, keyDefinition); if (Convert.ToBoolean(D4.MetaData.GetTag(key.MetaData, "Storage.ShouldReconcile", (key.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateDropIndex(devicePlan, node.TableVar, key)); } foreach (D4.DropOrderDefinition orderDefinition in node.AlterTableStatement.DropOrders) { Schema.Order order = null; SchemaLevelDropOrderDefinition schemaLevelDropOrderDefinition = orderDefinition as SchemaLevelDropOrderDefinition; if (schemaLevelDropOrderDefinition != null) order = schemaLevelDropOrderDefinition.Order; else order = Compiler.FindOrder(devicePlan.Plan, node.TableVar, orderDefinition); if (Convert.ToBoolean(D4.MetaData.GetTag(order.MetaData, "Storage.ShouldReconcile", (order.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateDropIndex(devicePlan, node.TableVar, order)); } foreach (D4.KeyDefinition keyDefinition in node.AlterTableStatement.CreateKeys) { Schema.Key key = Compiler.CompileKeyDefinition(devicePlan.Plan, node.TableVar, keyDefinition); if (Convert.ToBoolean(D4.MetaData.GetTag(key.MetaData, "Storage.ShouldReconcile", (key.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateCreateIndex(devicePlan, node.TableVar, key)); } foreach (D4.OrderDefinition orderDefinition in node.AlterTableVarStatement.CreateOrders) { Schema.Order order = Compiler.CompileOrderDefinition(devicePlan.Plan, node.TableVar, orderDefinition, false); if (Convert.ToBoolean(D4.MetaData.GetTag(order.MetaData, "Storage.ShouldReconcile", (order.Columns.Count > 0).ToString()))) batch.Statements.Add(TranslateCreateIndex(devicePlan, node.TableVar, order)); } return batch; } protected virtual Statement TranslateDropTableNode(DevicePlan devicePlan, DropTableNode node) { DropTableStatement statement = new DropTableStatement(); statement.TableSchema = D4.MetaData.GetTag(node.Table.MetaData, "Storage.Schema", Schema); statement.TableName = ToSQLIdentifier(node.Table); return statement; } /// <summary> /// Translates an order by clause based on the Order of the given node /// </summary> /// <param name="devicePlan">The device plan being translated</param> /// <param name="node">The node providing the definition of the order</param> /// <param name="statement">The current translated select statement</param> /// <param name="inContextOrderBy">Indicates that this is an order by in an expression context and is therefore allowed to reference range variables, regardless of the device OrderByInContext setting.</param> /// <returns>A select statement with an appropriate order by clause</returns> public virtual SelectStatement TranslateOrder(DevicePlan devicePlan, TableNode node, SelectStatement statement, bool inContextOrderBy) { SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan; if ((node.Order != null) && (node.Order.Columns.Count > 0)) { statement.OrderClause = new OrderClause(); SQLRangeVarColumn rangeVarColumn; foreach (OrderColumn column in node.Order.Columns) { if (!column.IsDefaultSort) { localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(@"Plan is not supported because the order uses expression-based sorting.", node)); localDevicePlan.IsSupported = false; break; } if (!localDevicePlan.Device.SupportsComparison(devicePlan.Plan, column.Column.DataType)) { localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not support comparison of values of type ""{0}"" for column ""{1}"".", column.Column.DataType.Name, column.Column.Name), node)); localDevicePlan.IsSupported = false; break; } OrderFieldExpression fieldExpression = new OrderFieldExpression(); rangeVarColumn = localDevicePlan.GetRangeVarColumn(column.Column.Name, true); if (IsOrderByInContext || inContextOrderBy) { if (rangeVarColumn.Expression != null) { QualifiedFieldExpression qualifiedFieldExpression = rangeVarColumn.Expression as QualifiedFieldExpression; if (qualifiedFieldExpression == null) { throw new NotImplementedException("Expressions within an order by are not implemented."); } fieldExpression.FieldName = qualifiedFieldExpression.FieldName; fieldExpression.TableAlias = qualifiedFieldExpression.TableAlias; } else { fieldExpression.FieldName = rangeVarColumn.ColumnName; fieldExpression.TableAlias = rangeVarColumn.TableAlias; } } else fieldExpression.FieldName = rangeVarColumn.Alias == String.Empty ? rangeVarColumn.ColumnName : rangeVarColumn.Alias; fieldExpression.Ascending = column.Ascending; // NOTE: Only include the NULLS FIRST/LAST clause if it is required by the underlying system; it has significant performance implications if (column.Column.IsNilable) { // TODO: Respect the IncludeNils option in the order column // TODO: Use the system-level NullSortBehavior to determine whether data coming from this device will be sorted differently // TODO: If different behavior is required and the underlying system doesn't support it (or we don't want to use the underlying system's built-in support for performance reasons) add a buffer for nulls to the device cursor if (SupportsOrderByNullsFirstLast) { fieldExpression.NullsFirst = column.Ascending; } } statement.OrderClause.Columns.Add(fieldExpression); } } return statement; } private bool SupportsOperator(Plan plan, Schema.Operator operatorValue) { // returns true if there exists a ScalarTypeOperator corresponding to the Operator for this InstructionNode return ResolveDeviceOperator(plan, operatorValue) != null; } private bool SupportsOperands(InstructionNodeBase node) { if ((node.DataType is Schema.ITableType) || (node.DataType is Schema.IScalarType) || (node.DataType is Schema.IRowType)) return true; return false; } public bool SupportsEqual(Plan plan, Schema.IDataType dataType) { if (SupportsComparison(plan, dataType)) return true; Schema.Signature signature = new Schema.Signature(new SignatureElement[]{new SignatureElement(dataType), new SignatureElement(dataType)}); OperatorBindingContext context = new OperatorBindingContext(null, "iEqual", plan.NameResolutionPath, signature, true); Compiler.ResolveOperator(plan, context); if (context.Operator != null) { Schema.DeviceOperator deviceOperator = ResolveDeviceOperator(plan, context.Operator); if (deviceOperator != null) { plan.AttachDependency(deviceOperator); return true; } } return false; } public bool SupportsComparison(Plan plan, Schema.IDataType dataType) { Schema.Signature signature = new Schema.Signature(new SignatureElement[]{new SignatureElement(dataType), new SignatureElement(dataType)}); OperatorBindingContext context = new OperatorBindingContext(null, "iCompare", plan.NameResolutionPath, signature, true); Compiler.ResolveOperator(plan, context); if (context.Operator != null) { Schema.DeviceOperator deviceOperator = ResolveDeviceOperator(plan, context.Operator); if (deviceOperator != null) { plan.AttachDependency(deviceOperator); return true; } } return false; } protected bool IsTruthValued(DeviceOperator deviceOperator) { SQLDeviceOperator localDeviceOperator = deviceOperator as SQLDeviceOperator; return (localDeviceOperator != null) && localDeviceOperator.IsTruthValued; } // Translate public override Statement Translate(DevicePlan devicePlan, PlanNode planNode) { bool scalarContext = false; SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan; if (((planNode is TableNode) || (planNode.DataType is Schema.IRowType)) && (localDevicePlan.CurrentQueryContext().IsScalarContext)) { bool supportsSubSelect = localDevicePlan.IsSubSelectSupported(); if (!supportsSubSelect) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(localDevicePlan.GetSubSelectNotSupportedReason(), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsSubSelect; localDevicePlan.CurrentQueryContext().ReferenceFlags |= SQLReferenceFlags.HasSubSelectExpressions; localDevicePlan.PushQueryContext(); scalarContext = true; } try { InstructionNodeBase instructionNode = planNode as InstructionNodeBase; if ((instructionNode != null) && (instructionNode.DataType != null) && (instructionNode.Operator != null)) { bool supportsOperator = SupportsOperator(devicePlan.Plan, instructionNode.Operator) && SupportsOperands(instructionNode); if (!supportsOperator) { if ( (localDevicePlan.CurrentQueryContext().IsScalarContext) && (instructionNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)instructionNode.DataType) != null) && instructionNode.IsFunctional && instructionNode.IsRepeatable && instructionNode.IsContextLiteral(localDevicePlan.Stack.Count == 0 ? 0 : localDevicePlan.Stack.Count - 1) ) { ServerStatementPlan plan = new ServerStatementPlan(devicePlan.Plan.ServerProcess); try { plan.Plan.PushStatementContext(localDevicePlan.Plan.StatementContext); plan.Plan.PushSecurityContext(localDevicePlan.Plan.SecurityContext); plan.Plan.PushCursorContext(localDevicePlan.Plan.CursorContext); if (localDevicePlan.Plan.InRowContext) plan.Plan.EnterRowContext(); for (int index = localDevicePlan.Plan.Symbols.Count - 1; index >= 0; index--) plan.Plan.Symbols.Push(localDevicePlan.Plan.Symbols.Peek(index)); try { PlanNode node = Compiler.CompileExpression(plan.Plan, new D4.Parser(true).ParseExpression(instructionNode.EmitStatementAsString())); // Perform binding on the children, but not on the root // A binding on the root would result in another attempt to support this expression, but we already know it's not supported, and // the device associative code would kick in again, resulting in stack overflow foreach (var childNode in node.Nodes) Compiler.OptimizeNode(plan.Plan, childNode); planNode.CouldSupport = true; // Set this to indicate that support could be provided if it would be beneficial to do so return FromScalar(localDevicePlan, node); } finally { while (plan.Plan.Symbols.Count > 0) plan.Plan.Symbols.Pop(); } } finally { plan.Dispose(); } } else { localDevicePlan.IsSupported = false; localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not contain an operator map for operator ""{0}"" with signature ""{1}"".", instructionNode.Operator.OperatorName, instructionNode.Operator.Signature.ToString()), planNode)); } } else { TableNode tableNode = planNode as TableNode; if (tableNode != null) DetermineCursorBehavior(localDevicePlan.Plan, tableNode); DeviceOperator deviceOperator = ResolveDeviceOperator(devicePlan.Plan, instructionNode.Operator); if (localDevicePlan.IsBooleanContext() && planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean) && !IsTruthValued(deviceOperator)) return new BinaryExpression((Expression)deviceOperator.Translate(localDevicePlan, planNode), "iEqual", new ValueExpression(1)); else return deviceOperator.Translate(localDevicePlan, planNode); } return new CallExpression(); } else if ((planNode is AggregateCallNode) && (planNode.DataType != null) && ((AggregateCallNode)planNode).Operator != null) { AggregateCallNode aggregateCallNode = (AggregateCallNode)planNode; bool supportsOperator = SupportsOperator(devicePlan.Plan, aggregateCallNode.Operator); if (!supportsOperator) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have an operator map for the operator ""{0}"" with signature ""{1}"".", aggregateCallNode.Operator.OperatorName, aggregateCallNode.Operator.Signature.ToString()), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsOperator; if (localDevicePlan.IsSupported) { DeviceOperator deviceOperator = ResolveDeviceOperator(devicePlan.Plan, aggregateCallNode.Operator); if (localDevicePlan.IsBooleanContext() && planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean) && !IsTruthValued(deviceOperator)) return new BinaryExpression((Expression)deviceOperator.Translate(localDevicePlan, planNode), "iEqual", new ValueExpression(1)); else return deviceOperator.Translate(localDevicePlan, planNode); } return new CallExpression(); } else if (planNode is StackReferenceNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"" of variable reference ""{1}"".", planNode.DataType.Name, ((StackReferenceNode)planNode).Identifier), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) return TranslateStackReference((SQLDevicePlan)localDevicePlan, (StackReferenceNode)planNode); return new CallExpression(); } else if (planNode is StackColumnReferenceNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"" of column reference ""{1}"".", planNode.DataType.Name, ((StackColumnReferenceNode)planNode).Identifier), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) return TranslateStackColumnReference((SQLDevicePlan)localDevicePlan, (StackColumnReferenceNode)planNode); return new CallExpression(); } else if (planNode is ExtractColumnNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"" of column reference ""{1}"".", planNode.DataType.Name, ((ExtractColumnNode)planNode).Identifier), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) return TranslateExtractColumnNode((SQLDevicePlan)localDevicePlan, (ExtractColumnNode)planNode); return new CallExpression(); } else if (planNode is ExtractRowNode) { return TranslateExtractRowNode(localDevicePlan, (ExtractRowNode)planNode); } else if (planNode is ValueNode) { bool supportsDataType = ((planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null)) || (planNode.DataType is Schema.GenericType); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"".", planNode.DataType.Name), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) return TranslateValueNode(localDevicePlan, (ValueNode)planNode); return new CallExpression(); } else if (planNode is AsNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"".", planNode.DataType.Name), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) return TranslateAsNode(localDevicePlan, (AsNode)planNode); return new CallExpression(); } else if (planNode is ConditionNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"".", planNode.DataType.Name), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) if (localDevicePlan.IsBooleanContext() && planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean)) return new BinaryExpression((Expression)TranslateConditionNode(localDevicePlan, (ConditionNode)planNode), "iEqual", new ValueExpression(1)); else return TranslateConditionNode(localDevicePlan, (ConditionNode)planNode); return new CallExpression(); } else if (planNode is ConditionedCaseNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"".", planNode.DataType.Name), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) if (localDevicePlan.IsBooleanContext() && planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean)) return new BinaryExpression((Expression)TranslateConditionedCaseNode(localDevicePlan, (ConditionedCaseNode)planNode), "iEqual", new ValueExpression(1)); else return TranslateConditionedCaseNode(localDevicePlan, (ConditionedCaseNode)planNode); return new CallExpression(); } else if (planNode is SelectedConditionedCaseNode) { bool supportsDataType = (planNode.DataType is Schema.ScalarType) && (ResolveDeviceScalarType(devicePlan.Plan, (Schema.ScalarType)planNode.DataType) != null); if (!supportsDataType) localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not have a type map for the type ""{0}"".", planNode.DataType.Name), planNode)); localDevicePlan.IsSupported = localDevicePlan.IsSupported && supportsDataType; if (localDevicePlan.IsSupported) if (localDevicePlan.IsBooleanContext() && planNode.DataType.Is(devicePlan.Plan.Catalog.DataTypes.SystemBoolean)) return new BinaryExpression((Expression)TranslateSelectedConditionedCaseNode(localDevicePlan, (SelectedConditionedCaseNode)planNode), "iEqual", new ValueExpression(1)); else return TranslateSelectedConditionedCaseNode(localDevicePlan, (SelectedConditionedCaseNode)planNode); return new CallExpression(); } else if (planNode is ConditionedCaseItemNode) { // Let the support walk up to the parent CaseNode for translation return new CallExpression(); } else if (planNode is ListNode) { return TranslateListNode(localDevicePlan, (ListNode)planNode); } else if (planNode is TableSelectorNode) { DetermineCursorBehavior(localDevicePlan.Plan, (TableNode)planNode); return TranslateTableSelectorNode(localDevicePlan, (TableSelectorNode)planNode); } else if (planNode is RowSelectorNode) return TranslateRowSelectorNode(localDevicePlan, (RowSelectorNode)planNode); #if TranslateModifications else if (APlanNode is InsertNode) return TranslateInsertNode(localDevicePlan, (InsertNode)APlanNode); else if (APlanNode is UpdateNode) return TranslateUpdateNode(localDevicePlan, (UpdateNode)APlanNode); else if (APlanNode is DeleteNode) return TranslateDeleteNode(localDevicePlan, (DeleteNode)APlanNode); #endif else if (planNode is CreateTableNode) return TranslateCreateTableNode(localDevicePlan, (CreateTableNode)planNode); else if (planNode is AlterTableNode) return TranslateAlterTableNode(localDevicePlan, (AlterTableNode)planNode); else if (planNode is DropTableNode) return TranslateDropTableNode(localDevicePlan, (DropTableNode)planNode); else { localDevicePlan.TranslationMessages.Add(new Schema.TranslationMessage(String.Format(@"Plan is not supported because the device does not support translation for nodes of type ""{0}"".", planNode.GetType().Name))); localDevicePlan.IsSupported = false; return new CallExpression(); } } finally { if (scalarContext) localDevicePlan.PopQueryContext(); } } public Batch DeviceReconciliationScript(ServerProcess process, ReconcileOptions options) { Catalog serverCatalog = GetServerCatalog(process, null); return DeviceReconciliationScript(process, serverCatalog, GetDeviceCatalog(process, serverCatalog), options); } public Batch DeviceReconciliationScript(ServerProcess process, TableVar tableVar, ReconcileOptions options) { Catalog serverCatalog = GetServerCatalog(process, tableVar); return DeviceReconciliationScript(process, serverCatalog, GetDeviceCatalog(process, serverCatalog, tableVar), options); } /// <summary>Produces a script to reconcile the given device catalog to the given server catalog, with the specified options.</summary> public Batch DeviceReconciliationScript(ServerProcess process, Catalog serverCatalog, Catalog deviceCatalog, ReconcileOptions options) { Batch batch = new Batch(); foreach (Schema.Object objectValue in serverCatalog) { Schema.BaseTableVar baseTableVar = objectValue as Schema.BaseTableVar; if (baseTableVar != null) { if (Convert.ToBoolean(D4.MetaData.GetTag(baseTableVar.MetaData, "Storage.ShouldReconcile", "true"))) { AlterTableNode alterTableNode = new AlterTableNode(); using (Plan plan = new Plan(process)) { using (SQLDevicePlan devicePlan = new SQLDevicePlan(plan, this, alterTableNode)) { int objectIndex = deviceCatalog.IndexOf(baseTableVar.Name); if (objectIndex < 0) batch.Statements.Add(TranslateCreateTable(devicePlan, baseTableVar)); else { // Compile and translate the D4.AlterTableStatement returned from ReconcileTable and add it to LBatch bool reconciliationRequired; D4.AlterTableStatement d4AlterTableStatement = ReconcileTable(plan, baseTableVar, (Schema.TableVar)deviceCatalog[objectIndex], options, out reconciliationRequired); if (reconciliationRequired) { alterTableNode.AlterTableStatement = d4AlterTableStatement; alterTableNode.DeterminePotentialDevice(devicePlan.Plan); alterTableNode.DetermineDevice(devicePlan.Plan); alterTableNode.DetermineAccessPath(devicePlan.Plan); batch.Statements.Add(TranslateAlterTableNode(devicePlan, alterTableNode)); } } } } } } } if ((options & ReconcileOptions.ShouldDropTables) != 0) { foreach (Schema.Object objectValue in deviceCatalog) { Schema.BaseTableVar baseTableVar = objectValue as Schema.BaseTableVar; if ((baseTableVar != null) && !serverCatalog.Contains(baseTableVar.Name)) { DropTableNode dropTableNode = new DropTableNode(baseTableVar); using (Plan plan = new Plan(process)) { using (SQLDevicePlan devicePlan = new SQLDevicePlan(plan, this, dropTableNode)) { batch.Statements.Add(TranslateDropTableNode(devicePlan, new DropTableNode(baseTableVar))); } } } } } return batch; } protected override void CreateServerTableInDevice(ServerProcess process, TableVar tableVar) { using (Plan plan = new Plan(process)) { using (SQLDevicePlan devicePlan = new SQLDevicePlan(plan, this, null)) { Statement statement = TranslateCreateTable(devicePlan, tableVar); SQLDeviceSession deviceSession = (SQLDeviceSession)plan.DeviceConnect(this); { Batch batch = statement as Batch; if (batch != null) { foreach (Statement singleStatement in batch.Statements) deviceSession.Connection.Execute(Emitter.Emit(singleStatement)); } else deviceSession.Connection.Execute(Emitter.Emit(statement)); } } } } public class SchemaLevelDropColumnDefinition : D4.DropColumnDefinition { public SchemaLevelDropColumnDefinition(Schema.TableVarColumn column) : base() { _column = column; } private Schema.TableVarColumn _column; public Schema.TableVarColumn Column { get { return _column; } } } public class SchemaLevelDropKeyDefinition : D4.DropKeyDefinition { public SchemaLevelDropKeyDefinition(Schema.Key key) : base() { _key = key; } private Schema.Key _key; public Schema.Key Key { get { return _key; } } } public class SchemaLevelDropOrderDefinition : D4.DropOrderDefinition { public SchemaLevelDropOrderDefinition(Schema.Order order) : base() { _order = order; } private Schema.Order _order; public Schema.Order Order { get { return _order; } } } protected override D4.AlterTableStatement ReconcileTable(Plan plan, TableVar sourceTableVar, TableVar targetTableVar, ReconcileOptions options, out bool reconciliationRequired) { reconciliationRequired = false; D4.AlterTableStatement statement = new D4.AlterTableStatement(); statement.TableVarName = targetTableVar.Name; // Ensure ASourceTableVar.Columns is a subset of ATargetTableVar.Columns foreach (Schema.TableVarColumn column in sourceTableVar.Columns) if (Convert.ToBoolean(D4.MetaData.GetTag(column.MetaData, "Storage.ShouldReconcile", "true"))) { int targetIndex = ColumnIndexFromNativeColumnName(targetTableVar, ToSQLIdentifier(column)); if (targetIndex < 0) { // Add the column to the target table var statement.CreateColumns.Add(column.EmitStatement(D4.EmitMode.ForCopy)); reconciliationRequired = true; } else { if ((options & ReconcileOptions.ShouldReconcileColumns) != 0) { Schema.TableVarColumn targetColumn = targetTableVar.Columns[targetIndex]; // Type of the column (Needs to be based on domain name because the reconciliation process will only create the column with the D4 type map for the native domain) SQLScalarType sourceType = (SQLScalarType)ResolveDeviceScalarType(plan, (Schema.ScalarType)column.DataType); SQLScalarType targetType = (SQLScalarType)ResolveDeviceScalarType(plan, (Schema.ScalarType)targetColumn.DataType); bool domainsDifferent = (sourceType.DomainName(column) != targetType.DomainName(targetColumn)) || (sourceType.NativeDomainName(column) != targetType.NativeDomainName(targetColumn)); // Nilability of the column bool nilabilityDifferent = column.IsNilable != targetColumn.IsNilable; if (domainsDifferent || nilabilityDifferent) { D4.AlterColumnDefinition alterColumnDefinition = new D4.AlterColumnDefinition(); alterColumnDefinition.ColumnName = targetColumn.Name; alterColumnDefinition.ChangeNilable = nilabilityDifferent; alterColumnDefinition.IsNilable = column.IsNilable; if (domainsDifferent) alterColumnDefinition.TypeSpecifier = column.DataType.EmitSpecifier(D4.EmitMode.ForCopy); statement.AlterColumns.Add(alterColumnDefinition); reconciliationRequired = true; } } } } // Ensure ATargetTableVar.Columns is a subset of ASourceTableVar.Columns if ((options & ReconcileOptions.ShouldDropColumns) != 0) foreach (Schema.TableVarColumn column in targetTableVar.Columns) if (!sourceTableVar.Columns.ContainsName(column.Name)) { statement.DropColumns.Add(new SchemaLevelDropColumnDefinition(column)); reconciliationRequired = true; } // Ensure All keys and orders have supporting indexes // TODO: Replace an imposed key if a new key is added foreach (Schema.Key key in sourceTableVar.Keys) if (Convert.ToBoolean(D4.MetaData.GetTag(key.MetaData, "Storage.ShouldReconcile", "true"))) if (!targetTableVar.Keys.Contains(key) && (!key.IsSparse || !targetTableVar.Orders.Contains(CreateOrderFromSparseKey(plan, key)))) { // Add the key to the target table var statement.CreateKeys.Add(key.EmitStatement(D4.EmitMode.ForCopy)); reconciliationRequired = true; } else { // TODO: Key level reconciliation } // Ensure ATargetTableVar.Keys is a subset of ASourceTableVar.Keys if ((options & ReconcileOptions.ShouldDropKeys) != 0) foreach (Schema.Key key in targetTableVar.Keys) if (!sourceTableVar.Keys.Contains(key) && !Convert.ToBoolean(D4.MetaData.GetTag(key.MetaData, "Storage.IsImposedKey", "false"))) { statement.DropKeys.Add(new SchemaLevelDropKeyDefinition(key)); reconciliationRequired = true; } foreach (Schema.Order order in sourceTableVar.Orders) if (Convert.ToBoolean(D4.MetaData.GetTag(order.MetaData, "Storage.ShouldReconcile", "true"))) if (!(targetTableVar.Orders.Contains(order))) { // Add the order to the target table var statement.CreateOrders.Add(order.EmitStatement(D4.EmitMode.ForCopy)); reconciliationRequired = true; } else { // TODO: Order level reconciliation } // Ensure ATargetTableVar.Orders is a subset of ASourceTableVar.Orders if ((options & ReconcileOptions.ShouldDropOrders) != 0) foreach (Schema.Order order in targetTableVar.Orders) if (!sourceTableVar.Orders.Contains(order) && !sourceTableVar.Keys.Contains(CreateSparseKeyFromOrder(order))) { statement.DropOrders.Add(new SchemaLevelDropOrderDefinition(order)); reconciliationRequired = true; } return statement; } private Schema.Order CreateOrderFromSparseKey(Plan plan, Schema.Key key ) { return Compiler.OrderFromKey(plan, key); } private Schema.Key CreateSparseKeyFromOrder(Schema.Order order) { TableVarColumn[] orderColumns = new TableVarColumn[order.Columns.Count]; for (int i = 0; i < order.Columns.Count; i++) orderColumns[i] = order.Columns[i].Column; Schema.Key key = new Schema.Key(orderColumns); key.IsSparse = true; return key; } public virtual bool ShouldIncludeColumn(Plan plan, string tableName, string columnName, string domainName) { return true; } public virtual ScalarType FindScalarType(Plan plan, string domainName, int length, D4.MetaData metaData) { throw new SQLException(SQLException.Codes.UnsupportedImportType, domainName); } public virtual ScalarType FindScalarType(Plan plan, SQLDomain domain) { if (domain.Type.Equals(typeof(bool))) return plan.DataTypes.SystemBoolean; else if (domain.Type.Equals(typeof(byte))) return plan.DataTypes.SystemByte; else if (domain.Type.Equals(typeof(short))) return plan.DataTypes.SystemShort; else if (domain.Type.Equals(typeof(int))) return plan.DataTypes.SystemInteger; else if (domain.Type.Equals(typeof(long))) return plan.DataTypes.SystemLong; else if (domain.Type.Equals(typeof(decimal))) return plan.DataTypes.SystemDecimal; else if (domain.Type.Equals(typeof(float))) return plan.DataTypes.SystemDecimal; else if (domain.Type.Equals(typeof(double))) return plan.DataTypes.SystemDecimal; else if (domain.Type.Equals(typeof(string))) return plan.DataTypes.SystemString; else if (domain.Type.Equals(typeof(byte[]))) return plan.DataTypes.SystemBinary; else if (domain.Type.Equals(typeof(Guid))) return plan.DataTypes.SystemGuid; else if (domain.Type.Equals(typeof(DateTime))) return plan.DataTypes.SystemDateTime; else if (domain.Type.Equals(typeof(TimeSpan))) return plan.DataTypes.SystemTimeSpan; else throw new SQLException(SQLException.Codes.UnsupportedImportType, domain.Type.Name); } private void ConfigureTableVar(Plan plan, TableVar tableVar, Objects columns, Catalog catalog) { if (tableVar != null) { tableVar.DataType = new TableType(); foreach (TableVarColumn column in columns) { tableVar.Columns.Add(column); tableVar.DataType.Columns.Add(column.Column); } catalog.Add(tableVar); } } private void AttachKeyOrOrder(Plan plan, TableVar tableVar, ref Key key, ref Order order) { if (key != null) { if (!tableVar.Keys.Contains(key) && (key.Columns.Count > 0)) tableVar.Keys.Add(key); key = null; } else if (order != null) { if (!tableVar.Orders.Contains(order) && (order.Columns.Count > 0)) tableVar.Orders.Add(order); order = null; } } private string _deviceTablesExpression = String.Empty; public string DeviceTablesExpression { get { return _deviceTablesExpression; } set { _deviceTablesExpression = value == null ? String.Empty : value; } } protected virtual string GetDeviceTablesExpression(TableVar tableVar) { return String.Format ( DeviceTablesExpression, tableVar == null ? String.Empty : ToSQLIdentifier(tableVar) ); } protected virtual string GetTitleFromName(string objectName) { StringBuilder columnTitle = new StringBuilder(); bool firstChar = true; for (int index = 0; index < objectName.Length; index++) if (Char.IsLetterOrDigit(objectName, index)) if (firstChar) { firstChar = false; columnTitle.Append(Char.ToUpper(objectName[index])); } else columnTitle.Append(Char.ToLower(objectName[index])); else if (!firstChar) { columnTitle.Append(" "); firstChar = true; } return columnTitle.ToString(); } protected string GetServerTableName(Plan plan, Catalog serverCatalog, string deviceTableName) { string serverTableName = FromSQLIdentifier(deviceTableName); List<string> names = new List<string>(); int index = serverCatalog.IndexOf(serverTableName, names); if ((index >= 0) && (serverCatalog[index].Library != null) && (D4.MetaData.GetTag(serverCatalog[index].MetaData, "Storage.Name", deviceTableName) == deviceTableName)) serverTableName = serverCatalog[index].Name; else { // if LNames is populated, all but one of them must have a Storage.Name tag specifying a different name for the table bool found = false; foreach (string name in names) { TableVar tableVar = (TableVar)serverCatalog[serverCatalog.IndexOfName(name)]; if (tableVar.Library != null) if (D4.MetaData.GetTag(tableVar.MetaData, "Storage.Name", deviceTableName) == deviceTableName) { serverTableName = tableVar.Name; found = true; } } // search for a table with ADeviceTableName as it's Storage.Name tag if (!found) foreach (TableVar tableVar in serverCatalog) if (tableVar.Library != null) if (D4.MetaData.GetTag(tableVar.MetaData, "Storage.Name", "") == deviceTableName) { serverTableName = tableVar.Name; found = true; break; } if (!found) serverTableName = DAE.Schema.Object.Qualify(serverTableName, plan.CurrentLibrary.Name); } return serverTableName; } public int ColumnIndexFromNativeColumnName(TableVar existingTableVar, string nativeColumnName) { if (existingTableVar != null) for (int index = 0; index < existingTableVar.Columns.Count; index++) if (D4.MetaData.GetTag(existingTableVar.Columns[index].MetaData, "Storage.Name", "") == nativeColumnName) return index; return -1; } public unsafe virtual void GetDeviceTables(Plan plan, Catalog serverCatalog, Catalog deviceCatalog, TableVar tableVar) { string deviceTablesExpression = GetDeviceTablesExpression(tableVar); if (deviceTablesExpression != String.Empty) { SQLCursor cursor = ((SQLDeviceSession)plan.DeviceConnect(this)).Connection.Open(deviceTablesExpression); try { string tableName = String.Empty; BaseTableVar localTableVar = null; BaseTableVar existingTableVar = null; Objects columns = new Objects(); while (cursor.Next()) { if (tableName != (string)cursor[1]) { ConfigureTableVar(plan, localTableVar, columns, deviceCatalog); tableName = (string)cursor[1]; // Search for a table with this name unqualified in the server catalog string tableTitle = (string)cursor[4]; localTableVar = new BaseTableVar(GetServerTableName(plan, serverCatalog, tableName), null); localTableVar.Owner = plan.User; localTableVar.Library = plan.CurrentLibrary; localTableVar.Device = this; localTableVar.MetaData = new D4.MetaData(); localTableVar.MetaData.Tags.Add(new D4.Tag("Storage.Name", tableName, true)); localTableVar.MetaData.Tags.Add(new D4.Tag("Storage.Schema", (string)cursor[0], true)); // if this table is already present in the server catalog, use StorageNames to map the columns int existingTableIndex = serverCatalog.IndexOfName(localTableVar.Name); if (existingTableIndex >= 0) existingTableVar = serverCatalog[existingTableIndex] as BaseTableVar; else existingTableVar = null; if (tableTitle == tableName) tableTitle = GetTitleFromName(tableName); localTableVar.MetaData.Tags.Add(new D4.Tag("Frontend.Title", tableTitle)); localTableVar.AddDependency(this); columns = new Objects(); } string nativeColumnName = (string)cursor[2]; string columnName = FromSQLIdentifier(nativeColumnName); string columnTitle = (string)cursor[5]; string nativeDomainName = (string)cursor[6]; string domainName = (string)cursor[7]; int length = Convert.ToInt32(cursor[8]); int existingColumnIndex = ColumnIndexFromNativeColumnName(existingTableVar, nativeColumnName); if (existingColumnIndex >= 0) columnName = existingTableVar.Columns[existingColumnIndex].Name; if (ShouldIncludeColumn(plan, tableName, columnName, nativeDomainName)) { D4.MetaData metaData = new D4.MetaData(); TableVarColumn column = new TableVarColumn ( new Column(columnName, FindScalarType(plan, nativeDomainName, length, metaData)), metaData, TableVarColumnType.Stored ); if (column.MetaData == null) column.MetaData = new D4.MetaData(); column.MetaData.Tags.Add(new D4.Tag("Storage.Name", nativeColumnName)); if (nativeDomainName != domainName) column.MetaData.Tags.Add(new D4.Tag("Storage.DomainName", domainName)); if (column.MetaData.Tags.Contains("Storage.Length")) { column.MetaData.Tags.Add(new D4.Tag("Frontend.Width", Math.Min(Math.Max(3, length), 40).ToString())); if (length >= 0) // A (n)varchar(max) column in Microsoft SQL Server will reconcile with length -1 column.Constraints.Add(Compiler.CompileTableVarColumnConstraint(plan, localTableVar, column, new D4.ConstraintDefinition("LengthValid", new BinaryExpression(new CallExpression("Length", new Expression[]{new IdentifierExpression(D4.Keywords.Value)}), D4.Instructions.InclusiveLess, new ValueExpression(length)), null))); } if (columnTitle == nativeColumnName) columnTitle = GetTitleFromName(nativeColumnName); column.MetaData.Tags.AddOrUpdate("Frontend.Title", columnTitle); if (Convert.ToInt32(cursor[9]) != 0) column.IsNilable = true; if (Convert.ToInt32(cursor[10]) != 0) column.MetaData.Tags.AddOrUpdate("Storage.Deferred", "true"); columns.Add(column); localTableVar.Dependencies.Ensure((Schema.ScalarType)column.DataType); } } // while ConfigureTableVar(plan, localTableVar, columns, deviceCatalog); } catch (Exception E) { throw new SQLException(SQLException.Codes.ErrorReadingDeviceTables, E); } finally { cursor.Command.Connection.Close(cursor); } } } private string _deviceIndexesExpression = String.Empty; public string DeviceIndexesExpression { get { return _deviceIndexesExpression; } set { _deviceIndexesExpression = value == null ? String.Empty : value; } } protected virtual string GetDeviceIndexesExpression(TableVar tableVar) { return String.Format ( DeviceIndexesExpression, (tableVar == null) ? String.Empty : ToSQLIdentifier(tableVar) ); } public virtual void GetDeviceIndexes(Plan plan, Catalog serverCatalog, Catalog deviceCatalog, TableVar tableVar) { string deviceIndexesExpression = GetDeviceIndexesExpression(tableVar); if (deviceIndexesExpression != String.Empty) { SQLCursor cursor = ((SQLDeviceSession)plan.DeviceConnect(this)).Connection.Open(deviceIndexesExpression); try { string tableName = String.Empty; string indexName = String.Empty; BaseTableVar localTableVar = null; Key key = null; Order order = null; OrderColumn orderColumn; int columnIndex = -1; bool shouldIncludeIndex = true; while (cursor.Next()) { if (tableName != (string)cursor[1]) { if ((localTableVar != null) && shouldIncludeIndex) AttachKeyOrOrder(plan, localTableVar, ref key, ref order); else { key = null; order = null; } tableName = (string)cursor[1]; localTableVar = (BaseTableVar)deviceCatalog[GetServerTableName(plan, serverCatalog, tableName)]; indexName = (string)cursor[2]; D4.MetaData metaData = new D4.MetaData(); metaData.Tags.Add(new D4.Tag("Storage.Name", indexName, true)); if (Convert.ToInt32(cursor[5]) != 0) key = new Key(metaData); else order = new Order(metaData); shouldIncludeIndex = true; } if (indexName != (string)cursor[2]) { if (shouldIncludeIndex) AttachKeyOrOrder(plan, localTableVar, ref key, ref order); else { key = null; order = null; } indexName = (string)cursor[2]; D4.MetaData metaData = new D4.MetaData(); metaData.Tags.Add(new D4.Tag("Storage.Name", indexName, true)); if (Convert.ToInt32(cursor[5]) != 0) key = new Key(metaData); else order = new Order(metaData); shouldIncludeIndex = true; } if (key != null) { columnIndex = ColumnIndexFromNativeColumnName(localTableVar, (string)cursor[3]); if (columnIndex >= 0) key.Columns.Add(localTableVar.Columns[columnIndex]); else shouldIncludeIndex = false; } else { columnIndex = ColumnIndexFromNativeColumnName(localTableVar, (string)cursor[3]); if (columnIndex >= 0) { orderColumn = new OrderColumn(localTableVar.Columns[columnIndex], Convert.ToInt32(cursor[6]) == 0); orderColumn.Sort = Compiler.GetSort(plan, orderColumn.Column.DataType); orderColumn.IsDefaultSort = true; order.Columns.Add(orderColumn); } else shouldIncludeIndex = false; } } if (shouldIncludeIndex) AttachKeyOrOrder(plan, localTableVar, ref key, ref order); } catch (Exception E) { throw new SQLException(SQLException.Codes.ErrorReadingDeviceIndexes, E); } finally { cursor.Command.Connection.Close(cursor); } } } private string _deviceForeignKeysExpression = String.Empty; public string DeviceForeignKeysExpression { get { return _deviceForeignKeysExpression; } set { _deviceForeignKeysExpression = value == null ? String.Empty : value; } } protected virtual string GetDeviceForeignKeysExpression(TableVar tableVar) { return String.Format ( DeviceForeignKeysExpression, (tableVar == null) ? String.Empty : ToSQLIdentifier(tableVar) ); } public virtual void GetDeviceForeignKeys(Plan plan, Catalog serverCatalog, Catalog deviceCatalog, TableVar tableVar) { string deviceForeignKeysExpression = GetDeviceForeignKeysExpression(tableVar); if (deviceForeignKeysExpression != String.Empty) { SQLCursor cursor = ((SQLDeviceSession)plan.DeviceConnect(this)).Connection.Open(deviceForeignKeysExpression); try { string constraintName = String.Empty; TableVar sourceTableVar = null; TableVar targetTableVar = null; Reference reference = null; int columnIndex; bool shouldIncludeReference = true; while (cursor.Next()) { if (constraintName != (string)cursor[1]) { if ((reference != null) && shouldIncludeReference) { deviceCatalog.Add(reference); reference = null; } constraintName = (string)cursor[1]; string sourceTableName = GetServerTableName(plan, serverCatalog, (string)cursor[3]); string targetTableName = GetServerTableName(plan, serverCatalog, (string)cursor[6]); if (deviceCatalog.Contains(sourceTableName)) sourceTableVar = (TableVar)deviceCatalog[sourceTableName]; else sourceTableVar = null; if (deviceCatalog.Contains(targetTableName)) targetTableVar = (TableVar)deviceCatalog[targetTableName]; else targetTableVar = null; shouldIncludeReference = (sourceTableVar != null) && (targetTableVar != null); if (shouldIncludeReference) { D4.MetaData metaData = new D4.MetaData(); metaData.Tags.Add(new D4.Tag("Storage.Name", constraintName, true)); metaData.Tags.Add(new D4.Tag("Storage.Schema", (string)cursor[0], true)); metaData.Tags.Add(new D4.Tag("DAE.Enforced", "false", true)); reference = new Schema.Reference(DAE.Schema.Object.Qualify(FromSQLIdentifier(constraintName), DAE.Schema.Object.Qualifier(sourceTableVar.Name))); reference.MergeMetaData(metaData); reference.Owner = plan.User; reference.Library = plan.CurrentLibrary; reference.SourceTable = sourceTableVar; reference.TargetTable = targetTableVar; reference.Enforced = false; } } if (reference != null) { columnIndex = sourceTableVar.Columns.IndexOf(FromSQLIdentifier((string)cursor[4])); if (columnIndex >= 0) reference.SourceKey.Columns.Add(sourceTableVar.Columns[columnIndex]); else shouldIncludeReference = false; columnIndex = targetTableVar.Columns.IndexOf(FromSQLIdentifier((string)cursor[7])); if (columnIndex >= 0) reference.TargetKey.Columns.Add(targetTableVar.Columns[columnIndex]); else shouldIncludeReference = false; } } if ((reference != null) && shouldIncludeReference) deviceCatalog.Add(reference); } catch (Exception E) { throw new SQLException(SQLException.Codes.ErrorReadingDeviceForeignKeys, E); } finally { cursor.Command.Connection.Close(cursor); } } } public override Catalog GetDeviceCatalog(ServerProcess process, Catalog serverCatalog, TableVar tableVar) { Catalog catalog = base.GetDeviceCatalog(process, serverCatalog, tableVar); using (Plan plan = new Plan(process)) { GetDeviceTables(plan, serverCatalog, catalog, tableVar); GetDeviceIndexes(plan, serverCatalog, catalog, tableVar); GetDeviceForeignKeys(plan, serverCatalog, catalog, tableVar); // Impose a key on each table if one is not defined by the device foreach (Schema.Object objectValue in catalog) if ((objectValue is TableVar) && (((TableVar)objectValue).Keys.Count == 0)) { TableVar localTableVar = (TableVar)objectValue; Key key = new Key(); foreach (TableVarColumn column in localTableVar.Columns) if (!Convert.ToBoolean(D4.MetaData.GetTag(column.MetaData, "Storage.Deferred", "false"))) key.Columns.Add(column); key.IsGenerated = true; key.MetaData = new D4.MetaData(); key.MetaData.Tags.Add(new D4.Tag("Storage.IsImposedKey", "true")); localTableVar.Keys.Add(key); } } return catalog; } private string _connectionClass = String.Empty; public string ConnectionClass { get { return _connectionClass; } set { _connectionClass = value == null ? String.Empty : value; } } private string _connectionStringBuilderClass = String.Empty; public string ConnectionStringBuilderClass { get { return _connectionStringBuilderClass; } set { _connectionStringBuilderClass = value == null ? String.Empty : value; } } public void GetConnectionParameters (D4.Tags tags, Schema.DeviceSessionInfo deviceSessionInfo) { StringToTags(ConnectionParameters, tags); StringToTags(deviceSessionInfo.ConnectionParameters, tags); } public static string TagsToString(Language.D4.Tags tags) { StringBuilder result = new StringBuilder(); #if USEHASHTABLEFORTAGS foreach (D4.Tag tag in ATags) { #else D4.Tag tag; for (int index = 0; index < tags.Count; index++) { tag = tags[index]; #endif if (result.Length > 0) result.Append(";"); result.AppendFormat("{0}={1}", tag.Name, tag.Value); } return result.ToString(); } public static void StringToTags(String stringValue, Language.D4.Tags tags) { if (stringValue != null && stringValue != "") { string[] array = stringValue.Split(';'); for (int index = 0; index < array.Length; index++) { string[] tempArray = array[index].Split('='); if (tempArray.Length != 2) throw new Schema.SchemaException(DAE.Schema.SchemaException.Codes.InvalidConnectionString); tags.AddOrUpdate(tempArray[0], tempArray[1]); } } } /// <summary>Determines the default buffer size for SQLDeviceCursors created for this device.</summary> /// <remarks>A value of 0 for this property indicates that the SQLDeviceCursors should be disconnected, i.e. the entire result set will be cached by the device on open.</remarks> private int _connectionBufferSize = SQLDeviceCursor.DefaultBufferSize; public int ConnectionBufferSize { get { return _connectionBufferSize; } set { _connectionBufferSize = value; } } } public class SQLConnectionHeader : Disposable { public SQLConnectionHeader(SQLConnection connection) : base() { _connection = connection; } protected override void Dispose(bool disposing) { if (_connection != null) { _connection.Dispose(); _connection = null; } base.Dispose(disposing); } private SQLConnection _connection; public SQLConnection Connection { get { return _connection; } } private SQLDeviceCursor _deviceCursor; public SQLDeviceCursor DeviceCursor { get { return _deviceCursor; } set { _deviceCursor = value; } } } #if USETYPEDLIST public class SQLConnectionPool : DisposableTypedList { public SQLConnectionPool() : base(typeof(SQLConnectionHeader)) {} public new SQLConnectionHeader this[int AIndex] { get { return (SQLConnectionHeader)base[AIndex]; } set { base[AIndex] = value; } } #else public class SQLConnectionPool : DisposableList<SQLConnectionHeader> { #endif /// <returns>Returns the first avaiable connection in the pool. Will return null, if there are no available connections.</returns> public SQLConnectionHeader AvailableConnectionHeader() { for (int index = 0; index < Count; index++) if (this[index].Connection.State == SQLConnectionState.Idle) { Move(index, Count - 1); return this[Count - 1]; } return null; } public int IndexOfConnection(SQLConnection connection) { for (int index = 0; index < Count; index++) if (System.Object.ReferenceEquals(this[index].Connection, connection)) return index; return -1; } } public class SQLJoinContext : System.Object { public SQLJoinContext(SQLQueryContext leftQueryContext, SQLQueryContext rightQueryContext) : base() { LeftQueryContext = leftQueryContext; RightQueryContext = rightQueryContext; } public SQLQueryContext LeftQueryContext; public SQLQueryContext RightQueryContext; } #if USETYPEDLIST public class SQLJoinContexts : TypedList { public SQLJoinContexts() : base(typeof(SQLJoinContext), /* AllowNulls */ true) {} public new SQLJoinContext this[int AIndex] { get { return (SQLJoinContext)base[AIndex]; } set { base[AIndex] = value; } } } #else public class SQLJoinContexts : BaseList<SQLJoinContext> { } #endif [Flags] public enum SQLReferenceFlags { None = 0, HasAggregateExpressions = 1, // Indicates that the expression contains aggregate expressions in the outer-most query context HasSubSelectExpressions = 2, // Indicates that the expression contains subselect expressions in the outer-most query context HasCorrelation = 4, // Indicates that the expression contains a correlation (references a query-context outside the outer-most query context of the expression) HasParameters = 8 // Indicates that the expression contains parameters and is therefore not a literal in the SQL statement } public class SQLRangeVarColumn : System.Object { public SQLRangeVarColumn(TableVarColumn tableVarColumn, string tableAlias, string columnName) { _tableVarColumn = tableVarColumn; TableAlias = tableAlias; ColumnName = columnName; Alias = ColumnName; } public SQLRangeVarColumn(TableVarColumn tableVarColumn, string tableAlias, string columnName, string alias) { _tableVarColumn = tableVarColumn; TableAlias = tableAlias; ColumnName = columnName; Alias = alias; } public SQLRangeVarColumn(TableVarColumn tableVarColumn, Expression expression, string alias) { _tableVarColumn = tableVarColumn; _expression = expression; Alias = alias; } private TableVarColumn _tableVarColumn; /// <summary>The table var column in the D4 expression. This is the unique identifier for the range var column.</summary> public TableVarColumn TableVarColumn { get { return _tableVarColumn; } } private string _tableAlias = String.Empty; /// <summary>The name of the range var containing the column in the current query context. If this is empty, the expression will be specified, and vice versa.</summary> public string TableAlias { get { return _tableAlias; } set { _tableAlias = value == null ? String.Empty : value; } } private string _columnName = String.Empty; /// <summary>The name of the column in the table in the target system. If the column name is specified, the expression will be null, and vice versa.</summary> public string ColumnName { get { return _columnName; } set { _columnName = value == null ? String.Empty : value; if (_columnName != String.Empty) _expression = null; } } private Expression _expression; /// <summary>Expression is the expression used to define this column. Will be null if this is a base column reference.</summary> public Expression Expression { get { return _expression; } set { _expression = value; if (_expression != null) { _tableAlias = String.Empty; _columnName = String.Empty; } } } private string _alias = String.Empty; /// <summary>The alias name for this column in the current query context, if specified.</summary> public string Alias { get { return _alias; } set { _alias = value == null ? String.Empty : value; } } // ReferenceFlags private SQLReferenceFlags _referenceFlags; public SQLReferenceFlags ReferenceFlags { get { return _referenceFlags; } set { _referenceFlags = value; } } // GetExpression - returns an expression suitable for use in a where clause or other referencing context public Expression GetExpression() { if (_expression == null) return new QualifiedFieldExpression(_columnName, _tableAlias); else return _expression; } // GetColumnExpression - returns a ColumnExpression suitable for use in a select list public ColumnExpression GetColumnExpression() { return new ColumnExpression(GetExpression(), _alias); } } #if USETYPEDLIST public class SQLRangeVarColumns : TypedList { public SQLRangeVarColumns() : base(typeof(SQLRangeVarColumn)) {} public new SQLRangeVarColumn this[int AIndex] { get { return (SQLRangeVarColumn)base[AIndex]; } set { base[AIndex] = value; } } #else public class SQLRangeVarColumns : BaseList<SQLRangeVarColumn> { #endif public SQLRangeVarColumn this[string columnName] { get { return this[IndexOf(columnName)]; } } public int IndexOf(string columnName) { if (columnName.IndexOf(Keywords.Qualifier) == 0) { for (int index = 0; index < Count; index++) if (Schema.Object.NamesEqual(this[index].TableVarColumn.Name, columnName)) return index; } else { for (int index = 0; index < Count; index++) if (this[index].TableVarColumn.Name == columnName) return index; } return -1; } public bool Contains(string columnName) { return IndexOf(columnName) >= 0; } } public class SQLRangeVar : System.Object { public SQLRangeVar(string name) { _name = name; } // Name private string _name; public string Name { get { return _name; } } // Columns private SQLRangeVarColumns _columns = new SQLRangeVarColumns(); public SQLRangeVarColumns Columns { get { return _columns; } } } #if USETYPEDLIST public class SQLRangeVars : TypedList { public SQLRangeVars() : base(typeof(SQLRangeVar)) {} public new SQLRangeVar this[int AIndex] { get { return (SQLRangeVar)base[AIndex]; } set { base[AIndex] = value; } } } #else public class SQLRangeVars : BaseList<SQLRangeVar> { } #endif public class SQLQueryContext : System.Object { public SQLQueryContext() : base() {} public SQLQueryContext(SQLQueryContext parentContext) : base() { _parentContext = parentContext; } public SQLQueryContext(SQLQueryContext parentContext, bool isNestedFrom) : base() { _parentContext = parentContext; _isNestedFrom = isNestedFrom; } public SQLQueryContext(SQLQueryContext parentContext, bool isNestedFrom, bool isScalarContext) : base() { _parentContext = parentContext; _isNestedFrom = isNestedFrom; _isScalarContext = isScalarContext; } private SQLRangeVars _rangeVars = new SQLRangeVars(); public SQLRangeVars RangeVars { get { return _rangeVars; } } private SQLRangeVarColumns _addedColumns = new SQLRangeVarColumns(); public SQLRangeVarColumns AddedColumns { get { return _addedColumns; } } private SQLQueryContext _parentContext; public SQLQueryContext ParentContext { get { return _parentContext; } } private bool _isNestedFrom; public bool IsNestedFrom { get { return _isNestedFrom; } } private bool _isScalarContext; public bool IsScalarContext { get { return _isScalarContext; } } // True if this query context is an aggregate expression private bool _isAggregate; public bool IsAggregate { get { return _isAggregate; } set { _isAggregate = value; } } // True if this query context contains computed columns private bool _isExtension; public bool IsExtension { get { return _isExtension; } set { _isExtension = value; } } private bool _isSelectClause; public bool IsSelectClause { get { return _isSelectClause; } set { _isSelectClause = value; } } private bool _isWhereClause; public bool IsWhereClause { get { return _isWhereClause; } set { _isWhereClause = value; } } private bool _isGroupByClause; public bool IsGroupByClause { get { return _isGroupByClause; } set { _isGroupByClause = value; } } private bool _isHavingClause; public bool IsHavingClause { get { return _isHavingClause; } set { _isHavingClause = value; } } private bool _isListContext; public bool IsListContext { get { return _isListContext; } set { _isListContext = value; } } // ReferenceFlags - These flags are set when the appropriate type of reference has taken place in this context private SQLReferenceFlags _referenceFlags; public SQLReferenceFlags ReferenceFlags { get { return _referenceFlags; } set { _referenceFlags = value; } } public void ResetReferenceFlags() { _referenceFlags = SQLReferenceFlags.None; } public SQLRangeVarColumn GetRangeVarColumn(string identifier) { SQLRangeVarColumn column = FindRangeVarColumn(identifier); if (column == null) throw new CompilerException(CompilerException.Codes.UnknownIdentifier, identifier); return column; } public SQLRangeVarColumn FindRangeVarColumn(string identifier) { if (_addedColumns.Contains(identifier)) return _addedColumns[identifier]; foreach (SQLRangeVar rangeVar in _rangeVars) if (rangeVar.Columns.Contains(identifier)) return rangeVar.Columns[identifier]; return null; } public void ProjectColumns(Schema.TableVarColumns columns) { for (int index = _addedColumns.Count - 1; index >= 0; index--) if (!columns.Contains(_addedColumns[index].TableVarColumn)) _addedColumns.RemoveAt(index); foreach (SQLRangeVar rangeVar in _rangeVars) for (int index = rangeVar.Columns.Count - 1; index >= 0; index--) if (!columns.Contains(rangeVar.Columns[index].TableVarColumn)) rangeVar.Columns.RemoveAt(index); } public void RemoveColumn(SQLRangeVarColumn column) { if (_addedColumns.Contains(column)) _addedColumns.Remove(column); foreach (SQLRangeVar rangeVar in _rangeVars) if (rangeVar.Columns.Contains(column)) rangeVar.Columns.Remove(column); } /// <summary> /// Renames the given column and returns the new column. /// </summary> /// <param name="devicePlan">The device plan supporting the translation.</param> /// <param name="oldColumn">The column to be renamed.</param> /// <param name="newColumn">The new column.</param> /// <returns>The renamed SQLRangeVarColumn instance.</returns> /// <remarks> /// Note that this method removes the old column from the query context and DOES NOT add the new column. /// The returned column must be added to the query context by the caller. This is done because a rename /// operation may in general contain name exchanges, so the columns must all be removed and then re-added /// to the query context after all columns have been renamed to avoid the possibility of a subsequent /// column rename finding the newly added column for a rename in the same operation. /// </remarks> public SQLRangeVarColumn RenameColumn(SQLDevicePlan devicePlan, Schema.TableVarColumn oldColumn, Schema.TableVarColumn newColumn) { SQLRangeVarColumn localOldColumn = GetRangeVarColumn(oldColumn.Name); SQLRangeVarColumn localNewColumn; if (localOldColumn.ColumnName != String.Empty) localNewColumn = new SQLRangeVarColumn(newColumn, localOldColumn.TableAlias, localOldColumn.ColumnName); else localNewColumn = new SQLRangeVarColumn(newColumn, localOldColumn.Expression, localOldColumn.Alias); RemoveColumn(localOldColumn); localNewColumn.ReferenceFlags = localOldColumn.ReferenceFlags; localNewColumn.Alias = devicePlan.Device.ToSQLIdentifier(newColumn.Name); return localNewColumn; } } public class SQLDevicePlan : DevicePlan { public SQLDevicePlan(Plan plan, SQLDevice device, PlanNode planNode) : base(plan, device, planNode) { if ((planNode != null) && (planNode.DeviceNode != null)) _devicePlanNode = (SQLDevicePlanNode)planNode.DeviceNode; } public new SQLDevice Device { get { return (SQLDevice)base.Device; } } // SQLQueryContexts private SQLQueryContext _queryContext = new SQLQueryContext(); public void PushQueryContext(bool isNestedFrom) { _queryContext = new SQLQueryContext(_queryContext, isNestedFrom, false); } public void PushQueryContext() { PushQueryContext(false); } public void PopQueryContext() { _queryContext = _queryContext.ParentContext; } public SQLQueryContext CurrentQueryContext() { if (_queryContext == null) throw new SQLException(SQLException.Codes.NoCurrentQueryContext); return _queryContext; } public void PushScalarContext() { _queryContext = new SQLQueryContext(_queryContext, false, true); } public void PopScalarContext() { PopQueryContext(); } // Internal stack used for translation private Symbols _stack = new Symbols(); public Symbols Stack { get { return _stack; } } // JoinContexts (only used for natural join translation) private SQLJoinContexts _joinContexts = new SQLJoinContexts(); public void PushJoinContext(SQLJoinContext joinContext) { _joinContexts.Add(joinContext); } public void PopJoinContext() { _joinContexts.RemoveAt(_joinContexts.Count - 1); } // This will return null if the join being translated is not a natural join public SQLJoinContext CurrentJoinContext() { if (_joinContexts.Count == 0) throw new SQLException(SQLException.Codes.NoCurrentJoinContext); return _joinContexts[_joinContexts.Count - 1]; } public bool HasJoinContext() { return (CurrentJoinContext() != null); } // IsSubSelectSupported() - returns true if a subselect is supported in the current context public bool IsSubSelectSupported() { SQLQueryContext context = CurrentQueryContext(); return context.IsScalarContext && ( !(context.IsSelectClause || context.IsWhereClause || context.IsGroupByClause || context.IsHavingClause) || (context.IsSelectClause && Device.SupportsSubSelectInSelectClause) || (context.IsWhereClause && Device.SupportsSubSelectInWhereClause) || (context.IsGroupByClause && Device.SupportsSubSelectInGroupByClause) || (context.IsHavingClause && Device.SupportsSubSelectInHavingClause) ); } public string GetSubSelectNotSupportedReason() { SQLQueryContext context = CurrentQueryContext(); if (context.IsSelectClause && !Device.SupportsSubSelectInSelectClause) return "Plan is not supported because the device does not support sub-selects in the select clause."; if (context.IsWhereClause && !Device.SupportsSubSelectInWhereClause) return "Plan is not supported because the device does not support sub-selects in the where clause."; if (context.IsGroupByClause && !Device.SupportsSubSelectInGroupByClause) return "Plan is not supported because the device does not support sub-selects in the group by clause."; if (context.IsHavingClause && !Device.SupportsSubSelectInHavingClause) return "Plan is not supported because the device does not support sub-selects in the having clause."; return String.Empty; } // IsBooleanContext private ArrayList _contexts = new ArrayList(); public bool IsBooleanContext() { return (_contexts.Count > 0) && ((bool)_contexts[_contexts.Count - 1]); } public void EnterContext(bool isBooleanContext) { _contexts.Add(isBooleanContext); } public void ExitContext() { _contexts.RemoveAt(_contexts.Count - 1); } private int _counter = 0; private List<string> _tableAliases = new List<string>(); public string GetNextTableAlias() { _counter++; string tableAlias = String.Format("T{0}", _counter.ToString()); _tableAliases.Add(tableAlias); return tableAlias; } private SQLDevicePlanNode _devicePlanNode; public SQLDevicePlanNode DevicePlanNode { get { return _devicePlanNode; } set { _devicePlanNode = value; } } public SQLRangeVarColumn GetRangeVarColumn(string identifier, bool currentContextOnly) { SQLRangeVarColumn column = FindRangeVarColumn(identifier, currentContextOnly); if (column == null) throw new CompilerException(CompilerException.Codes.UnknownIdentifier, identifier); return column; } public SQLRangeVarColumn FindRangeVarColumn(string identifier, bool currentContextOnly) { SQLRangeVarColumn column = null; bool inCurrentContext = true; SQLQueryContext queryContext = CurrentQueryContext(); while (queryContext != null) { column = queryContext.FindRangeVarColumn(identifier); if (column != null) break; if (queryContext.IsScalarContext) queryContext = queryContext.ParentContext; else { if (currentContextOnly || (queryContext.IsNestedFrom && !Device.SupportsNestedCorrelation)) break; queryContext = queryContext.ParentContext; inCurrentContext = false; } } if (column != null) { if (!inCurrentContext) CurrentQueryContext().ReferenceFlags |= SQLReferenceFlags.HasCorrelation; CurrentQueryContext().ReferenceFlags |= column.ReferenceFlags; } return column; } } public class SQLDevicePlanNode : DevicePlanNode { public SQLDevicePlanNode(PlanNode planNode) : base(planNode) {} private Statement _statement; public Statement Statement { get { return _statement; } set { _statement = value; } } // Parameters private SQLPlanParameters _planParameters = new SQLPlanParameters(); public SQLPlanParameters PlanParameters { get { return _planParameters; } } } public class TableSQLDevicePlanNode : SQLDevicePlanNode { public TableSQLDevicePlanNode(PlanNode planNode) : base(planNode) {} private bool _isAggregate; public bool IsAggregate { get { return _isAggregate; } set { _isAggregate = value; } } } public class ScalarSQLDevicePlanNode : SQLDevicePlanNode { public ScalarSQLDevicePlanNode(PlanNode planNode) : base(planNode) {} private SQLScalarType _mappedType; public SQLScalarType MappedType { get { return _mappedType; } set { _mappedType = value; } } } public class RowSQLDevicePlanNode : SQLDevicePlanNode { public RowSQLDevicePlanNode(PlanNode planNode) : base(planNode) {} private List<SQLScalarType> _mappedTypes = new List<SQLScalarType>(); public List<SQLScalarType> MappedTypes { get { return _mappedTypes; } } } public class SQLPlanParameter : System.Object { public SQLPlanParameter(SQLParameter sQLParameter, PlanNode planNode, SQLScalarType scalarType) : base() { _sQLParameter = sQLParameter; _planNode = planNode; _scalarType = scalarType; } private SQLParameter _sQLParameter; public SQLParameter SQLParameter { get { return _sQLParameter; } } private PlanNode _planNode; public PlanNode PlanNode { get { return _planNode; } } private SQLScalarType _scalarType; public SQLScalarType ScalarType { get { return _scalarType; } } } #if USETYPEDLIST public class SQLPlanParameters : TypedList { public SQLPlanParameters() : base(typeof(SQLPlanParameter)){} public new SQLPlanParameter this[int AIndex] { get { return (SQLPlanParameter)base[AIndex]; } set { base[AIndex] = value; } } } #else public class SQLPlanParameters : BaseList<SQLPlanParameter> { } #endif public abstract class SQLDeviceSession : DeviceSession, IStreamProvider { public SQLDeviceSession(SQLDevice device, ServerProcess process, Schema.DeviceSessionInfo deviceSessionInfo) : base(device, process, deviceSessionInfo) {} protected override void Dispose(bool disposing) { try { if (Transactions != null) EnsureTransactionsRolledback(); } finally { try { if (_streams != null) { DestroyStreams(); _streams = null; } } finally { try { if (_browsePool != null) { if (Device.UseTransactions) { for (int index = 0; index < _browsePool.Count; index++) try { if (_browsePool[index].Connection.InTransaction) _browsePool[index].Connection.CommitTransaction(); } catch {} } _browsePool.Dispose(); _browsePool = null; } } finally { try { if (_executePool != null) { _executePool.Dispose(); _executePool = null; } } finally { base.Dispose(disposing); // Call the base here to clean up any outstanding transactions } } } } } public new SQLDevice Device { get { return (SQLDevice)base.Device; } } protected abstract SQLConnection InternalCreateConnection(); protected SQLConnection CreateConnection() { SQLConnection connection = InternalCreateConnection(); connection.DefaultCommandTimeout = Device.CommandTimeout; connection.DefaultUseParametersForCursors = Device.UseParametersForCursors; connection.DefaultShouldNormalizeWhitespace = Device.ShouldNormalizeWhitespace; return connection; } private SQLConnectionPool _browsePool = new SQLConnectionPool(); private SQLConnectionPool _executePool = new SQLConnectionPool(); public SQLConnection Connection { get { return RequestConnection(false).Connection; } } private bool _executingConnectionStatement; protected virtual void ExecuteConnectStatement(SQLConnectionHeader connectionHeader, bool isBrowseCursor) { if (!ServerProcess.IsLoading()) { if (!_executingConnectionStatement) { _executingConnectionStatement = true; try { string executeStatementExpression = isBrowseCursor ? Device.OnBrowseConnectStatement : Device.OnExecuteConnectStatement; if (executeStatementExpression != null) { string executeStatement = null; IServerExpressionPlan plan = ((IServerProcess)ServerProcess).PrepareExpression(executeStatementExpression, null); try { executeStatement = ((IScalar)plan.Evaluate(null)).AsString; } finally { ((IServerProcess)ServerProcess).UnprepareExpression(plan); } connectionHeader.Connection.Execute(executeStatement); if (connectionHeader.Connection.InTransaction) { connectionHeader.Connection.CommitTransaction(); connectionHeader.Connection.BeginTransaction(_isolationLevel); } } } finally { _executingConnectionStatement = false; } } else throw new SQLException(SQLException.Codes.AlreadyExecutingConnectionStatement, Device.Name); } } public virtual SQLConnectionHeader RequestConnection(bool isBrowseCursor) { SQLConnectionHeader connectionHeader = isBrowseCursor ? _browsePool.AvailableConnectionHeader() : _executePool.AvailableConnectionHeader(); // Ensure Transaction Started if (Device.UseTransactions && (Transactions.Count > 0) && !_transactionStarted) _transactionStarted = true; if (connectionHeader == null) { SQLConnection connection = AddConnection(isBrowseCursor); if (connection != null) { connectionHeader = new SQLConnectionHeader(connection); if (isBrowseCursor) _browsePool.Add(connectionHeader); else _executePool.Add(connectionHeader); try { ExecuteConnectStatement(connectionHeader, isBrowseCursor); } catch { if (isBrowseCursor) _browsePool.Remove(connectionHeader); else _executePool.Remove(connectionHeader); connectionHeader.Dispose(); throw; } } } if (connectionHeader == null) { // Perform a Cursor switch here to free up a connection on the transaction // This means that all connections in the execute pool are currently supporting open cursors. // Select the connection victim (the first connection in the execute pool) connectionHeader = _executePool[0]; // Move the connection to the back of the list for round-robin pool replacement _executePool.Move(0, _executePool.Count - 1); if (connectionHeader.DeviceCursor != null) connectionHeader.DeviceCursor.ReleaseConnection(connectionHeader); } // If the connection is closed, throw out the connection if (!connectionHeader.Connection.IsConnectionValid()) { if (isBrowseCursor) _browsePool.Remove(connectionHeader); else _executePool.Remove(connectionHeader); connectionHeader.Dispose(); connectionHeader = RequestConnection(isBrowseCursor); } // Ensure the connection has an active transaction if (Device.UseTransactions && (Transactions.Count > 0) && !isBrowseCursor && !connectionHeader.Connection.InTransaction) connectionHeader.Connection.BeginTransaction(_isolationLevel); return connectionHeader; } public void ReleaseConnection(SQLConnection connection) { ReleaseConnection(connection, false); } public virtual void ReleaseConnection(SQLConnection connection, bool disposing) { int index = _browsePool.IndexOfConnection(connection); if (index >= 0) { var header = _browsePool[index]; if (header.DeviceCursor != null) header.DeviceCursor.ReleaseConnection(header, disposing); if (header.Connection.InTransaction) header.Connection.CommitTransaction(); header.Dispose(); // Always release browse connections } else { index = _executePool.IndexOfConnection(connection); if (index >= 0) { var header = _executePool[index]; if (header.DeviceCursor != null) header.DeviceCursor.ReleaseConnection(header, disposing); if (!Device.UseTransactions || Transactions.Count == 0) header.Dispose(); } else throw new SQLException(SQLException.Codes.ConnectionNotFound); } } // This override allows for the implementation of transaction binding across connections such as distributed transactions or session binding. protected virtual SQLConnection AddConnection(bool isBrowseCursor) { if (isBrowseCursor) { SQLConnection connection = CreateConnection(); if (Device.UseTransactions && (Transactions.Count > 0)) connection.BeginTransaction(SQLIsolationLevel.ReadUncommitted); return connection; } else { if (_executePool.Count == 0) { SQLConnection connection = CreateConnection(); if (Device.UseTransactions && (Transactions.Count > 0) && _transactionStarted) connection.BeginTransaction(_isolationLevel); return connection; } else return null; } } public static SQLIsolationLevel IsolationLevelToSQLIsolationLevel(IsolationLevel isolationLevel) { switch (isolationLevel) { case IsolationLevel.Browse : return SQLIsolationLevel.ReadUncommitted; case IsolationLevel.CursorStability : return SQLIsolationLevel.ReadCommitted; case IsolationLevel.Isolated : return SQLIsolationLevel.Serializable; } return SQLIsolationLevel.Serializable; } // BeginTransaction private SQLIsolationLevel _isolationLevel; private bool _transactionStarted; protected override void InternalBeginTransaction(IsolationLevel isolationLevel) { if (Device.UseTransactions && (Transactions.Count == 1)) // If this is the first transaction { _isolationLevel = IsolationLevelToSQLIsolationLevel(isolationLevel); // Transaction starting is deferred until actually necessary _transactionStarted = false; _transactionFailure = false; } } private bool _transactionFailure; /// <summary> Indicates whether the DBMS-side transaction has been rolled-back. </summary> public bool TransactionFailure { get { return _transactionFailure; } set { _transactionFailure = value; } } protected override bool IsTransactionFailure(Exception exception) { return _transactionFailure; } protected override void InternalPrepareTransaction() {} // CommitTransaction protected override void InternalCommitTransaction() { if (Device.UseTransactions && (Transactions.Count == 1) && _transactionStarted) { for (int index = _executePool.Count - 1; index >= 0; index--) { var header = _executePool[index]; if (header.DeviceCursor != null) header.DeviceCursor.ReleaseConnection(header, true); try { if (header.Connection.InTransaction) header.Connection.CommitTransaction(); } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } // Dispose the connection to release it back to the server try { _executePool.DisownAt(index).Dispose(); } catch { // Ignore errors disposing the connection, as long as it removed from the execute pool, we are good } } _transactionStarted = false; } } // RollbackTransaction protected override void InternalRollbackTransaction() { if (Device.UseTransactions && (Transactions.Count == 1) && _transactionStarted) { for (int index = _executePool.Count - 1; index >= 0; index--) { var header = _executePool[index]; if (header.DeviceCursor != null) header.DeviceCursor.ReleaseConnection(header, true); try { if (header.Connection.InTransaction) header.Connection.RollbackTransaction(); } catch { _transactionFailure = header.Connection.TransactionFailure; // Don't rethrow, we do not care if there was an issue rolling back on the server, there's nothing we can do about it here } // Dispose the connection to release it back to the server try { _executePool.DisownAt(index).Dispose(); } catch { // Ignore errors disposing the connection, as long as it is removed from the execute pool, we are good } } for (int index = 0; index < _executePool.Count; index++) { if (_executePool[index].DeviceCursor != null) _executePool[index].DeviceCursor.ReleaseConnection(_executePool[index], true); try { if (_executePool[index].Connection.InTransaction) _executePool[index].Connection.RollbackTransaction(); } catch { _transactionFailure = _executePool[index].Connection.TransactionFailure; } } _transactionStarted = false; } } protected virtual SQLTable CreateSQLTable(Program program, TableNode node, SelectStatement selectStatement, SQLParameters parameters, bool isAggregate) { return new SQLTable(this, program, node, selectStatement, parameters, isAggregate); } protected void SetParameterValueLength(object nativeParamValue, SQLPlanParameter planParameter) { string stringParamValue = nativeParamValue as String; SQLStringType parameterType = planParameter.SQLParameter.Type as SQLStringType; if ((parameterType != null) && (stringParamValue != null) && (parameterType.Length != stringParamValue.Length)) parameterType.Length = stringParamValue.Length <= 20 ? 20 : stringParamValue.Length; } protected void PrepareSQLParameters(Program program, SQLDevicePlanNode devicePlanNode, bool isCursor, SQLParameters parameters) { object paramValue; object nativeParamValue; foreach (SQLPlanParameter planParameter in devicePlanNode.PlanParameters) { paramValue = planParameter.PlanNode.Execute(program); nativeParamValue = (paramValue == null) ? null : planParameter.ScalarType.ParameterFromScalar(program.ValueManager, paramValue); if (nativeParamValue != null) SetParameterValueLength(nativeParamValue, planParameter); parameters.Add ( new SQLParameter ( planParameter.SQLParameter.Name, planParameter.SQLParameter.Type, nativeParamValue, planParameter.SQLParameter.Direction, planParameter.SQLParameter.Marker, Device.UseParametersForCursors && isCursor ? null : planParameter.ScalarType.ToLiteral(program.ValueManager, paramValue) ) ); } } // Execute protected override object InternalExecute(Program program, PlanNode planNode) { if (planNode.DeviceNode == null) { throw new DeviceException(DeviceException.Codes.UnpreparedDevicePlan, ErrorSeverity.System); } var devicePlanNode = (SQLDevicePlanNode)planNode.DeviceNode; if (planNode is DMLNode) { SQLConnectionHeader header = RequestConnection(false); try { using (SQLCommand command = header.Connection.CreateCommand(false)) { command.Statement = Device.Emitter.Emit(devicePlanNode.Statement); PrepareSQLParameters(program, devicePlanNode, false, command.Parameters); command.Execute(); return null; } } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } else if (planNode is DDLNode) { SQLConnectionHeader header = RequestConnection(false); try { if ((!ServerProcess.IsLoading()) && ((Device.ReconcileMode & D4.ReconcileMode.Command) != 0)) { Statement dDLStatement = devicePlanNode.Statement; if (dDLStatement is Batch) { // If this is a batch, split it into separate statements for execution. This is required because the Oracle ODBC driver does // not allow multiple statements to be executed at a time. using (SQLCommand command = header.Connection.CreateCommand(false)) { foreach (Statement statement in ((Batch)dDLStatement).Statements) { string statementString = Device.Emitter.Emit(statement); if (statementString != String.Empty) { command.Statement = statementString; command.Execute(); } } } } else { string statement = Device.Emitter.Emit(devicePlanNode.Statement); if (statement != String.Empty) { using (SQLCommand command = header.Connection.CreateCommand(false)) { command.Statement = statement; PrepareSQLParameters(program, devicePlanNode, false, command.Parameters); command.Execute(); } } } } return null; } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } else { if (planNode is TableNode) { SQLParameters parameters = new SQLParameters(); PrepareSQLParameters(program, devicePlanNode, true, parameters); SQLTable table = CreateSQLTable(program, (TableNode)planNode, (SelectStatement)devicePlanNode.Statement, parameters, ((TableSQLDevicePlanNode)planNode.DeviceNode).IsAggregate); try { table.Open(); return table; } catch { table.Dispose(); throw; } } else { SQLConnectionHeader header = RequestConnection(false); try { using (SQLCommand command = header.Connection.CreateCommand(true)) { command.Statement = Device.Emitter.Emit(devicePlanNode.Statement); PrepareSQLParameters(program, devicePlanNode, true, command.Parameters); SQLCursor cursor = command.Open(SQLCursorType.Dynamic, IsolationLevelToSQLIsolationLevel(ServerProcess.CurrentIsolationLevel())); //SQLIsolationLevel.ReadCommitted); try { if (cursor.Next()) { if (planNode.DataType is Schema.IScalarType) { if (cursor.IsNull(0)) return null; else return ((ScalarSQLDevicePlanNode)planNode.DeviceNode).MappedType.ToScalar(ServerProcess.ValueManager, cursor[0]); } else { Row row = new Row(program.ValueManager, (Schema.IRowType)planNode.DataType); var rowDeviceNode = planNode.DeviceNode as RowSQLDevicePlanNode; for (int index = 0; index < row.DataType.Columns.Count; index++) if (!cursor.IsNull(index)) row[index] = rowDeviceNode.MappedTypes[index].ToScalar(ServerProcess.ValueManager, cursor[index]); if (cursor.Next()) throw new RuntimeException(RuntimeException.Codes.InvalidRowExtractorExpression); return row; } } else return null; } finally { command.Close(cursor); } } } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } } } // InsertRow protected virtual void InternalVerifyInsertStatement(TableVar table, IRow row, InsertStatement statement) {} protected override void InternalInsertRow(Program program, TableVar table, IRow row, BitArray valueFlags) { SQLConnectionHeader header = RequestConnection(false); try { using (SQLCommand command = header.Connection.CreateCommand(false)) { InsertStatement insertStatement = new InsertStatement(); insertStatement.InsertClause = new InsertClause(); insertStatement.InsertClause.TableExpression = new TableExpression(); insertStatement.InsertClause.TableExpression.TableSchema = D4.MetaData.GetTag(table.MetaData, "Storage.Schema", Device.Schema); insertStatement.InsertClause.TableExpression.TableName = Device.ToSQLIdentifier(table); if (Device.UseValuesClauseInInsert) { ValuesExpression values = new ValuesExpression(); insertStatement.Values = values; string columnName; string parameterName; Schema.TableVarColumn column; SQLScalarType scalarType; for (int index = 0; index < row.DataType.Columns.Count; index++) { column = table.Columns[table.Columns.IndexOfName(row.DataType.Columns[index].Name)]; columnName = Device.ToSQLIdentifier(column); parameterName = String.Format("P{0}", index.ToString()); insertStatement.InsertClause.Columns.Add(new InsertFieldExpression(columnName)); values.Expressions.Add(new QueryParameterExpression(parameterName)); scalarType = (SQLScalarType)Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType); command.Parameters.Add ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(column), row.HasValue(index) ? scalarType.ParameterFromScalar(program.ValueManager, row[index]) : null, SQLDirection.In, Device.GetParameterMarker(scalarType, column) ) ); } } else { // DB2/400 does not allow typed parameter markers in values clauses // We original removed the functionality from the insert statement, but now replaced it for consistency, and use // the UseValuesClauseInInsert switch instead. This is because we have to be able to take advantage of the // parameter markers capability to force a cast client side in order to use strings to pass values // across the CLI, but convert those strings to different types on the target system. This is to work around // an issue with passing decimals through the CLI. SelectExpression selectExpression = new SelectExpression(); insertStatement.Values = selectExpression; selectExpression.FromClause = new CalculusFromClause(Device.GetDummyTableSpecifier()); selectExpression.SelectClause = new SelectClause(); string columnName; string parameterName; Schema.TableVarColumn column; SQLScalarType scalarType; for (int index = 0; index < row.DataType.Columns.Count; index++) { column = table.Columns[table.Columns.IndexOfName(row.DataType.Columns[index].Name)]; columnName = Device.ToSQLIdentifier(column); parameterName = String.Format("P{0}", index.ToString()); insertStatement.InsertClause.Columns.Add(new InsertFieldExpression(columnName)); selectExpression.SelectClause.Columns.Add(new ColumnExpression(new QueryParameterExpression(parameterName), columnName)); scalarType = (SQLScalarType)Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType); command.Parameters.Add ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(column), row.HasValue(index) ? scalarType.ParameterFromScalar(program.ValueManager, row[index]) : null, SQLDirection.In, Device.GetParameterMarker(scalarType, column) ) ); } } InternalVerifyInsertStatement(table, row, insertStatement); if (Device.CommandTimeout >= 0) command.CommandTimeout = Device.CommandTimeout; command.Statement = Device.Emitter.Emit(insertStatement); command.Execute(); } } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } // UpdateRow protected virtual void InternalVerifyUpdateStatement(TableVar table, IRow oldRow, IRow newRow, UpdateStatement statement) {} protected override void InternalUpdateRow(Program program, TableVar table, IRow oldRow, IRow newRow, BitArray valueFlags) { UpdateStatement statement = new UpdateStatement(); statement.UpdateClause = new UpdateClause(); statement.UpdateClause.TableExpression = new TableExpression(); statement.UpdateClause.TableExpression.TableSchema = D4.MetaData.GetTag(table.MetaData, "Storage.Schema", Device.Schema); statement.UpdateClause.TableExpression.TableName = Device.ToSQLIdentifier(table); SQLConnectionHeader header = RequestConnection(false); try { using (SQLCommand command = header.Connection.CreateCommand(false)) { string columnName; string parameterName; Schema.TableVarColumn column; SQLScalarType scalarType; for (int index = 0; index < newRow.DataType.Columns.Count; index++) { if ((valueFlags == null) || valueFlags[index]) { column = table.Columns[index]; columnName = Device.ToSQLIdentifier(column); parameterName = String.Format("P{0}", index.ToString()); UpdateFieldExpression expression = new UpdateFieldExpression(); expression.FieldName = columnName; expression.Expression = new QueryParameterExpression(parameterName); scalarType = (SQLScalarType)Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType); command.Parameters.Add ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(column), newRow.HasValue(index) ? scalarType.ParameterFromScalar(program.ValueManager, newRow[index]) : null, SQLDirection.In, Device.GetParameterMarker(scalarType, column) ) ); statement.UpdateClause.Columns.Add(expression); } } if (statement.UpdateClause.Columns.Count > 0) { Schema.Key clusteringKey = program.FindClusteringKey(table); if (clusteringKey.Columns.Count > 0) { int rowIndex; statement.WhereClause = new WhereClause(); for (int index = 0; index < clusteringKey.Columns.Count; index++) { column = clusteringKey.Columns[index]; rowIndex = oldRow.DataType.Columns.IndexOfName(column.Name); columnName = Device.ToSQLIdentifier(column); parameterName = String.Format("P{0}", (index + newRow.DataType.Columns.Count).ToString()); scalarType = (SQLScalarType)Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType); command.Parameters.Add ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(column), oldRow.HasValue(rowIndex) ? scalarType.ParameterFromScalar(program.ValueManager, oldRow[rowIndex]) : null, SQLDirection.In, Device.GetParameterMarker(scalarType, column) ) ); Expression expression = new BinaryExpression ( new QualifiedFieldExpression(columnName), "iEqual", new QueryParameterExpression(parameterName) ); if (statement.WhereClause.Expression == null) statement.WhereClause.Expression = expression; else statement.WhereClause.Expression = new BinaryExpression(statement.WhereClause.Expression, "iAnd", expression); } } InternalVerifyUpdateStatement(table, oldRow, newRow, statement); if (Device.CommandTimeout >= 0) command.CommandTimeout = Device.CommandTimeout; command.Statement = Device.Emitter.Emit(statement); command.Execute(); } } } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } // DeleteRow protected virtual void InternalVerifyDeleteStatement(TableVar table, IRow row, DeleteStatement statement) {} protected override void InternalDeleteRow(Program program, TableVar table, IRow row) { DeleteStatement statement = new DeleteStatement(); statement.DeleteClause = new DeleteClause(); statement.DeleteClause.TableExpression = new TableExpression(); statement.DeleteClause.TableExpression.TableSchema = D4.MetaData.GetTag(table.MetaData, "Storage.Schema", Device.Schema); statement.DeleteClause.TableExpression.TableName = Device.ToSQLIdentifier(table); SQLConnectionHeader header = RequestConnection(false); try { using (SQLCommand command = header.Connection.CreateCommand(false)) { Schema.TableVarColumn column; string columnName; string parameterName; SQLScalarType scalarType; Schema.Key clusteringKey = program.FindClusteringKey(table); if (clusteringKey.Columns.Count > 0) { int rowIndex; statement.WhereClause = new WhereClause(); for (int index = 0; index < clusteringKey.Columns.Count; index++) { column = clusteringKey.Columns[index]; rowIndex = row.DataType.Columns.IndexOfName(column.Name); columnName = Device.ToSQLIdentifier(column); parameterName = String.Format("P{0}", index.ToString()); scalarType = (SQLScalarType)Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType); command.Parameters.Add ( new SQLParameter ( parameterName, scalarType.GetSQLParameterType(column), row.HasValue(rowIndex) ? scalarType.ParameterFromScalar(program.ValueManager, row[rowIndex]) : null, SQLDirection.In, Device.GetParameterMarker(scalarType, column) ) ); Expression expression = new BinaryExpression ( new QualifiedFieldExpression(columnName), "iEqual", new QueryParameterExpression(parameterName) ); if (statement.WhereClause.Expression == null) statement.WhereClause.Expression = expression; else statement.WhereClause.Expression = new BinaryExpression(statement.WhereClause.Expression, "iAnd", expression); } } InternalVerifyDeleteStatement(table, row, statement); if (Device.CommandTimeout >= 0) command.CommandTimeout = Device.CommandTimeout; command.Statement = Device.Emitter.Emit(statement); command.Execute(); } } catch { _transactionFailure = header.Connection.TransactionFailure; throw; } } // IStreamProvider private SQLStreamHeaders _streams = new SQLStreamHeaders(); private SQLStreamHeader GetStreamHeader(StreamID streamID) { SQLStreamHeader streamHeader = _streams[streamID]; if (streamHeader == null) throw new StreamsException(StreamsException.Codes.StreamIDNotFound, streamID.ToString()); return streamHeader; } protected void DestroyStreams() { foreach (StreamID streamID in _streams.Keys) _streams[streamID].Dispose(); _streams.Clear(); } public virtual void Create ( StreamID streamID, string columnName, Schema.DeviceScalarType deviceScalarType, string statement, SQLParameters parameters, SQLCursorType cursorType, SQLIsolationLevel isolationLevel ) { _streams.Add(new SQLStreamHeader(streamID, this, columnName, deviceScalarType, statement, parameters, cursorType, isolationLevel)); } public virtual Stream Open(StreamID streamID) { try { return GetStreamHeader(streamID).GetSourceStream(); } catch (Exception exception) { throw WrapException(exception); } } public virtual void Close(StreamID streamID) { // no action to perform } public virtual void Destroy(StreamID streamID) { SQLStreamHeader streamHeader = GetStreamHeader(streamID); _streams.Remove(streamID); streamHeader.Dispose(); } public virtual void Reassign(StreamID oldStreamID, StreamID newStreamID) { SQLStreamHeader streamHeader = GetStreamHeader(oldStreamID); _streams.Remove(oldStreamID); streamHeader.StreamID = newStreamID; _streams.Add(streamHeader); } // SQLExecute public void SQLExecute(string statement, SQLParameters parameters) { SQLConnectionHeader header = RequestConnection(false); try { header.Connection.Execute(statement, parameters); } catch (Exception exception) { _transactionFailure = header.Connection.TransactionFailure; throw WrapException(exception); } } } public class SQLStreamHeader : Disposable { public SQLStreamHeader ( StreamID streamID, SQLDeviceSession deviceSession, string columnName, Schema.DeviceScalarType deviceScalarType, string statement, SQLParameters parameters, SQLCursorType cursorType, SQLIsolationLevel isolationLevel ) : base() { _streamID = streamID; _deviceSession = deviceSession; _columnName = columnName; _deviceScalarType = deviceScalarType; _statement = statement; _parameters = parameters; _cursorType = cursorType; _isolationLevel = isolationLevel; } protected override void Dispose(bool disposing) { CloseSource(); _deviceScalarType = null; _deviceSession = null; _parameters = null; _streamID = StreamID.Null; base.Dispose(disposing); } // The stream manager id for this stream private StreamID _streamID; public StreamID StreamID { get { return _streamID; } set { _streamID = value; } } // The device session supporting this stream private SQLDeviceSession _deviceSession; // The name of the column from which this stream originated private string _columnName; // The device scalar type map for the data type of this stream private Schema.DeviceScalarType _deviceScalarType; // The statement used to retrieve the data for the stream private string _statement; // The parameters used to retrieve the data for the stream private SQLParameters _parameters; // The cursor type used for the open request private SQLCursorType _cursorType; // The isolation level used for the open request private SQLIsolationLevel _isolationLevel; // A DeferredWriteStream built on the DeferredStream obtained from a cursor based on the expression // <FTable.Node> where KeyColumns = KeyRowValues over { KeyColumns, DataColumn } private DeferredWriteStream _sourceStream; public Stream GetSourceStream() { OpenSource(); return _sourceStream; } // If the underlying value cannot be opened deferred from the connectivity layer, it is stored in this non-native scalar private Scalar _sourceValue; // The Cursor used to access the deferred stream private SQLCursor _cursor; public void OpenSource() { if (_sourceStream == null) { SQLConnectionHeader header = _deviceSession.RequestConnection(false); try { _cursor = header.Connection.Open(_statement, _parameters, _cursorType, _isolationLevel, SQLCommandBehavior.Default); try { if (_cursor.Next()) if (_cursor.IsDeferred(_cursor.ColumnCount - 1)) _sourceStream = new DeferredWriteStream(_deviceScalarType.GetStreamAdapter(_deviceSession.ServerProcess.ValueManager, _cursor.OpenDeferredStream(_cursor.ColumnCount - 1))); else { _sourceValue = new Scalar(_deviceSession.ServerProcess.ValueManager, _deviceScalarType.ScalarType); _sourceValue.AsNative = _deviceScalarType.ToScalar(_deviceSession.ServerProcess.ValueManager, _cursor[_cursor.ColumnCount - 1]); _sourceStream = new DeferredWriteStream(_sourceValue.OpenStream()); } else throw new SQLException(SQLException.Codes.DeferredDataNotFound, _columnName); } finally { _cursor.Command.Connection.Close(_cursor); _cursor = null; } } catch { _deviceSession.TransactionFailure = header.Connection.TransactionFailure; throw; } } } public void CloseSource() { try { if (_sourceStream != null) { _sourceStream.Close(); _sourceStream = null; } } finally { if (_sourceValue != null) { _sourceValue.Dispose(); _sourceValue = null; } } } } public class SQLStreamHeaders : Hashtable { public SQLStreamHeaders() : base(){} public SQLStreamHeader this[StreamID streamID] { get { return (SQLStreamHeader)base[streamID]; } } public void Add(SQLStreamHeader stream) { Add(stream.StreamID, stream); } public void Remove(SQLStreamHeader stream) { Remove(stream.StreamID); } } public class ColumnMap { public ColumnMap(Column column, ColumnExpression expression, int index) { _column = column; _columnExpression = expression; _index = index; } // The Column instance in DataType.Columns private Column _column; public Column Column { get { return _column; } } // The index of FColumn in DataType.Columns private int _index; public int Index { get { return _index; } } // The column expression in the translated statement private ColumnExpression _columnExpression; public ColumnExpression ColumnExpression { get { return _columnExpression; } } } #if USETYPEDLIST public class ColumnMaps : TypedList { public ColumnMaps() : base(typeof(ColumnMap)){} public new ColumnMap this[int AIndex] { get { return (ColumnMap)base[AIndex]; } set { base[AIndex] = value; } } #else public class ColumnMaps : BaseList<ColumnMap> { #endif // Returns the ColumnMap with the given ColumnIndex into DataType.Columns public ColumnMap ColumnMapByIndex(int index) { foreach (ColumnMap columnMap in this) if (columnMap.Index == index) return columnMap; throw new SQLException(SQLException.Codes.ColumnMapNotFound, index); } } public class SQLTableColumn { public SQLTableColumn(Schema.TableVarColumn column, Schema.DeviceScalarType scalarType) : base() { Column = column; ScalarType = scalarType; IsDeferred = Convert.ToBoolean(D4.MetaData.GetTag(Column.MetaData, "Storage.Deferred", "false")); } public Schema.TableVarColumn Column; public Schema.DeviceScalarType ScalarType; public bool IsDeferred; } #if USETYPEDLIST public class SQLTableColumns : TypedList { public SQLTableColumns() : base(typeof(SQLTableColumn)){} public new SQLTableColumn this[int AIndex] { get { return (SQLTableColumn)base[AIndex]; } set { base[AIndex] = value; } } } #else public class SQLTableColumns : BaseList<SQLTableColumn> { } #endif public class SQLTable : Table { public SQLTable(SQLDeviceSession deviceSession, Program program, TableNode tableNode, SelectStatement statement, SQLParameters parameters, bool isAggregate) : base(tableNode, program) { _deviceSession = deviceSession; _parameters = parameters; _statement = new SelectStatement(); _statement.Modifiers = statement.Modifiers; _isAggregate = isAggregate; _statement.QueryExpression = new QueryExpression(); _statement.QueryExpression.SelectExpression = new SelectExpression(); SelectClause selectClause = new SelectClause(); SelectClause givenSelectClause = statement.QueryExpression.SelectExpression.SelectClause; selectClause.Distinct = givenSelectClause.Distinct; selectClause.NonProject = givenSelectClause.NonProject; selectClause.Columns.AddRange(givenSelectClause.Columns); _statement.QueryExpression.SelectExpression.SelectClause = selectClause; _statement.QueryExpression.SelectExpression.FromClause = statement.QueryExpression.SelectExpression.FromClause; _statement.QueryExpression.SelectExpression.WhereClause = statement.QueryExpression.SelectExpression.WhereClause; _statement.QueryExpression.SelectExpression.GroupClause = statement.QueryExpression.SelectExpression.GroupClause; _statement.QueryExpression.SelectExpression.HavingClause = statement.QueryExpression.SelectExpression.HavingClause; _statement.OrderClause = statement.OrderClause; foreach (TableVarColumn column in Node.TableVar.Columns) { SQLTableColumn sQLColumn = new SQLTableColumn(column, (DeviceScalarType)_deviceSession.Device.ResolveDeviceScalarType(program.Plan, (Schema.ScalarType)column.DataType)); _sQLColumns.Add(sQLColumn); if (sQLColumn.IsDeferred) _hasDeferredData = true; } } protected override void Dispose(bool disposing) { Close(); _deviceSession = null; base.Dispose(disposing); } protected SQLDeviceSession _deviceSession; public SQLDeviceSession DeviceSession { get { return _deviceSession; } } protected SQLDeviceCursor _cursor; protected SQLParameters _parameters; protected SelectStatement _statement; protected bool _isAggregate; protected ColumnMaps _mainColumns = new ColumnMaps(); protected ColumnMaps _deferredColumns = new ColumnMaps(); protected SQLTableColumns _sQLColumns = new SQLTableColumns(); protected bool _hasDeferredData; protected bool _bOF; protected bool _eOF; public static SQLCursorType CursorTypeToSQLCursorType(DAE.CursorType cursorType) { switch (cursorType) { case DAE.CursorType.Static: return SQLCursorType.Static; default: return SQLCursorType.Dynamic; } } public static SQLLockType CursorCapabilitiesToSQLLockType(CursorCapability capabilities, IsolationLevel isolation) { return (((capabilities & CursorCapability.Updateable) != 0) && (isolation == IsolationLevel.Isolated)) ? SQLLockType.Pessimistic : SQLLockType.ReadOnly; } public static IsolationLevel CursorIsolationToIsolationLevel(CursorIsolation cursorIsolation, IsolationLevel isolation) { switch (cursorIsolation) { case CursorIsolation.Chaos: case CursorIsolation.Browse: return IsolationLevel.Browse; case CursorIsolation.CursorStability: case CursorIsolation.Isolated: return IsolationLevel.Isolated; default: return (isolation == IsolationLevel.Browse) ? IsolationLevel.Browse : IsolationLevel.Isolated; } } public static SQLIsolationLevel CursorIsolationToSQLIsolationLevel(CursorIsolation cursorIsolation, IsolationLevel isolation) { return SQLDeviceSession.IsolationLevelToSQLIsolationLevel(CursorIsolationToIsolationLevel(cursorIsolation, isolation)); } private SQLDeviceCursor GetMainCursor() { SelectExpression selectExpression = _statement.QueryExpression.SelectExpression; if (_hasDeferredData) { for (int index = 0; index < DataType.Columns.Count; index++) if (_sQLColumns[index].IsDeferred) { ColumnMap columnMap = new ColumnMap ( DataType.Columns[index], selectExpression.SelectClause.Columns[index], index ); selectExpression.SelectClause.Columns[index] = new ColumnExpression ( new CaseExpression ( new CaseItemExpression[] { new CaseItemExpression ( new UnaryExpression("iIsNull", columnMap.ColumnExpression.Expression), new ValueExpression(0) ) }, new CaseElseExpression(new ValueExpression(1)) ), columnMap.ColumnExpression.ColumnAlias ); _deferredColumns.Add(columnMap); } else _mainColumns.Add(new ColumnMap(DataType.Columns[index], selectExpression.SelectClause.Columns[index], index)); } SQLParameters parameters = new SQLParameters(); parameters.AddRange(_parameters); SQLParameters keyParameters = new SQLParameters(); int[] keyIndexes = new int[Node.Order == null ? 0 : Node.Order.Columns.Count]; SQLScalarType[] keyTypes = new SQLScalarType[keyIndexes.Length]; TableVarColumn keyColumn; for (int index = 0; index < keyIndexes.Length; index++) { keyColumn = Node.Order.Columns[index].Column; keyIndexes[index] = DataType.Columns.IndexOfName(keyColumn.Name); keyTypes[index] = (SQLScalarType)_sQLColumns[keyIndexes[index]].ScalarType; keyParameters.Add ( new SQLParameter ( selectExpression.SelectClause.Columns[keyIndexes[index]].ColumnAlias, keyTypes[index].GetSQLParameterType(keyColumn), null, SQLDirection.In, DeviceSession.Device.GetParameterMarker(keyTypes[index], keyColumn) ) ); } SelectStatement statement = new SelectStatement(); statement.Modifiers = _statement.Modifiers; statement.QueryExpression = new QueryExpression(); statement.QueryExpression.SelectExpression = new SelectExpression(); statement.QueryExpression.SelectExpression.SelectClause = _statement.QueryExpression.SelectExpression.SelectClause; statement.QueryExpression.SelectExpression.FromClause = _statement.QueryExpression.SelectExpression.FromClause; if (_statement.QueryExpression.SelectExpression.WhereClause != null) statement.QueryExpression.SelectExpression.WhereClause = new WhereClause(_statement.QueryExpression.SelectExpression.WhereClause.Expression); statement.QueryExpression.SelectExpression.GroupClause = _statement.QueryExpression.SelectExpression.GroupClause; statement.QueryExpression.SelectExpression.HavingClause = _statement.QueryExpression.SelectExpression.HavingClause; statement.OrderClause = _statement.OrderClause; return new SQLDeviceCursor ( _deviceSession, statement, _isAggregate, parameters, keyIndexes, keyTypes, keyParameters, CursorCapabilitiesToSQLLockType(Capabilities, CursorIsolationToIsolationLevel(Isolation, DeviceSession.ServerProcess.CurrentIsolationLevel())), CursorTypeToSQLCursorType(Node.RequestedCursorType), CursorIsolationToSQLIsolationLevel(Isolation, DeviceSession.ServerProcess.CurrentIsolationLevel()) ); } // Returns a SQLCommand for accessing the deferred read data for the given column index. // The deferred column is guaranteed to be the last column in the Cursor opened from the command. private void GetDeferredStatement(IRow key, int columnIndex, out string statement, out SQLParameters parameters) { parameters = new SQLParameters(); parameters.AddRange(_parameters); SelectStatement localStatement = new SelectStatement(); localStatement.Modifiers = _statement.Modifiers; localStatement.QueryExpression = new QueryExpression(); localStatement.QueryExpression.SelectExpression = new SelectExpression(); localStatement.QueryExpression.SelectExpression.SelectClause = new SelectClause(); Expression keyCondition = null; for (int index = 0; index < key.DataType.Columns.Count; index++) { ColumnMap columnMap = _mainColumns.ColumnMapByIndex(DataType.Columns.IndexOfName(key.DataType.Columns[index].Name)); SQLScalarType scalarType = (SQLScalarType)_sQLColumns[columnMap.Index].ScalarType; TableVarColumn tableVarColumn = Node.TableVar.Columns[key.DataType.Columns[index].Name]; localStatement.QueryExpression.SelectExpression.SelectClause.Columns.Add(columnMap.ColumnExpression); SQLParameter parameter = new SQLParameter ( columnMap.ColumnExpression.ColumnAlias, scalarType.GetSQLParameterType(tableVarColumn), key.HasValue(index) ? scalarType.ParameterFromScalar(Manager, key[index]) : null, SQLDirection.In, DeviceSession.Device.GetParameterMarker(scalarType, tableVarColumn), DeviceSession.Device.UseParametersForCursors ? null : scalarType.ToLiteral(Manager, key[index]) ); parameters.Add(parameter); Expression condition = new BinaryExpression ( columnMap.ColumnExpression.Expression, "iEqual", new QueryParameterExpression(parameter.Name) ); if (keyCondition != null) keyCondition = new BinaryExpression(keyCondition, "iAnd", condition); else keyCondition = condition; } localStatement.QueryExpression.SelectExpression.SelectClause.Columns.Add(_deferredColumns.ColumnMapByIndex(columnIndex).ColumnExpression); localStatement.QueryExpression.SelectExpression.FromClause = _statement.QueryExpression.SelectExpression.FromClause; if ((keyCondition != null) || (_statement.QueryExpression.SelectExpression.WhereClause != null)) { localStatement.QueryExpression.SelectExpression.WhereClause = new WhereClause(); if ((keyCondition != null) && (_statement.QueryExpression.SelectExpression.WhereClause != null)) localStatement.QueryExpression.SelectExpression.WhereClause.Expression = new BinaryExpression(_statement.QueryExpression.SelectExpression.WhereClause.Expression, "iAnd", keyCondition); else if (keyCondition != null) localStatement.QueryExpression.SelectExpression.WhereClause.Expression = keyCondition; else localStatement.QueryExpression.SelectExpression.WhereClause.Expression = _statement.QueryExpression.SelectExpression.WhereClause.Expression; } localStatement.QueryExpression.SelectExpression.GroupClause = _statement.QueryExpression.SelectExpression.GroupClause; localStatement.QueryExpression.SelectExpression.HavingClause = _statement.QueryExpression.SelectExpression.HavingClause; statement = _deviceSession.Device.Emitter.Emit(localStatement); } protected override void InternalOpen() { if (!_deviceSession.ServerProcess.IsOpeningInsertCursor) { _cursor = GetMainCursor(); _bOF = true; _eOF = !_cursor.Next(); } else { _bOF = true; _eOF = true; } } protected override void InternalClose() { if (_cursor != null) { _cursor.Dispose(); _cursor = null; } } protected void InternalSelect(IRow row, bool allowDeferred) { for (int index = 0; index < row.DataType.Columns.Count; index++) { int columnIndex = DataType.Columns.IndexOfName(row.DataType.Columns[index].Name); if (columnIndex >= 0) { if (_sQLColumns[columnIndex].IsDeferred) { if (!allowDeferred) throw new SQLException(SQLException.Codes.InvalidDeferredContext); if ((int)_cursor[columnIndex] == 0) row.ClearValue(index); else { // set up a deferred read stream using the device session as the provider StreamID streamID = Program.ServerProcess.Register(_deviceSession); string statement; SQLParameters parameters; GetDeferredStatement(InternalGetKey(), columnIndex, out statement, out parameters); _deviceSession.Create ( streamID, DataType.Columns[columnIndex].Name, _sQLColumns[columnIndex].ScalarType, statement, parameters, CursorTypeToSQLCursorType(Node.RequestedCursorType), CursorIsolationToSQLIsolationLevel(Isolation, DeviceSession.ServerProcess.CurrentIsolationLevel()) ); row[index] = streamID; } } else { if (_cursor.IsNull(columnIndex)) row.ClearValue(index); else row[index] = _sQLColumns[columnIndex].ScalarType.ToScalar(Manager, _cursor[columnIndex]); } } } } protected override void InternalSelect(IRow row) { InternalSelect(row, true); } protected override IRow InternalGetKey() { Row row = new Row(Manager, new RowType(Program.FindClusteringKey(Node.TableVar).Columns)); InternalSelect(row, false); return row; } protected override bool InternalNext() { if (_bOF) { _bOF = _eOF; } else { _eOF = !_cursor.Next(); _bOF = _bOF && _eOF; } return !_eOF; } protected override bool InternalBOF() { return _bOF; } protected override bool InternalEOF() { return _eOF; } } public static class SQLDeviceUtility { public static SQLDevice ResolveSQLDevice(Plan plan, string deviceName) { Device device = Compiler.ResolveCatalogIdentifier(plan, deviceName, true) as Schema.Device; if (device == null) throw new CompilerException(CompilerException.Codes.DeviceIdentifierExpected); SQLDevice sQLDevice = device as SQLDevice; if (sQLDevice == null) throw new SQLException(SQLException.Codes.SQLDeviceExpected); return sQLDevice; } public static ReconcileOptions ResolveReconcileOptions(ListValue list) { StringBuilder localList = new StringBuilder(); for (int index = 0; index < list.Count(); index++) { if (index > 0) localList.Append(", "); localList.Append((string)list[index]); } return (ReconcileOptions)Enum.Parse(typeof(ReconcileOptions), localList.ToString()); } } // operator D4ToSQL(AQuery : System.String) : System.String; // operator D4ToSQL(ADeviceName : System.Name, AQuery : System.String) : System.String; public class D4ToSQLNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { string statementString; Schema.Device device = null; SQLDevice sQLDevice = null; if (arguments.Length == 1) statementString = (string)arguments[0]; else { sQLDevice = SQLDeviceUtility.ResolveSQLDevice(program.Plan, (string)arguments[0]); device = sQLDevice; statementString = (string)arguments[1]; } string sQLQuery = String.Empty; Plan plan = new Plan(program.ServerProcess); try { ParserMessages parserMessages = new ParserMessages(); Statement statement = new D4.Parser().ParseStatement(statementString, parserMessages); plan.Messages.AddRange(parserMessages); PlanNode node = Compiler.Compile(plan, statement); if (plan.Messages.HasErrors) throw new ServerException(ServerException.Codes.UncompiledPlan, plan.Messages.ToString(CompilerErrorLevel.NonFatal)); if (node is FrameNode) node = node.Nodes[0]; if ((node is ExpressionStatementNode) || (node is CursorNode)) node = node.Nodes[0]; if (device == null) device = node.Device; if ((device != null) && node.DeviceSupported) { if (sQLDevice == null) sQLDevice = device as SQLDevice; if (sQLDevice == null) throw new SQLException(SQLException.Codes.QuerySupportedByNonSQLDevice, device.Name); if (node.Device == sQLDevice) sQLQuery = sQLDevice.Emitter.Emit(((SQLDevicePlanNode)node.DeviceNode).Statement); else throw new SQLException(SQLException.Codes.QuerySupportedByDifferentDevice, node.Device.Name, sQLDevice.Name); } else throw new SQLException(SQLException.Codes.QueryUnsupported); } finally { plan.Dispose(); } return sQLQuery; } } // operator SQLExecute(const AStatement : String); // operator SQLExecute(const AStatement : String, const AInValues : row); // operator SQLExecute(const AStatement : String, const AInValues : row, var AOutValues : row); // operator SQLExecute(const ADeviceName : Name, const AStatement : String); // operator SQLExecute(const ADeviceName : Name, const AStatement : String, const AInValues : row); // operator SQLExecute(const ADeviceName : Name, const AStatement : String, const AInValues : row, var AOutValues : row); public class SQLExecuteNode : InstructionNode { private static bool IsValidIdentifierCharacter(char charValue) { return (charValue == '_') || Char.IsLetterOrDigit(charValue); } private static bool HandleParameter(Plan plan, SQLDevice device, SQLParameters paramsValue, PlanNode[] conversionNodes, Schema.IRowType inRowType, Schema.IRowType outRowType, string parameterName) { int inIndex = inRowType != null ? inRowType.Columns.IndexOf(parameterName) : -1; int outIndex = outRowType != null ? outRowType.Columns.IndexOf(parameterName) : -1; if ((inIndex >= 0) || (outIndex >= 0)) { Schema.ScalarType valueType; if (outIndex >= 0) valueType = (Schema.ScalarType)outRowType.Columns[outIndex].DataType; else valueType = (Schema.ScalarType)inRowType.Columns[inIndex].DataType; if (inIndex >= 0) { //if (AInValues.HasValue(LInIndex)) // LValue = (IScalar)AInValues[LInIndex]; if (!inRowType.Columns[inIndex].DataType.Equals(valueType)) { ValueNode valueNode = new DAE.Runtime.Instructions.ValueNode(); //LValueNode.Value = LValue; valueNode.DataType = valueType; PlanNode sourceNode = valueNode; if (!inRowType.Columns[inIndex].DataType.Is(valueType)) { ConversionContext context = Compiler.FindConversionPath(plan, inRowType.Columns[inIndex].DataType, valueType); Compiler.CheckConversionContext(plan, context); sourceNode = Compiler.ConvertNode(plan, sourceNode, context); } sourceNode = Compiler.Upcast(plan, sourceNode, valueType); conversionNodes[inIndex] = sourceNode; //LValue = (IScalar)Compiler.Upcast(AProcess.Plan, LSourceNode, LValueType).Execute(AProcess).Value; } } SQLScalarType scalarType = device.ResolveDeviceScalarType(plan, valueType) as SQLScalarType; if (scalarType == null) throw new SchemaException(SchemaException.Codes.DeviceScalarTypeNotFound, valueType.Name); paramsValue.Add(new SQLParameter(parameterName, scalarType.GetSQLParameterType(), null, ((inIndex >= 0) && (outIndex >= 0)) ? SQLDirection.InOut : inIndex >= 0 ? SQLDirection.In : SQLDirection.Out, device.GetParameterMarker(scalarType))); return true; // return true if the parameter was handled } return false; // return false since the parameter was not handled } public static SQLParameters PrepareParameters(Plan plan, SQLDevice device, string statement, Schema.IRowType inRowType, Schema.IRowType outRowType, PlanNode[] conversionNodes) { SQLParameters parameters = new SQLParameters(); StringBuilder parameterName = null; bool inParameter = false; char quoteChar = '\0'; for (int index = 0; index < statement.Length; index++) { if (inParameter && !IsValidIdentifierCharacter(statement[index])) { if (HandleParameter(plan, device, parameters, conversionNodes, inRowType, outRowType, parameterName.ToString())) inParameter = false; } switch (statement[index]) { case '@' : if (quoteChar == '\0') // if not inside of a string { parameterName = new StringBuilder(); inParameter = true; } break; case '\'' : case '"' : if (quoteChar != '\0') { if (((index + 1) >= statement.Length) || (statement[index + 1] != quoteChar)) quoteChar = '\0'; } else quoteChar = statement[index]; break; default: if (inParameter) parameterName.Append(statement[index]); break; } } // handle the param if it's the last thing on the statement if (inParameter) HandleParameter(plan, device, parameters, conversionNodes, inRowType, outRowType, parameterName.ToString()); return parameters; } private static void SetValueNode(PlanNode planNode, IDataValue tempValue) { if (planNode is ValueNode) ((ValueNode)planNode).Value = tempValue.IsNil ? null : tempValue.AsNative; else SetValueNode(planNode.Nodes[0], tempValue); } public static void GetParameters(Program program, SQLDevice device, SQLParameters parameters, IRow inValues, PlanNode[] conversionNodes) { for (int index = 0; index < parameters.Count; index++) { switch (parameters[index].Direction) { case SQLDirection.InOut : case SQLDirection.In : int inIndex = inValues.DataType.Columns.IndexOf(parameters[index].Name); PlanNode conversionNode = conversionNodes[inIndex]; Schema.ScalarType valueType = (Schema.ScalarType)(conversionNode == null ? inValues.DataType.Columns[inIndex].DataType : conversionNode.DataType); SQLScalarType scalarType = device.ResolveDeviceScalarType(program.Plan, valueType) as SQLScalarType; if (scalarType == null) throw new SchemaException(SchemaException.Codes.DeviceScalarTypeNotFound, valueType.Name); if (inValues.HasValue(inIndex)) { if (conversionNode == null) parameters[index].Value = scalarType.ParameterFromScalar(program.ValueManager, inValues[inIndex]); else { SetValueNode(conversionNode, inValues.GetValue(inIndex)); parameters[index].Value = scalarType.ParameterFromScalar(program.ValueManager, conversionNode.Execute(program)); } } else parameters[index].Value = null; break; } } } public static void SetParameters(Program program, SQLDevice device, SQLParameters parameters, IRow outValues) { for (int index = 0; index < parameters.Count; index++) switch (parameters[index].Direction) { case SQLDirection.InOut : case SQLDirection.Out : int outIndex = outValues.DataType.Columns.IndexOf(parameters[index].Name); Schema.ScalarType valueType = (Schema.ScalarType)outValues.DataType.Columns[outIndex].DataType; SQLScalarType scalarType = device.ResolveDeviceScalarType(program.Plan, valueType) as SQLScalarType; if (scalarType == null) throw new SchemaException(SchemaException.Codes.DeviceScalarTypeNotFound, valueType.Name); if (parameters[index].Value != null) outValues[outIndex] = scalarType.ParameterToScalar(program.ValueManager, parameters[index].Value); else outValues.ClearValue(outIndex); break; } } public override object InternalExecute(Program program, object[] arguments) { long startTicks = TimingUtility.CurrentTicks; try { string deviceName = String.Empty; string statement = String.Empty; IRow inValues = null; IRow outValues = null; if (Operator.Operands[0].DataType.Is(Compiler.ResolveCatalogIdentifier(program.Plan, "System.Name") as IDataType)) { deviceName = (string)arguments[0]; statement = (string)arguments[1]; if (arguments.Length >= 3) inValues = (IRow)arguments[2]; if (arguments.Length == 4) outValues = (IRow)arguments[3]; } else { deviceName = program.Plan.DefaultDeviceName; statement = (string)arguments[0]; if (arguments.Length >= 2) inValues = (IRow)arguments[1]; if (arguments.Length == 3) outValues = (IRow)arguments[2]; } SQLDevice sQLDevice = SQLDeviceUtility.ResolveSQLDevice(program.Plan, deviceName); SQLDeviceSession deviceSession = program.DeviceConnect(sQLDevice) as SQLDeviceSession; PlanNode[] conversionNodes = inValues == null ? new PlanNode[0] : new PlanNode[inValues.DataType.Columns.Count]; SQLParameters parameters = PrepareParameters(program.Plan, sQLDevice, statement, inValues == null ? null : inValues.DataType, outValues == null ? null : outValues.DataType, conversionNodes); GetParameters(program, sQLDevice, parameters, inValues, conversionNodes); deviceSession.SQLExecute(statement, parameters); SetParameters(program, sQLDevice, parameters, outValues); return null; } finally { program.Statistics.DeviceExecuteTime += TimingUtility.TimeSpanFromTicks(startTicks); } } } // ADeviceName, AStatement, AKeyInfo, and ATableType must be literals (evaluable at compile-time) // operator SQLQuery(const AStatement : String) : table // operator SQLQuery(const AStatement : String, const AKeyInfo : String) : table // operator SQLQuery(const AStatement : String, const AInValues : row) : table // operator SQLQuery(const AStatement : String, const AInValues : row, const AKeyInfo : String) : table // operator SQLQuery(const AStatement : String, const AInValues : row, var AOutValues : row) : table // operator SQLQuery(const AStatement : String, const AInValues : row, var AOutValues : row, const AKeyInfo : String) : table // operator SQLQuery(const AStatement : String, const AInValues : row, var AOutValues : row, const ATableType : String, const AKeyInfo : String) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AKeyInfo : String) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AInValues : row) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AInValues : row, const AKeyInfo : String) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AInValues : row, var AOutValues : row) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AInValues : row, var AOutValues : row, const AKeyInfo : String) : table // operator SQLQuery(const ADeviceName : System.Name, const AStatement : System.String, const AInValues : row, var AOutValues : row, const ATableType : String, const AKeyInfo : String) : table public class SQLQueryNode : TableNode { public SQLQueryNode() { ShouldSupport = false; } public override void DetermineDataType(Plan plan) { DetermineModifiers(plan); // determine the table type from the CLI call string deviceName = String.Empty; _statement = String.Empty; Schema.RowType inRowType = null; Schema.RowType outRowType = null; string tableType = String.Empty; string keyDefinition = String.Empty; if (plan.IsEngine && (Modifiers != null)) { tableType = LanguageModifiers.GetModifier(Modifiers, "TableType", tableType); keyDefinition = LanguageModifiers.GetModifier(Modifiers, "KeyInfo", keyDefinition); } // ADeviceName and AStatement must be literal if (Nodes[0].DataType.Is(plan.DataTypes.SystemName)) { // NOTE: We are deliberately not using APlan.ExecuteLiteralArgument here because we want to throw the SQLException, not the CompilerException. if (!Nodes[0].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "ADeviceName"); deviceName = (string)plan.ExecuteNode(Nodes[0]); if (!Nodes[1].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AStatement"); _statement = (string)plan.ExecuteNode(Nodes[1]); if (Nodes.Count >= 3) { if (Nodes[2].DataType.Is(plan.DataTypes.SystemString)) { if (!Nodes[2].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[2]); } else inRowType = Nodes[2].DataType as Schema.RowType; } if (Nodes.Count >= 4) { if (Nodes[3].DataType.Is(plan.DataTypes.SystemString)) { if (!Nodes[3].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[3]); } else outRowType = Nodes[3].DataType as Schema.RowType; } if (Nodes.Count == 5) { if (!Nodes[4].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[4]); } else if (Nodes.Count == 6) { if (!Nodes[4].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "ATableType"); tableType = (string)plan.ExecuteNode(Nodes[4]); if (!Nodes[5].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[5]); } } else { deviceName = plan.DefaultDeviceName; if (!Nodes[0].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AStatement"); _statement = (string)plan.ExecuteNode(Nodes[0]); if (Nodes.Count >= 2) { if (Nodes[1].DataType.Is(plan.DataTypes.SystemString)) { if (!Nodes[1].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[1]); } else inRowType = Nodes[1].DataType as Schema.RowType; } if (Nodes.Count >= 3) { if (Nodes[2].DataType.Is(plan.DataTypes.SystemString)) { if (!Nodes[2].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[2]); } else outRowType = Nodes[2].DataType as Schema.RowType; } if (Nodes.Count == 4) { if (!Nodes[3].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[3]); } else if (Nodes.Count == 5) { if (!Nodes[3].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "ATableType"); tableType = (string)plan.ExecuteNode(Nodes[3]); if (!Nodes[4].IsLiteral) throw new SQLException(SQLException.Codes.ArgumentMustBeLiteral, "AKeyInfo"); keyDefinition = (string)plan.ExecuteNode(Nodes[4]); } } CursorCapabilities = plan.CursorContext.CursorCapabilities; CursorIsolation = plan.CursorContext.CursorIsolation; CursorType = plan.CursorContext.CursorType; SQLDeviceSession deviceSession = null; if (!plan.IsEngine) { _sQLDevice = SQLDeviceUtility.ResolveSQLDevice(plan, deviceName); deviceSession = plan.DeviceConnect(_sQLDevice) as SQLDeviceSession; _conversionNodes = inRowType == null ? new PlanNode[0] : new PlanNode[inRowType.Columns.Count]; _planParameters = SQLExecuteNode.PrepareParameters(plan, _sQLDevice, _statement, inRowType, outRowType, _conversionNodes); } if (tableType == String.Empty) { SQLCursor cursor = deviceSession.Connection.Open ( _statement, _planParameters, SQLTable.CursorTypeToSQLCursorType(CursorType), SQLIsolationLevel.ReadUncommitted, SQLCommandBehavior.SchemaOnly | (keyDefinition == String.Empty ? SQLCommandBehavior.KeyInfo : SQLCommandBehavior.Default) ); try { bool messageReported = false; SQLTableSchema schema = null; try { schema = cursor.Schema; } catch (Exception exception) { // An error here should be ignored, just get as much schema information as possible from the actual cursor... // Not as efficient, but the warning lets them know that. plan.Messages.Add(new CompilerException(CompilerException.Codes.CompilerMessage, CompilerErrorLevel.Warning, exception, "Compile-time schema retrieval failed, attempting run-time schema retrieval.")); messageReported = true; } if ((schema == null) || (schema.Columns.Count == 0)) { if (!messageReported) plan.Messages.Add(new CompilerException(CompilerException.Codes.CompilerMessage, CompilerErrorLevel.Warning, "Compile-time schema retrieval failed, attempting run-time schema retrieval.")); if (cursor != null) { cursor.Dispose(); cursor = null; } cursor = deviceSession.Connection.Open ( _statement, _planParameters, SQLTable.CursorTypeToSQLCursorType(CursorType), SQLIsolationLevel.ReadUncommitted, SQLCommandBehavior.Default ); schema = cursor.Schema; } _dataType = new Schema.TableType(); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; _sQLColumns = new SQLTableColumns(); foreach (SQLColumn sQLColumn in schema.Columns) { Schema.Column column = new Schema.Column(sQLColumn.Name, _sQLDevice.FindScalarType(plan, sQLColumn.Domain)); DataType.Columns.Add(column); _tableVar.Columns.Add(new Schema.TableVarColumn(column, Schema.TableVarColumnType.Stored)); } _sQLDevice.CheckSupported(plan, _tableVar); foreach (Schema.TableVarColumn tableVarColumn in _tableVar.Columns) _sQLColumns.Add(new SQLTableColumn(tableVarColumn, (Schema.DeviceScalarType)_sQLDevice.ResolveDeviceScalarType(plan, (Schema.ScalarType)tableVarColumn.Column.DataType))); if (keyDefinition == String.Empty) { foreach (SQLIndex sQLIndex in schema.Indexes) { if (sQLIndex.IsUnique) { Schema.Key key = new Schema.Key(); foreach (SQLIndexColumn sQLIndexColumn in sQLIndex.Columns) key.Columns.Add(_tableVar.Columns[sQLIndexColumn.Name]); _tableVar.Keys.Add(key); } } } else { _tableVar.Keys.Add(Compiler.CompileKeyDefinition(plan, _tableVar, new D4.Parser().ParseKeyDefinition(keyDefinition))); } } finally { cursor.Dispose(); } } else { _dataType = Compiler.CompileTypeSpecifier(plan, new D4.Parser().ParseTypeSpecifier(tableType)) as Schema.TableType; if (_dataType == null) throw new CompilerException(CompilerException.Codes.TableTypeExpected); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; _sQLColumns = new SQLTableColumns(); foreach (Schema.Column column in DataType.Columns) TableVar.Columns.Add(new Schema.TableVarColumn(column)); if (!plan.IsEngine) { _sQLDevice.CheckSupported(plan, _tableVar); foreach (Schema.TableVarColumn tableVarColumn in _tableVar.Columns) _sQLColumns.Add(new SQLTableColumn(tableVarColumn, (Schema.DeviceScalarType)_sQLDevice.ResolveDeviceScalarType(plan, (Schema.ScalarType)tableVarColumn.Column.DataType))); } _tableVar.Keys.Add(Compiler.CompileKeyDefinition(plan, _tableVar, new D4.Parser().ParseKeyDefinition(keyDefinition))); } Compiler.EnsureKey(plan, _tableVar); TableVar.DetermineRemotable(plan.CatalogDeviceSession); Order = Compiler.FindClusteringOrder(plan, TableVar); // Ensure the order exists in the orders list if (!TableVar.Orders.Contains(Order)) TableVar.Orders.Add(Order); if (!plan.IsEngine) { if (Modifiers == null) Modifiers = new LanguageModifiers(); D4.D4TextEmitter emitter = new D4.D4TextEmitter(); Modifiers.AddOrUpdate("TableType", emitter.Emit(_tableVar.DataType.EmitSpecifier(D4.EmitMode.ForCopy))); Modifiers.AddOrUpdate("KeyInfo", emitter.Emit(Compiler.FindClusteringKey(plan, _tableVar).EmitStatement(D4.EmitMode.ForCopy))); } } private SQLDevice _sQLDevice; private string _statement; private PlanNode[] _conversionNodes; private SQLParameters _planParameters; private SQLTableColumns _sQLColumns; public override object InternalExecute(Program program) { var parameters = new SQLParameters(); foreach (var parameter in _planParameters) { parameters.Add(new SQLParameter(parameter.Name, parameter.Type, parameter.Value, parameter.Direction, parameter.Marker, parameter.Literal)); } long startTicks = TimingUtility.CurrentTicks; try { IRow inValues = null; IRow outValues = null; if (Nodes[0].DataType.Is(Compiler.ResolveCatalogIdentifier(program.Plan, "System.Name", true) as IDataType)) { if ((Nodes.Count >= 3) && (Nodes[2].DataType is Schema.IRowType)) inValues = (IRow)Nodes[2].Execute(program); if ((Nodes.Count >= 4) && (Nodes[3].DataType is Schema.IRowType)) outValues = (IRow)Nodes[3].Execute(program); } else { if ((Nodes.Count >= 2) && (Nodes[1].DataType is Schema.IRowType)) inValues = (IRow)Nodes[1].Execute(program); if ((Nodes.Count == 3) && (Nodes[2].DataType is Schema.IRowType)) outValues = (IRow)Nodes[2].Execute(program); } SQLDeviceSession deviceSession = program.DeviceConnect(_sQLDevice) as SQLDeviceSession; SQLExecuteNode.GetParameters(program, _sQLDevice, parameters, inValues, _conversionNodes); LocalTable result = new LocalTable(this, program); try { result.Open(); // Populate the result Row row = new Row(program.ValueManager, result.DataType.RowType); try { row.ValuesOwned = false; using ( SQLCursor cursor = deviceSession.Connection.Open ( _statement, parameters, SQLTable.CursorTypeToSQLCursorType(CursorType), SQLTable.CursorIsolationToSQLIsolationLevel(CursorIsolation, program.ServerProcess.CurrentIsolationLevel()), SQLCommandBehavior.Default ) ) { SQLExecuteNode.SetParameters(program, _sQLDevice, parameters, outValues); while (cursor.Next()) { for (int index = 0; index < DataType.Columns.Count; index++) { if (cursor.IsNull(index)) row.ClearValue(index); else row[index] = _sQLColumns[index].ScalarType.ToScalar(program.ValueManager, cursor[index]); } result.Insert(row); } } } finally { row.Dispose(); } result.First(); return result; } catch { result.Dispose(); throw; } } finally { program.Statistics.DeviceExecuteTime += TimingUtility.TimeSpanFromTicks(startTicks); } } } // operator AvailableTables() : table { Name : Name, StorageName : String }; // operator AvailableTables(const ADeviceName : System.Name) : table { Name : Name, StorageName : String }; public class AvailableTablesNode : TableNode { public override void DetermineDataType(Plan plan) { DetermineModifiers(plan); _dataType = new Schema.TableType(); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; DataType.Columns.Add(new Schema.Column("Name", plan.DataTypes.SystemName)); DataType.Columns.Add(new Schema.Column("StorageName", plan.DataTypes.SystemString)); foreach (Schema.Column column in DataType.Columns) TableVar.Columns.Add(new Schema.TableVarColumn(column)); TableVar.Keys.Add(new Schema.Key(new Schema.TableVarColumn[]{TableVar.Columns["Name"]})); TableVar.DetermineRemotable(plan.CatalogDeviceSession); Order = Compiler.FindClusteringOrder(plan, TableVar); // Ensure the order exists in the orders list if (!TableVar.Orders.Contains(Order)) TableVar.Orders.Add(Order); } private void PopulateAvailableTables(Program program, SQLDevice device, Table table, Row row) { Schema.Catalog serverCatalog = device.GetServerCatalog(program.ServerProcess, null); Schema.Catalog catalog = new Schema.Catalog(); device.GetDeviceTables(program.Plan, serverCatalog, catalog, null); foreach (Schema.Object objectValue in catalog) { Schema.BaseTableVar tableVar = objectValue as Schema.BaseTableVar; if (tableVar != null) { row[0] = tableVar.Name; row[1] = tableVar.MetaData.Tags["Storage.Name"].Value; table.Insert(row); } } } public override object InternalExecute(Program program) { string deviceName = (Nodes.Count == 0) ? program.Plan.DefaultDeviceName : (string)Nodes[0].Execute(program); SQLDevice sQLDevice = SQLDeviceUtility.ResolveSQLDevice(program.Plan, deviceName); LocalTable result = new LocalTable(this, program); try { result.Open(); // Populate the result Row row = new Row(program.ValueManager, result.DataType.RowType); try { row.ValuesOwned = false; PopulateAvailableTables(program, sQLDevice, result, row); } finally { row.Dispose(); } result.First(); return result; } catch { result.Dispose(); throw; } } } // operator AvailableReferences() : table { Name : Name, StorageName : String }; // operator AvailableReferences(const ADeviceName : System.Name) : table { Name : Name, StorageName : String }; public class AvailableReferencesNode : TableNode { public override void DetermineDataType(Plan plan) { DetermineModifiers(plan); _dataType = new Schema.TableType(); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; DataType.Columns.Add(new Schema.Column("Name", plan.DataTypes.SystemName)); DataType.Columns.Add(new Schema.Column("StorageName", plan.DataTypes.SystemString)); foreach (Schema.Column column in DataType.Columns) TableVar.Columns.Add(new Schema.TableVarColumn(column)); TableVar.Keys.Add(new Schema.Key(new Schema.TableVarColumn[]{TableVar.Columns["Name"]})); TableVar.DetermineRemotable(plan.CatalogDeviceSession); Order = Compiler.FindClusteringOrder(plan, TableVar); // Ensure the order exists in the orders list if (!TableVar.Orders.Contains(Order)) TableVar.Orders.Add(Order); } private void PopulateAvailableReferences(Program program, SQLDevice device, Table table, Row row) { Schema.Catalog serverCatalog = device.GetServerCatalog(program.ServerProcess, null); Schema.Catalog catalog = new Schema.Catalog(); device.GetDeviceForeignKeys(program.Plan, serverCatalog, catalog, null); foreach (Schema.Object objectValue in catalog) { Schema.Reference reference = objectValue as Schema.Reference; if (reference != null) { row[0] = reference.Name; row[1] = reference.MetaData.Tags["Storage.Name"].Value; table.Insert(row); } } } public override object InternalExecute(Program program) { string deviceName = (Nodes.Count == 0) ? program.Plan.DefaultDeviceName : (string)Nodes[0].Execute(program); SQLDevice sQLDevice = SQLDeviceUtility.ResolveSQLDevice(program.Plan, deviceName); LocalTable result = new LocalTable(this, program); try { result.Open(); // Populate the result Row row = new Row(program.ValueManager, result.DataType.RowType); try { row.ValuesOwned = false; PopulateAvailableReferences(program, sQLDevice, result, row); } finally { row.Dispose(); } result.First(); return result; } catch { result.Dispose(); throw; } } } // operator DeviceReconciliationScript(const ADeviceName : Name) : String; // operator DeviceReconciliationScript(const ADeviceName : Name, const AOptions : list(String)) : String; // operator DeviceReconciliationScript(const ADeviceName : Name, const ATableName : Name, const AOptions : list(String)) : String; public class DeviceReconciliationScriptNode : InstructionNode { public override object InternalExecute(Program program, object[] arguments) { SQLDevice sQLDevice = SQLDeviceUtility.ResolveSQLDevice(program.Plan, (string)arguments[0]); string tableName = String.Empty; ReconcileOptions options = ReconcileOptions.All; switch (arguments.Length) { case 2 : if (Operator.Operands[1].DataType.Is(program.DataTypes.SystemName)) tableName = (string)arguments[1]; else options = SQLDeviceUtility.ResolveReconcileOptions(arguments[1] as ListValue); break; case 3 : tableName = (string)arguments[1]; options = SQLDeviceUtility.ResolveReconcileOptions(arguments[2] as ListValue); break; } Batch batch; if (tableName == String.Empty) batch = sQLDevice.DeviceReconciliationScript(program.ServerProcess, options); else batch = sQLDevice.DeviceReconciliationScript(program.ServerProcess, Compiler.ResolveCatalogIdentifier(program.Plan, tableName, true) as Schema.TableVar, options); return sQLDevice.Emitter.Emit(batch); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RWCustom; using System.IO; using System.Text.RegularExpressions; using Rainbow.CreatureOverhaul; namespace Rainbow.WorldOverhaul { public static class RegionStatePatch { public static void SubPatch() { //On.RegionState.AdaptWorldToRegionState += new On.RegionState.hook_AdaptWorldToRegionState(AdaptWorldToRegionStatePatch); //On.RegionState.AdaptRegionStateToWorld += new On.RegionState.hook_AdaptRegionStateToWorld(AdaptRegionStateToWorldPatch); } public static List<string> savedPopulation; /// <summary> /// Load RegionState /// </summary> public static void AdaptWorldToRegionStatePatch(On.RegionState.orig_AdaptWorldToRegionState orig, RegionState self) { // = new string[self.saveState.progression.regionNames.Length]; orig.Invoke(self); //RegionStatePatch.regionLoadStrings[self.world.region.regionNumber] } /// <summary> /// Load Regional Data /// </summary> public static void LoadRainbowRegion(string str) { if (string.IsNullOrEmpty(str)) { return; } string[] array = Regex.Split(str, "<rgA>"); List<string[]> list = new List<string[]>(); for (int i = 0; i < array.Length; i++) { string[] array2 = Regex.Split(array[i], "<rgB>"); if (array2.Length >= 2) { list.Add(array2); } } RegionStatePatch.savedPopulation = new List<string>(); for (int j = 0; j < list.Count; j++) { switch (list[j][0]) { case "POPULATION": array = Regex.Split(list[j][1], "<rgC>"); for (int n = 0; n < array.Length; n++) { if (!string.IsNullOrEmpty(array[n])) { RegionStatePatch.savedPopulation.Add(array[n]); } } break; //add more types to be saved if needed } } } public static void AdaptRegionStateToWorldPatch(On.RegionState.orig_AdaptRegionStateToWorld orig, RegionState self, int playerShelter, int activeGate) { if (self.saveState != null) { string text = SaveRainbowRegion(self); using (StreamWriter streamWriter = File.CreateText(PlayerProgressionPatch.SaveFilePath(self.world.game.rainWorld.options.saveSlot))) { streamWriter.Write(Custom.Md5Sum(text) + text); } } orig.Invoke(self, playerShelter, activeGate); } public static string SaveRainbowRegion(RegionState state) { string str = string.Concat("REGIONNAME<rgB>", state.regionName, "<rgA>LASTCYCLEUPDATED<rgB>", state.lastCycleUpdated, "<rgA>"); RegionStatePatch.savedPopulation = new List<string>(); foreach (AbstractCreature c in state.loadedCreatures) { //RegionStatePatch.savedPopulation.Add(RainbowWorld.GetState(c).ToString()); } if (RegionStatePatch.savedPopulation.Count > 0) { str += "POPULATION<rgB>"; for (int l = 0; l < RegionStatePatch.savedPopulation.Count; l++) { str = str + RegionStatePatch.savedPopulation[l] + "<rgC>"; } str += "<rgA>"; } return str; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; namespace BRI { partial class AboutBox1 : Form { public AboutBox1() { InitializeComponent(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://nguyentrieuphong.com"); } private void label2_Click(object sender, EventArgs e) { this.Close(); } private void AboutBox1_Load(object sender, EventArgs e) {} } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace ConsoleApp4 { class Program { static void Main(string[] args) { var obj = new MyClass(); var lobj = new List<MyClass>() { obj, obj, obj, obj, obj }; Test(lobj, obj, suf: "List"); var qobj = new Queue<MyClass>(lobj); Test(qobj, obj, suf: "Queue"); var cqobj = new ConcurrentQueue<MyClass>(lobj); Test(cqobj, obj, suf: "ConcurrentQueue"); Console.ReadLine(); } static void Test(IEnumerable<MyClass> lobj, MyClass obj, int iter = 10_000, string suf = "") { var comparer = new MyClassComparer(); //cache for (int i = 0; i < 10_000; i++) { lobj.Contains(obj); lobj.Contains(obj, comparer); } List<TimeSpan> results = new List<TimeSpan>(); Stopwatch sw = new Stopwatch(); for (int q = 0; q < 60; q++) { for (int i = 0; i < iter; i++) { sw.Start(); lobj.Contains(obj); sw.Stop(); } results.Add(sw.Elapsed); sw.Reset(); } Console.WriteLine($"default {suf} {results.Average(x=>x.TotalMilliseconds)}"); results.Clear(); for (int q = 0; q < 60; q++) { for (int i = 0; i < iter; i++) { sw.Start(); lobj.Contains(obj, comparer); sw.Stop(); } results.Add(sw.Elapsed); sw.Reset(); } Console.WriteLine($"custom {suf} {results.Average(x => x.TotalMilliseconds)}"); } } public class MyClass { public int id { get; set; } public int id2 { get; set; } } public class MyClassComparer : IEqualityComparer<MyClass> { public bool Equals(MyClass x, MyClass y) { return x.Equals(y); } public int GetHashCode([DisallowNull] MyClass obj) { return obj.GetHashCode(); } } }
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 Labor { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } float arg01, arg02, arg03, arg04, arg5; double RES; string Out = ""; private void Form1_MouseMove(object sender, MouseEventArgs e) { Text = string.Format("Координаты: {0}, {1}", e.X, e.Y); textBox1.Text = (e.X + e.Y).ToString(); arg01 = e.X; arg02 = e.Y; textBox2.Text = arg01.ToString(); textBox3.Text = arg02.ToString(); textBox6.Text = CalculateAnswer(); } private string CalculateAnswer() { try { arg03 = Convert.ToSingle(textBox4.Text); arg04 = Convert.ToSingle(textBox5.Text); arg5 = Convert.ToSingle(textBox7.Text); RES = (arg01 - arg02 + Math.Abs(Math.Sin(arg03) + Math.Sqrt(Math.Abs(arg04)))) / (Math.Pow(arg01, arg5) - Math.Log10(arg02)); return RES.ToString(); } catch { return "ERROR"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; namespace ManageWeb.Areas.Api.Controllers { public class ConfigController : ApiBaseController { [ClientAuth(ClientAuthType.TryAuth)] public ActionResult Ping() { if (ServerId > 0) { var serverbll = new ManageDomain.BLL.ServerMachineBll(); var model = serverbll.PingTask(ServerId); return JsonE(model); } return Json(new { code = -1001, msg = "Ping成功,但未绑定!", data = new { MaxCmdID = 0 } }); } [ClientAuth(ClientAuthType.Auth)] public ActionResult uploaddata(string uploadtype, string data) { uploadtype = (uploadtype ?? "").ToLower(); switch (uploadtype) { case "watchdata": new ManageDomain.BLL.ServerWatchBll().SaveWatchData(this.ServerId, data); break; case "tasksummary": new ManageDomain.BLL.TaskBll().SaveTaskSummary(this.ServerId, data); break; default: break; } return JsonE(1); } [ClientAuth(ClientAuthType.Auth)] public ActionResult GetConfig() { var bll = new ManageDomain.BLL.ServerMachineBll(); var configs = bll.GetServerUnionConfig(ServerId); return JsonE(configs); } public ActionResult DownloadFile(string filename) { filename = filename.Replace("\\", "/").Replace("..", "").Replace("~", "").TrimStart('/'); string file = Server.MapPath("~/" + filename); return File(file, "application/octet-stream"); } [ClientAuth(ClientAuthType.Auth)] public ActionResult PostData(int typecode, string data) { return JsonE("接收到了数据!" + data); } } }
using EduHome.DataContext; using EduHome.Models.Entity; using EduHome.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.Areas.Admin.Controllers { [Area("admin")] public class SubscriberController : Controller { public EduhomeDbContext _context { get; } public SubscriberController(EduhomeDbContext context) { _context = context; } public IActionResult Index() { List<Subscriber> subscribers = _context.Subscribers.ToList(); return View(subscribers); } public IActionResult MakeDeleteOrActive(int? id) { if (id == null) { return NotFound(); } Subscriber subscriber = _context.Subscribers.ToList().FirstOrDefault(pm => pm.Id == id); if (subscriber == null) { return BadRequest(); } if (subscriber.IsDeleted == true) subscriber.IsDeleted = false; else subscriber.IsDeleted = true; _context.Subscribers.Update(subscriber); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using Microsoft.Win32; using System.Data.SqlClient; using System.Runtime.InteropServices; using System.Diagnostics; using Microsoft.VisualBasic.Devices; using System.Collections.Specialized; using Gma.QrCodeNet.Encoding; using Gma.QrCodeNet.Encoding.Windows; using Gma.QrCodeNet.Encoding.Windows.Render; // 添加额外的命名空间 using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace JsonTools { public partial class Form1 : Form { [DllImport("user32.dll", EntryPoint = "FindWindow")] private extern static IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", EntryPoint = "FindWindowEx")] private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); [DllImport("user32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(IntPtr hwnd, int wMsg, uint wParam, int lParam); [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalAddAtom(String lpString); //添加原子 [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalFindAtom(String lpString); //查找原子 [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom); //删除原子 [DllImport("user32.dll", SetLastError = true)] static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); string nowRP02 = ""; int tmpLen = 0; int index = 0; int tP05_RB2 = 0; int tP05_RB4 = 0; TreeNodeEx CurrentNode = null; public delegate void ClickEventHandler(object sender, TreeNodeMouseClickEventArgs e); static Computer myComputer = new Computer(); public static string Mydocument = myComputer.FileSystem.SpecialDirectories.MyDocuments; public static string JsonDir = Mydocument + @"\JsonTools\"; public static string PGNamePath = Mydocument + @"\JsonTools\PGName.ini"; enum ary { N0100=2,N0101=10,N01011=26 }; //由左至右計算 2的N次方從0開始 N0100 = 0*1+1*2+0*4+0*8=2 List<TextBox> tP03_tbList = new List<TextBox>(); List<DataGridView> tP03_dgvList = new List<DataGridView>(); List<TextBox> tP04_tbList = new List<TextBox>(); List<DataGridView> tP04_dgvList = new List<DataGridView>(); //20140218 // 服务器端口 int port; // 监听端口 int tcpPort; // 定义变量 private UdpClient receiveUdpClient; private IPEndPoint serverIPEndPoint; private IPAddress serverIp; private TreeNodeEx FoundNode = null; public static Dictionary<string, string> jsonKeyValues = new Dictionary<string, string>(); int MsgCount = 0; int MsgDone = 0; //20140218 //20140225 public static JObject Pool = new JObject(); int count = 0; int Mmax = 0; private TcpListener tcpListener; private Thread listenThread; MemoryStream Fstream = null; private static string JsonTreeStr = ""; private static bool IsCanUpdate = false; private static bool IsLogToTxt = false; private static int LogLines = 1; //20140225 public Form1() { InitializeComponent(); } public static bool isDirectory(string p)//目錄是否存在 { if (p == "") { return false; } return System.IO.Directory.Exists(p); } TreeNodeEx MyNode = new TreeNodeEx(); string ss = ""; //20140325 int DGV03_SelectIndex = -1; private void Form1_Load(object sender, EventArgs e) { //f2.Show(); GoRead(); lbl_Msg.Text = ""; this.Text = "JSonTools Ver " + GetVersion() + " @ ErricGuo "; if (tb_TXT.Text != "") { if (!File.Exists(tb_TXT.Text)) { MessageBox.Show("檔案不存在!!", "錯誤"); return; } GoRegisty("Path",tb_TXT.Text); btn_Load.PerformClick(); } cboChanged(cbo_Name); cboChanged(cbo_Value); cboChanged(cbo_Path); cboChanged(chk_CheckNow); if (cbo_Big5.SelectedIndex == -1) { cbo_Big5.SelectedIndex = 0; } if (cbo_Sym.SelectedIndex == -1) { cbo_Sym.SelectedIndex = 3; } cboSelectChanged(cbo_Big5); cboSelectChanged(cbo_Sym); tP06_Lb01.Text = ""; if (tP06_tbPath.Text != "") { GoRegisty("tP06_tbPath", tP06_tbPath.Text); } //TP07 LoadPGSections(); ThreadPool.SetMaxThreads(2, 2); timer_AutoUpdate.Interval = Int32.Parse(tb_Seconds.Text) *1000; timer_AutoUpdate.Enabled = true; tcpListener = new TcpListener(IPAddress.Any, 4097); listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.Start(); } public static string GetVersion() { string s = ""; try { s += System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(); } catch (Exception) { s = "開發程式階段"; } return s; } string nodeName = string.Empty; private bool GetJsonTree(string xStr, TreeNodeEx xNode, int xType) { Hashtable ht = new Hashtable(); Hashtable ht2 = new Hashtable(); ArrayList al = new ArrayList(); ArrayList al2 = new ArrayList(); SortedDictionary<string, string> sdc = null; JArray ja = new JArray(); string tmp2 = ""; if (xType == 1) { /*if (xStr.StartsWith("[") && xStr.EndsWith("]")) { tmp2 = "[" + xStr + "]"; } else*/ { tmp2 = xStr; } try { ja = JArray.Parse(tmp2); } catch { } TreeNodeEx Nodeay = null; for (int i = 0; i < ja.Count();i++ ) { sdc = new SortedDictionary<string, string>(); ht = JavaScriptConvert.DeserializeObject(ja[i].ToString(), typeof(Hashtable)) as Hashtable; foreach (DictionaryEntry de in ht) { //al.Add(de.Key.ToString()); //al2.Add(de.Value.ToString()); sdc.Add(de.Key.ToString(), de.Value.ToString()); } ht.Clear(); Nodeay = new TreeNodeEx(); Nodeay.Text = "["+i.ToString()+"]"; //節點文字 Nodeay.value = i.ToString(); //節點文字 Nodeay.Tag = ""; //Nodeay.path = "";// xNode.path + ",'" + xNode.nodename + "'"; //Nodeay.path = xNode.path + ",'" + xNode.nodename + "'"; Nodeay.path = xNode.path ; //Nodeay.nodename = xNode.nodename+Nodeay.Text; Nodeay.Name = Nodeay.Text; Nodeay.nodename = Nodeay.Text; SetNodeSelectPath(Nodeay); Nodeay.Tsdc = sdc; Nodeay.index = index++; xNode.Nodes.Add(Nodeay); //if (ht != null) if (sdc != null) { //foreach (DictionaryEntry de in ht) foreach (KeyValuePair<string, string> de in sdc) { TreeNodeEx Node = new TreeNodeEx(); Node.Text = de.Key.ToString(); //節點文字 Node.value = de.Key.ToString(); //節點文字 //Node.path = xNode.path + ",'" + xNode.nodename + "'"; //Node.path = xNode.path + ",'" + Nodeay.nodename + "'"; Node.path = Nodeay.path; //Node.nodename = xNode.nodename + Nodeay.nodename; Node.Name = Node.Text; Node.nodename = Node.Text; SetNodeSelectPath(Node); string tmp = de.Value.ToString().Trim(); if (tmp.EndsWith("}") && tmp.StartsWith("{")) { Node.index = index++; Nodeay.Nodes.Add(Node); Node.Tag = ""; GetJsonTree(de.Value.ToString(), Node, 0); } else if (tmp.EndsWith("]") && tmp.StartsWith("[")) { string tmps = tmp.Substring(1, tmp.Length - 1).Trim(); Node.index = index++; Nodeay.Nodes.Add(Node); Node.Tag = ""; char[] ch = new char[2]; ch[0] = '['; ch[1] = ']'; if (tmps.StartsWith("{")) { GetJsonTree(de.Value.ToString().Trim(), Node, 1); } } else { Node.Text += " : \"" + de.Value.ToString() + "\""; Node.value = de.Value.ToString(); Node.Tag = de.Value.ToString(); Node.index = index++; Node.ImageIndex = 2; Node.SelectedImageIndex = 2; Nodeay.Nodes.Add(Node); } } } Nodeay = null; } return true; } else { try { xStr = xStr.Replace("\\\"\"","\\\"");//20141227 add by erric sdc = new SortedDictionary<string, string>(); //ht = JavaScriptConvert.DeserializeObject(xStr, typeof(Hashtable)) as Hashtable; ht = JavaScriptConvert.DeserializeObject<Hashtable>(xStr); foreach (DictionaryEntry de in ht) { //al.Add(de.Key.ToString()); //al2.Add(de.Value.ToString()); sdc.Add(de.Key.ToString(), de.Value.ToString()); } ht.Clear(); } catch (System.Exception ex) { MessageBox.Show("不符合的資料型態!!","錯誤"); treeView1.Nodes.Clear(); return false; } /* foreach (KeyValuePair<string, string> k in sdc) { ht.Add(k.Key,k.Value); }*/ // Dictionary<string, string> dc = JavaScriptConvert.DeserializeObject(xStr, typeof(Dictionary<string, string>)) as Dictionary<string, string>; } if (ht != null) { xNode.Tsdc = sdc; //foreach (DictionaryEntry de in ht) foreach (KeyValuePair<string, string> de in sdc) { TreeNodeEx Node = new TreeNodeEx(); Node.Text = de.Key.ToString(); //節點文字 Node.value = de.Key.ToString(); //節點文字 Node.Name = de.Key.ToString(); //節點文字 Node.nodename = de.Key.ToString(); //節點文字 if (xNode.nodename == "ROOT") Node.path = ""; //Node.path = xNode.path + ",'" + xNode.nodename + "'"; else //Node.path = xNode.path + ",'" + xNode.nodename + "'"; Node.path = xNode.path ; //Node.path = "'" + xNode.nodename + "'"; SetNodeSelectPath(Node); string tmp = de.Value.ToString().Trim(); if (tmp.EndsWith("}") && tmp.StartsWith("{")) { Node.index = index++; xNode.Nodes.Add(Node); Node.Tag = ""; GetJsonTree(de.Value.ToString(), Node,0); } else if (tmp.EndsWith("]") && tmp.StartsWith("[")) { string tmps = tmp.Substring(1, tmp.Length - 1).Trim(); if (tmps.StartsWith("{")) { Node.index = index++; xNode.Nodes.Add(Node); Node.Tag = ""; char[] ch = new char[2]; ch[0] = '['; ch[1] = ']'; GetJsonTree(de.Value.ToString().Trim(), Node, 1); } else { Node.index = index++; Node.Text += " : \"" + de.Value.ToString() + "\""; Node.value = de.Value.ToString(); Node.Tag = de.Value.ToString(); Node.ImageIndex = 2; Node.SelectedImageIndex = 2; xNode.Nodes.Add(Node); } } else { Node.index = index++; Node.Text += " : \"" + de.Value.ToString() + "\""; Node.value = de.Value.ToString(); Node.Tag = de.Value.ToString(); Node.ImageIndex = 2; Node.SelectedImageIndex = 2; xNode.Nodes.Add(Node); } } } return true; } private void SetNodeSelectPath(TreeNodeEx a) { string tmp = a.path; if (tmp.EndsWith(",")) { tmp = tmp.Substring(0, tmp.Length - 1); } if (tmp.StartsWith(",")) { tmp = tmp.Substring(1, tmp.Length - 1); } a.path = tmp + "," + a.nodename;// +"'"; if (a.path.StartsWith(",")) { a.path = a.path.Substring(1, a.path.Length - 1); } } private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { TreeNodeEx a = (TreeNodeEx)e.Node; treeView1.SelectedNode = a; tb_VALUE.Text = a.Tag.ToString(); tb_NAME.Text = a.nodename; //tb_SEARCH.Text = a.index.ToString(); ss = ""; //string tmp = GetTreeList(a); /*string tmp = a.path; if (tmp.EndsWith(",")) { tmp = tmp.Substring(0, tmp.Length - 1); } if (tmp.StartsWith(",")) { tmp = tmp.Substring(1, tmp.Length-1); } tb_PATH.Text = tmp + ",'"+a.nodename+"'"; if (tb_PATH.Text.StartsWith(",")) { tb_PATH.Text = tb_PATH.Text.Substring(1, tb_PATH.Text.Length - 1); }*/ tb_PATH.Text = a.path; int count = 0; dataGridView1.Rows.Clear(); if (a.Tsdc != null) { foreach (KeyValuePair<string, string> de in a.Tsdc) { /* if (count == 0) dataGridView1.Rows[0].SetValues(de.Key.ToString(), de.Value.ToString()); else*/ dataGridView1.Rows.Add(de.Key.ToString(), de.Value.ToString()); count = 1; } dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } CurrentNode = a; } private string GetTreeList(TreeNodeEx xnode) { if (xnode.Parent == null) { if (ss=="") { return xnode.Text; } return ss; } else { if (xnode.Parent.Text != "ROOT") { ss = "'" + xnode.Parent.Text + "'," + ss; } return GetTreeList((TreeNodeEx)xnode.Parent); } } //private TreeNodeEx FindNode(TreeNodeEx tnParent, string strValue) private TreeNodeEx FindNode(TreeNodeEx tnParent, int index) { if (tnParent == null) return null; //if (tnParent.nodename.ToUpper() == strValue) return tnParent; if (tnParent.index == index) return tnParent; else if (tnParent.Nodes.Count == 0) return null; TreeNodeEx tnCurrent, tnCurrentPar; //Init node tnCurrentPar = tnParent; tnCurrent = (TreeNodeEx)tnCurrentPar.FirstNode; while (tnCurrent != null && tnCurrent != tnParent) { while (tnCurrent != null) { if (tnCurrent.index == index) return tnCurrent; else if (tnCurrent.Nodes.Count > 0) { //Go into the deepest node in current sub-path tnCurrentPar = tnCurrent; tnCurrent = (TreeNodeEx)tnCurrent.FirstNode; } else if (tnCurrent != tnCurrentPar.LastNode) { //Goto next sible node tnCurrent = (TreeNodeEx)tnCurrent.NextNode; } else break; } //Go back to parent node till its has next sible node while (tnCurrent != tnParent && tnCurrent == tnCurrentPar.LastNode) { tnCurrent = tnCurrentPar; tnCurrentPar = (TreeNodeEx)tnCurrentPar.Parent; } //Goto next sible node if (tnCurrent != tnParent) tnCurrent = (TreeNodeEx)tnCurrent.NextNode; } return null; } private void FindNodes(TreeNodeEx xnode, string strValue) { bool[] b = new bool[] { cbo_Name.Checked, cbo_Value.Checked, cbo_Path.Checked }; for(int i=0;i<xnode.Nodes.Count;i++) { TreeNodeEx a = (TreeNodeEx)xnode.Nodes[i]; string[] t = new string[] { a.nodename.ToUpper(), a.Tag.ToString().ToUpper(), a.path.ToString().ToUpper() }; for (int j = 0; j < b.Length; j++) { if (b[j]) { if (System.Text.RegularExpressions.Regex.IsMatch(t[j], CheckChars(strValue.ToUpper()), System.Text.RegularExpressions.RegexOptions.IgnoreCase)) //if (System.Text.RegularExpressions.Regex.IsMatch(t[j], strValue.ToUpper())) { string tmp = a.path; if (tmp.StartsWith(",")) { tmp = tmp.Substring(1, tmp.Length - 1); } dataGridView2.Rows.Add(a.index, a.nodename, a.Tag.ToString(), tmp); int idx = dataGridView2.RowCount - 1; if (idx % 2 == 0) { dataGridView2.Rows[idx].DefaultCellStyle.BackColor = Color.FromName("InactiveBorder"); } else { dataGridView2.Rows[idx].DefaultCellStyle.BackColor = Color.FromName("Info"); } } } } FindNodes((TreeNodeEx)xnode.Nodes[i], strValue); } } private void FindNodes2(TreeNodeEx xnode, string path,string rvalue) { for (int i = 0; i < xnode.Nodes.Count; i++) { TreeNodeEx a = (TreeNodeEx)xnode.Nodes[i]; if (System.Text.RegularExpressions.Regex.IsMatch(a.path.ToString().ToUpper(), CheckChars(path.ToUpper()), System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { string tmp = a.path; if (tmp.StartsWith(",")) { tmp = tmp.Substring(1, tmp.Length - 1); } a.value = rvalue; a.Tag = rvalue; a.Text = a.nodename + ":" + "\"" + rvalue + "\""; FoundNode = a; return; } FindNodes2((TreeNodeEx)xnode.Nodes[i], path, rvalue); } } TreeNodeEx b = null; private TreeNodeEx FindNodeWithIndex(TreeNodeEx xnode, string path,out int input) { input = 0; TreeNodeEx a = null; for (int i = 0; i < xnode.Nodes.Count; i++) { a = (TreeNodeEx)xnode.Nodes[i]; if (System.Text.RegularExpressions.Regex.IsMatch(a.path.ToUpper(),CheckChars(path.ToUpper()), System.Text.RegularExpressions.RegexOptions.IgnoreCase)) //if (System.Text.RegularExpressions.Regex.IsMatch(a.path.ToUpper(), path.ToUpper())) { input = 1; return a; } else { b = FindNodeWithIndex(a, path,out input); } if (b!=null && input ==1) { return b; } } return null; } private void btn_Copy_Click(object sender, EventArgs e) { if (tb_PATH.Text=="") { return; } Clipboard.SetData(DataFormats.Text, tb_PATH.Text); } private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) { return; } string tmp_path = ""; if ((sender as DataGridView).RowCount > 0) { int index = Int32.Parse(dataGridView2.Rows[e.RowIndex].Cells[0].Value.ToString()); tb_NAME.Text = dataGridView2.Rows[e.RowIndex].Cells[1].Value.ToString(); tb_VALUE.Text = dataGridView2.Rows[e.RowIndex].Cells[2].Value.ToString(); /* tmp_path = dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString(); tb_PATH.Text = tmp_path + ",'" + tb_NAME.Text + "'"; if (tb_PATH.Text.StartsWith(",")) { tb_PATH.Text = tb_PATH.Text.Substring(1, tb_PATH.Text.Length - 1); }*/ tb_PATH.Text = dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString(); TreeNodeEx tnRet = null; foreach (TreeNodeEx tn in treeView1.Nodes) { if (tn.Text.StartsWith("[")) { continue; } tnRet = FindNode(tn, index); if (tnRet != null) break; } if (tnRet != null) { treeView1.SelectedNode = tnRet; treeView1.SelectedNode.Expand(); treeView1.SelectedNode = tnRet; treeView1.Focus(); tnRet.EnsureVisible(); } } //dataGridView2.Focus(); } private void treeView1_AfterExpand(object sender, TreeViewEventArgs e) { TreeNodeEx a = (TreeNodeEx)e.Node; treeView1.SelectedNode = a; if (a.Nodes.Count == 0) { return; } a.ImageIndex = 1; a.SelectedImageIndex = 1; } private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e) { TreeNodeEx a = (TreeNodeEx)e.Node; treeView1.SelectedNode = a; if (a.Nodes.Count == 0) { return; } a.ImageIndex = 0; a.SelectedImageIndex = 0; } private void GoRegisty(string key,string value) { //打開 子機碼 路徑。 RegistryKey Reg = Registry.LocalMachine.OpenSubKey("Software", true); ////檢查子機碼是否存在,檢查資料夾是否存在。 if (Reg.GetSubKeyNames().Contains("JSonTools") == false) { //建立子機碼,建立資料夾。 Reg.CreateSubKey("JSonTools"); //寫入資料 Name,Value,"寫入類型" Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", key, value, RegistryValueKind.String); } else { //寫入資料 Name,Value,"寫入類型" Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", key, value, RegistryValueKind.String); //關閉 子機碼 路徑 Reg.Close(); } } private void GoRead() { //開啟指定的機碼目錄。 RegistryKey oRegistryKey = Registry.LocalMachine.OpenSubKey("Software\\JSonTools"); if (oRegistryKey != null) { //若目錄存在,則取出 key=cnstr 的值。 if (oRegistryKey.GetValue("Path", "").ToString() != "") { tb_TXT.Text = oRegistryKey.GetValue("Path").ToString(); } if (oRegistryKey.GetValue("cbo_Name", "ERROR").ToString() == "Y") { cbo_Name.Checked = true; } else if (oRegistryKey.GetValue("cbo_Name", "ERROR").ToString() == "N") { cbo_Name.Checked = false; } else { Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", "cbo_Name", "Y", RegistryValueKind.String); } if (oRegistryKey.GetValue("cbo_Value", "ERROR").ToString() == "Y") { cbo_Value.Checked = true; } else if (oRegistryKey.GetValue("cbo_Value", "ERROR").ToString() == "N") { cbo_Value.Checked = false; } else { Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", "cbo_Value", "Y", RegistryValueKind.String); } if (oRegistryKey.GetValue("cbo_Path", "ERROR").ToString() == "Y") { cbo_Path.Checked = true; } else if (oRegistryKey.GetValue("cbo_Path", "ERROR").ToString() == "N") { cbo_Path.Checked = false; } else { Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", "cbo_Path", "Y", RegistryValueKind.String); } if (oRegistryKey.GetValue("chk_CheckNow", "ERROR").ToString() == "Y") { chk_CheckNow.Checked = true; } else if (oRegistryKey.GetValue("chk_CheckNow", "ERROR").ToString() == "N") { chk_CheckNow.Checked = false; } else { Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\JSonTools", "chk_CheckNow", "Y", RegistryValueKind.String); } if (oRegistryKey.GetValue("cbo_Big5", "").ToString() != "") { cbo_Big5.SelectedIndex = Int32.Parse(oRegistryKey.GetValue("cbo_Big5").ToString()); } if (oRegistryKey.GetValue("cbo_Sym", "").ToString() != "") { cbo_Sym.SelectedIndex = Int32.Parse(oRegistryKey.GetValue("cbo_Sym").ToString()); } //TP03 { if (oRegistryKey.GetValue("tP03_tb01", "").ToString() != "") { tP03_tb01.Text = oRegistryKey.GetValue("tP03_tb01").ToString(); } if (oRegistryKey.GetValue("tP03_tb02", "").ToString() != "") { tP03_tb02.Text = oRegistryKey.GetValue("tP03_tb02").ToString(); } if (oRegistryKey.GetValue("tP03_tb03", "").ToString() != "") { tP03_tb03.Text = oRegistryKey.GetValue("tP03_tb03").ToString(); } if (oRegistryKey.GetValue("tP03_tb04", "").ToString() != "") { tP03_tb04.Text = oRegistryKey.GetValue("tP03_tb04").ToString(); } if (oRegistryKey.GetValue("tP03_tb05", "").ToString() != "") { tP03_tb05.Text = oRegistryKey.GetValue("tP03_tb05").ToString(); } if (oRegistryKey.GetValue("tP03_tb06", "").ToString() != "") { tP03_tb06.Text = oRegistryKey.GetValue("tP03_tb06").ToString(); } } //TP04 { if (oRegistryKey.GetValue("tP04_tb07", "").ToString() != "") { tP03_tb01.Text = oRegistryKey.GetValue("tP04_tb07").ToString(); } if (oRegistryKey.GetValue("tP04_tb08", "").ToString() != "") { tP03_tb02.Text = oRegistryKey.GetValue("tP04_tb08").ToString(); } if (oRegistryKey.GetValue("tP04_tb09", "").ToString() != "") { tP03_tb03.Text = oRegistryKey.GetValue("tP04_tb09").ToString(); } if (oRegistryKey.GetValue("tP04_tb10", "").ToString() != "") { tP03_tb04.Text = oRegistryKey.GetValue("tP04_tb10").ToString(); } if (oRegistryKey.GetValue("tP04_tb11", "").ToString() != "") { tP03_tb05.Text = oRegistryKey.GetValue("tP04_tb11").ToString(); } if (oRegistryKey.GetValue("tP04_tb12", "").ToString() != "") { tP03_tb06.Text = oRegistryKey.GetValue("tP04_tb12").ToString(); } } //TP01_DGV { if (oRegistryKey.GetValue("tP01_dgv", "").ToString() != "") { string[] tmp = Split(",", oRegistryKey.GetValue("tP01_dgv").ToString()); for (int i = 0; i < tmp.Length;i++ ) { tP01_dgv.Rows.Add("",tmp[i]); } } } //TP06 if (oRegistryKey.GetValue("tP06_tbPath", "").ToString() != "") { tP06_tbPath.Text = oRegistryKey.GetValue("tP06_tbPath").ToString(); } } } private void 版更說明ToolStripMenuItem_Click(object sender, EventArgs e) { Form7 f7 = new Form7(); f7.ShowDialog(); } private void btn_Load_Click(object sender, EventArgs e) { string mName = (sender as Button).Name; FileStream myFile = null; StreamReader rd = null; string output = ""; treeView1.Nodes.Clear(); MyNode.Nodes.Clear(); if (mName == "btn_Load") { if (tb_TXT.Text == "") { MessageBox.Show("請選擇檔案!!", "提示"); return; } if (!File.Exists(tb_TXT.Text)) { MessageBox.Show("檔案不存在!!", "錯誤"); return; } myFile = File.Open(tb_TXT.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); rd = new StreamReader(myFile, System.Text.Encoding.GetEncoding("Big5")); output = rd.ReadToEnd(); output = output.Replace("\\", "\\\\"); rd.Dispose(); myFile.Dispose(); } else if (mName == "btn_UpdatePool") { if (Pool==null) { return; } byte[] byteArray = Encoding.Unicode.GetBytes(Pool.ToString()); MemoryStream stream = new MemoryStream( byteArray ); // convert stream to string rd = new StreamReader(stream, Encoding.Unicode); output = rd.ReadToEnd(); output = output.Replace("\\", "\\\\"); rd.Dispose(); } else if (mName == "btn_LoadPool") { if (tb_TXT.Text == "") { MessageBox.Show("請選擇檔案!!", "提示"); return; } if (!File.Exists(tb_TXT.Text)) { MessageBox.Show("檔案不存在!!", "錯誤"); return; } myFile = File.Open(tb_TXT.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); rd = new StreamReader(myFile, System.Text.Encoding.GetEncoding("Big5")); output = rd.ReadToEnd(); output = output.Replace("\\", "\\\\"); rd.Dispose(); myFile.Dispose(); Pool = JObject.Parse(output); } MyNode.Text = "ROOT"; //節點文字 MyNode.nodename = "ROOT"; MyNode.path = ""; MyNode.Tag = "5"; MyNode.index = index++; treeView1.Nodes.Add(MyNode); if (!GetJsonTree(output, MyNode, 0)) { return; } treeView1.Nodes[0].Expand(); richTextBox1.SelectionStart = richTextBox1.TextLength; richTextBox1.ScrollToCaret(); // treeView1.TreeViewNodeSorter = new NodeSorter(); } private void btn_SelectFile_Click(object sender, EventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.ShowDialog(); tb_TXT.Text = file.FileName; if (!File.Exists(tb_TXT.Text)) { MessageBox.Show("檔案不存在!!", "錯誤"); return; } GoRegisty("Path", tb_TXT.Text); btn_Load.PerformClick(); } private void btn_Select_Click(object sender, EventArgs e) { //if (cbo_Name.Checked && cbo_Value.Checked && cbo_Path.Checked && tb_SEARCH.Text=="") if ( tb_SEARCH.Text=="") { if (MessageBox.Show("搜尋空字串將花費較久的時間,是否確定進行?", "提示", MessageBoxButtons.YesNo) == DialogResult.No) return; } DateTime dtone = DateTime.Now; dataGridView2.Rows.Clear(); FindNodes(MyNode, tb_SEARCH.Text.ToUpper()); DateTime dtwo = DateTime.Now; TimeSpan span = dtwo.Subtract(dtone); //算法是dtone 减去 dtwo string seconds = string.Format((((int)span.TotalMilliseconds) / 1000.0).ToString(), "0.000") + "秒"; dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; if (dataGridView2.RowCount <= 0) { lbl_Msg.Text = "無符合資料!! 費時:" + seconds; lbl_Msg.ForeColor = Color.Red; } else { lbl_Msg.Text = "符合資料: " + dataGridView2.RowCount.ToString() + "筆 費時:" + seconds; lbl_Msg.ForeColor = Color.Green; } } private void cbo_CheckedChanged(object sender, EventArgs e) { cboChanged((sender as CheckBox)); } private void cboChanged(CheckBox cbo) { string s = ""; string key = cbo.Name; if (cbo.Checked) { s = "Y"; } else { s = "N"; } GoRegisty(key, s); } private void cbo_Big5_SelectedIndexChanged(object sender, EventArgs e) { cboSelectChanged(sender as ComboBox); } private void cboSelectChanged(ComboBox cbo) { string s = cbo.SelectedIndex.ToString(); string key = cbo.Name; GoRegisty(key, s); } private void tb_SEARCH_TextChanged(object sender, EventArgs e) { if (CheckChineseString(tb_SEARCH.Text) < Int32.Parse(cbo_Big5.Text) && (tb_SEARCH.Text.Length < Int32.Parse(cbo_Sym.Text))) { return; } if (!chk_CheckNow.Checked || tb_SEARCH.Text == "" ) { return; } if (tb_SEARCH.Text.Length >= Int32.Parse(cbo_Sym.Text) || CheckChineseString(tb_SEARCH.Text) >= Int32.Parse(cbo_Big5.Text)) { btn_Select.PerformClick(); } } private int CheckChineseString(string strInputString) { int intCode = 0; int count = 0; // int intIndexNumber=0; for (int i = 0; i < strInputString.Length;i++) { //中文範圍(0x4e00 - 0x9fff)轉換成int(intChineseFrom - intChineseEnd) int intChineseFrom = Convert.ToInt32("4e00", 16); int intChineseEnd = Convert.ToInt32("9fff", 16); if (strInputString != "") { //取得input字串中指定判斷的index字元的unicode碼 intCode = Char.ConvertToUtf32(strInputString, i); if (intCode >= intChineseFrom && intCode <= intChineseEnd) { count++; //return true; //如果是範圍內的數值就回傳true } else { //return false; //如果是範圍外的數值就回傳true } } } return count; } private void btn_AddNewPage_Click(object sender, EventArgs e) { tabControl1.TabPages.Add("123"); } private void treeView1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right ) { contextMenuStrip1.Show(MousePosition); } } private void toolStripMenuItem1_Click(object sender, EventArgs e) { btn_Lock.PerformClick(); bool Isadd = false; string s = ""; string key = ""; if (CurrentNode.Nodes.Count == 0) { //tP01_dgv.Rows.Add(CurrentNode.index, CurrentNode.nodename, CurrentNode.Tag.ToString(), CurrentNode.path); tP01_dgv.Rows.Add(CurrentNode.index, CurrentNode.nodename, CurrentNode.Tag.ToString(), tb_PATH.Text); tP01_dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; for (int i = 0; i < tP01_dgv.RowCount;i++ ) { s += tP01_dgv.Rows[i].Cells[1].Value.ToString() + ","; } if (s.EndsWith(",")) { s = s.Substring(0, s.Length - 1); } //GoRegisty(tP01_dgv.Name, s); showinfo(CurrentNode.nodename + "已加入頁籤:變數1"); } else { for(int i=0;i<6;i++) { if (tP03_tbList[i].Text == "") { Isadd = true; tP03_tbList[i].Text = CurrentNode.path; s = CurrentNode.path; key = tP03_tbList[i].Name; //tP03_tbList[i].Tag = CurrentNode.nodename; showinfo(CurrentNode.nodename + "已加入頁籤:變數群組1"); if (CurrentNode.Tsdc != null) { foreach (KeyValuePair<string, string> de in CurrentNode.Tsdc) { tP03_dgvList[i].Rows.Add(de.Key.ToString(), de.Value.ToString()); } tP03_dgvList[i].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } break; } } if (!Isadd) { for (int i = 0; i < 6; i++) { if (tP04_tbList[i].Text == "") { Isadd = true; tP04_tbList[i].Text = CurrentNode.path; s = CurrentNode.path; key = tP03_tbList[i].Name; showinfo(CurrentNode.nodename + "已加入頁籤:變數群組2"); //tP03_tbList[i].Tag = CurrentNode.nodename; if (CurrentNode.Tsdc != null) { foreach (KeyValuePair<string, string> de in CurrentNode.Tsdc) { tP04_dgvList[i].Rows.Add(de.Key.ToString(), de.Value.ToString()); } tP04_dgvList[i].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } break; } } } if (!Isadd) { MessageBox.Show("監看的變數群組已達上限,請先刪除後再加入!", "錯誤"); } else { //GoRegisty(key, s); } } } private void InitPages() { //TP03 { tP03_cboDel.SelectedIndex = 6; tP03_tbList.Add(tP03_tb01); tP03_tbList.Add(tP03_tb02); tP03_tbList.Add(tP03_tb03); tP03_tbList.Add(tP03_tb04); tP03_tbList.Add(tP03_tb05); tP03_tbList.Add(tP03_tb06); tP03_dgvList.Add(tP03_dgv01); tP03_dgvList.Add(tP03_dgv02); tP03_dgvList.Add(tP03_dgv03); tP03_dgvList.Add(tP03_dgv04); tP03_dgvList.Add(tP03_dgv05); tP03_dgvList.Add(tP03_dgv06); } //TP04 { tP04_cboDel.SelectedIndex = 6; tP04_tbList.Add(tP04_tb07); tP04_tbList.Add(tP04_tb08); tP04_tbList.Add(tP04_tb09); tP04_tbList.Add(tP04_tb10); tP04_tbList.Add(tP04_tb11); tP04_tbList.Add(tP04_tb12); tP04_dgvList.Add(tP04_dgv07); tP04_dgvList.Add(tP04_dgv08); tP04_dgvList.Add(tP04_dgv09); tP04_dgvList.Add(tP04_dgv10); tP04_dgvList.Add(tP04_dgv11); tP04_dgvList.Add(tP04_dgv12); } } private void tP03_btnReFresh_Click(object sender, EventArgs e) { if (tP03_tbList.Count <= 0) return; int input = 0; for (int i = 0; i < 6; i++) { if (tP03_tbList[i].Text == "") { continue; } else { TreeNodeEx a = FindNodeWithIndex(MyNode, tP03_tbList[i].Text,out input); if (a != null) { if (a.Tsdc != null) { tP03_dgvList[i].Rows.Clear(); foreach (KeyValuePair<string, string> de in a.Tsdc) { tP03_dgvList[i].Rows.Add(de.Key.ToString(), de.Value.ToString()); } tP03_dgvList[i].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } } } } } private void tP04_btnReFresh_Click(object sender, EventArgs e) { int input = 0; for (int i = 0; i < 6; i++) { if (tP04_tbList[i].Text == "") { continue; } else { TreeNodeEx a = FindNodeWithIndex(MyNode, tP04_tbList[i].Text, out input); if (a != null) { if (a.Tsdc != null) { tP04_dgvList[i].Rows.Clear(); foreach (KeyValuePair<string, string> de in a.Tsdc) { tP04_dgvList[i].Rows.Add(de.Key.ToString(), de.Value.ToString()); } tP04_dgvList[i].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } } } } } private void tP01_btnReFresh_Click(object sender, EventArgs e) { int input = 0; for (int i = 0; i < tP01_dgv.RowCount; i++) { if (tP01_dgv.Rows[i].Cells[3].Value==null) { continue; } TreeNodeEx a = FindNodeWithIndex(MyNode, tP01_dgv.Rows[i].Cells[3].Value.ToString(), out input); if (a != null) { tP01_dgv.Rows[i].SetValues(a.index,a.nodename,a.Tag.ToString(),a.path); tP01_dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } } } private void Form1_Activated(object sender, EventArgs e) { InitPages(); } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { if ( tabControl1.SelectedIndex == 2) { if (treeView1.Nodes.Count != 0) { tP01_btnReFresh.PerformClick(); } } if (tabControl1.SelectedIndex == 3) { if (treeView1.Nodes.Count != 0) { tP03_btnReFresh.PerformClick(); } } if (tabControl1.SelectedIndex == 4) { if (treeView1.Nodes.Count != 0) { tP04_btnReFresh.PerformClick(); } } } private string CheckChars(string a) { List<int> tmplist = new List<int>(); string tmp = a; for (int i = 0; i < a.Length;i++ ) { if (a[i]=='[') { tmplist.Add(i); } if (a[i] == ']') { tmplist.Add(i); } } for (int i = tmplist.Count-1; i >= 0; i--) { tmp = tmp.Insert(tmplist[i], "\\"); } return tmp; } private void tP03_btn0X_Click(object sender, EventArgs e) { if ((sender as Button).Text == "") { foreach (TextBox tb in tP03_tbList) { tb.Text = ""; tb.Tag = ""; GoRegisty(tb.Name, ""); } foreach (DataGridView d in tP03_dgvList) { d.Rows.Clear(); d.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } } else { int idx = Int32.Parse((sender as Button).Text) - 1; if (tP03_tbList[idx].Text != "") { tP03_tbList[idx].Text = ""; tP03_tbList[idx].Tag = ""; tP03_dgvList[idx].Rows.Clear(); tP03_dgvList[idx].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; GoRegisty(tP03_tbList[idx].Name, ""); } } } private void tP04_btn0X_Click(object sender, EventArgs e) { if (tP04_cboDel.Text == "ALL") { foreach (TextBox tb in tP04_tbList) { tb.Text = ""; tb.Tag = ""; GoRegisty(tb.Name, ""); } foreach (DataGridView d in tP04_dgvList) { d.Rows.Clear(); d.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } } else { int idx = Int32.Parse((sender as Button).Text) - 7; if (tP04_tbList[idx].Text != "") { tP04_tbList[idx].Text = ""; tP04_tbList[idx].Tag = ""; tP04_dgvList[idx].Rows.Clear(); tP04_dgvList[idx].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; GoRegisty(tP04_tbList[idx].Name, ""); } } } int idx_tP01_dgv = -1; string tP01_CellValue = ""; private void tP01_btn0X_Click(object sender, EventArgs e) { if (tP01_dgv.RowCount <=0) { return; } tP01_dgv.Rows.Clear(); GoRegisty(tP01_dgv.Name, ""); } private void tP01_dgv_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) { return; } idx_tP01_dgv = e.RowIndex; tP01_CellValue = tP01_dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); } private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e) { if (idx_tP01_dgv != -1) { tP01_dgv.Rows.RemoveAt(idx_tP01_dgv); } string s = ""; for (int i = 0; i < tP01_dgv.RowCount; i++) { s += tP01_dgv.Rows[i].Cells[1].Value.ToString() + ","; } if (s.EndsWith(",")) { s = s.Substring(0, s.Length - 1); } GoRegisty(tP01_dgv.Name, s); } private void tP01_dgv_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right && idx_tP01_dgv != -1) { contextMenuStrip2.Show(MousePosition); } } private void 複製ToolStripMenuItem_Click(object sender, EventArgs e) { if (idx_tP01_dgv != -1) { Clipboard.SetData(DataFormats.Text, tP01_CellValue); } } public static string[] Split(string separator, string Text) { string[] sp = new string[] { separator }; return Text.Split(sp, StringSplitOptions.RemoveEmptyEntries); } [DllImport("user32.dll", EntryPoint = "LockWindowUpdate")] public static extern int LockWindowUpdate(int hwndLock); private void showinfo(string s) { try { LockWindowUpdate(this.Handle.ToInt32()); //Form2 f2 = new Form2(); //f2.SetText(s,this.Size,this.Location); //f2.Show(); /* f2.Left = this.Left + this.Width / 2 - f2.width / 2; f2.Top = this.Top + this.Height / 2 - f2.height / 2;*/ //this.Focus(); } finally { LockWindowUpdate(0); } } private void tP05_tbInput_TextChanged(object sender, EventArgs e) { if (tP05_tbInput01.TextLength <= 4) return; tP05_Btn01.PerformClick(); } private void tP05_RB_S_CheckedChanged(object sender, EventArgs e) { if (tP05_RB2 == 0) { string Result = tP05_Result01.Text; if (Result == "") return; string tmp = (sender as RadioButton).Tag.ToString(); nowRP02 = tmp; string Retmp = Result.Substring(8, Result.Length - 8); Retmp = tmp + Retmp; tP05_Result01.Text = Retmp; } if (tP05_Result01.Text == "") { return; } Clipboard.SetData(DataFormats.Text, tP05_Result01.Text); } private void tP05_Btn01_Click(object sender, EventArgs e) { tP05_Result01.Text = GetValue(); if (tP05_Result01.Text == "") { return; } Clipboard.SetData(DataFormats.Text, tP05_Result01.Text); } ArrayList strlist = new ArrayList(); ArrayList intlist = new ArrayList(); private string GetValue() { strlist.Clear(); intlist.Clear(); if (tP05_tbInput01.Text == "") return ""; string Result = ""; bool isusearray = false; if (tP05_RB2 == 0 || tP05_RB2 == 1) { string tmp_s = tP05_tbInput01.Text; if (tmp_s.ToUpper().StartsWith("PUB")) { tmp_s = tmp_s.Substring(4, tmp_s.Length - 4); tP05_RB3_2.Checked = true; } string[] tmp = Split(".", tmp_s); char[] c = null; string subname = ""; if (tmp[0].ToUpper() == "GPARAM") { tP05_RB3_1.Checked = true; for (int k = 1; k < tmp.Length;k++ ) { c = tmp[k].ToCharArray(); if (k == 1) { for (int i = 0; i < c.Length; i++) { if (c[i] == '_') { if (tmp[1].ToUpper().EndsWith("_A") || tmp[1].ToUpper().EndsWith("_B") || tmp[1].ToUpper().EndsWith("_C") || tmp[1].ToUpper().EndsWith("_D") || tmp[1].ToUpper().EndsWith("_E") || tmp[1].ToUpper().EndsWith("_F")) { subname = ""; } break; } subname += c[i]; } if (subname != "") { strlist.Add("'" + subname + "'"); intlist.Add(0); strlist.Add("'" + tmp[k] + "'"); intlist.Add(0); } else { strlist.Add("'" + tmp[k] + "'"); intlist.Add(0); } } else { string s = ""; c = tmp[k].ToCharArray(); if (!Chkarray(c, out s)) { s = "'" + tmp[k] + "'"; } string[] m = Split(",", s); foreach (string l in m) { strlist.Add(l); } } } } else //矩陣 gPayType[mPayTypeIdx].Invoiced { for (int k = 0; k < tmp.Length; k++) { if (k==0) { string tmp0 = tmp[k].ToUpper(); if (tmp0.EndsWith("INFO") || tmp0 == "FUSER" || tmp0 == "GCREDITCARD" || tmp0 == "GCURRFUNC" || tmp0 == "GPAYTYPE" ||tmp0 == "PAYMENT" ) { tP05_RB3_5.Checked = true; } else if (tmp0.StartsWith("GCURRPOSTB") || tmp0.StartsWith("GPAYMENT") || tmp0 == "GPOSTA" || tmp0.StartsWith("GPOSTB") || tmp0.StartsWith("GPOSTC") ) { tP05_RB3_3.Checked = true; } } string s = ""; c = tmp[k].ToCharArray(); if (!Chkarray(c, out s)) { s = "'" + tmp[k] + "'"; } string[] m = Split(",", s); foreach (string l in m) { strlist.Add(l); } } } if (tP05_RB2 == 0) { if (intlist.Count == 4) { //if ((int)(intlist[1]) != 1 || (int)(intlist[3]) != 1) if (!ChkIntArray(intlist)) { isusearray = true; for (int q = 0; q < intlist.Count; q++) { if ((int)intlist[q] == 1) { strlist[q] = "IntToStr(" + strlist[q] + ")"; } } } } else if (intlist.Count == 5) { //if ((int)(intlist[1]) != 1 || (int)(intlist[3]) != 1 || (int)(intlist[4]) != 1) if (!ChkIntArray(intlist)) { isusearray = true; for (int q = 0; q < intlist.Count; q++) { if ((int)intlist[q] == 1) { strlist[q] = "IntToStr(" + strlist[q] + ")"; } } } } else if (intlist.Count > 5) { isusearray = true; for (int q = 0; q < intlist.Count; q++) { if ((int)intlist[q] == 1) { strlist[q] = "IntToStr(" + strlist[q] + ")"; } } } } string ss = "["; string ss2 = "]"; if (!isusearray) { ss = ""; ss2 = ""; } string dpnNode = ""; if (tP05_RB3_1.Checked) { dpnNode = tP05_RB3_1.Text + ","; tmpLen = tP05_RB3_1.Text.Length; } else if (tP05_RB3_2.Checked) { dpnNode = tP05_RB3_2.Text + ","; tmpLen = tP05_RB3_2.Text.Length; } else if (tP05_RB3_3.Checked) { dpnNode = tP05_RB3_3.Text + ","; tmpLen = tP05_RB3_3.Text.Length; } else if (tP05_RB3_4.Checked) { dpnNode = tP05_RB3_4.Text + ","; tmpLen = tP05_RB3_4.Text.Length; } else if (tP05_RB3_5.Checked) { dpnNode = tP05_RB3_5.Text + ","; tmpLen = tP05_RB3_5.Text.Length; } else { dpnNode = tP05_RB3_1.Text + ","; tmpLen = tP05_RB3_1.Text.Length; } if (tP05_RB2 == 0) { if (tP05_RB_S.Checked) { Result = "GetPub_S(" + dpnNode + ss; nowRP02 = "GetPub_S"; } else if (tP05_RB_I.Checked) { Result = "GetPub_I(" + dpnNode + ss; nowRP02 = "GetPub_I"; } else if (tP05_RB_E.Checked) { Result = "GetPub_E(" + dpnNode + ss; nowRP02 = "GetPub_E"; } else if (tP05_RB_B.Checked) { Result = "GetPub_B(" + dpnNode + ss; nowRP02 = "GetPub_B"; } else if (tP05_RB_D.Checked) { Result = "GetPub_D(" + dpnNode + ss; nowRP02 = "GetPub_D"; } else { Result = "GetPub_S(" + dpnNode + ss; nowRP02 = "GetPub_S"; } } else if (tP05_RB2 == 1) { Result = "SetPubValue("+ dpnNode +"["; for (int q = 0; q < intlist.Count; q++) { if ((int)intlist[q] == 1) { strlist[q] = "IntToStr(" + strlist[q] + ")"; } } } for (int j = 0; j < strlist.Count; j++) { { if (j != strlist.Count - 1) Result += strlist[j] + ","; else { if (tP05_RB2 == 0) { Result += strlist[j] + ss2 + ")"; } else if (tP05_RB2 == 1) { Result += strlist[j] + "],)"; } } } } } return Result; } private void tP05_tbInput_MouseDoubleClick(object sender, MouseEventArgs e) { tP05_tbInput01.SelectAll(); } private void tb_SEARCH_MouseDoubleClick(object sender, MouseEventArgs e) { tb_SEARCH.SelectAll(); } private void tP05_Btn02_Click(object sender, EventArgs e) { tP05_tbInput01.Text = ""; tP05_Result01.Text = ""; tP05_tbMEMO.Text = ""; tP05_RB_S.Checked = true; tP05_RB2_GP.Checked = true; tP05_RB2 = 0; } private void tP05_RB2_GP_CheckedChanged(object sender, EventArgs e) { tP05_RB2 = Int32.Parse((sender as RadioButton).Tag.ToString()); tP05_Btn01.PerformClick(); } private void tP05_RB4_GF_CheckedChanged(object sender, EventArgs e) { tP05_RB4 = Int32.Parse((sender as RadioButton).Tag.ToString()); } private void tP05_Btn04_Click(object sender, EventArgs e) { tP05_tbInput02.Text = ""; tP05_Result02.Text = ""; tP05_RB3_1.Checked = true; tP05_RB4_GF.Checked = true; tP05_RB4 = 0; } private void tP05_tbInput02_MouseDoubleClick(object sender, MouseEventArgs e) { tP05_tbInput02.SelectAll(); } private void tP05_tbInput02_TextChanged(object sender, EventArgs e) { tP05_Btn03.PerformClick(); } private void tP05_Btn03_Click(object sender, EventArgs e) { tP05_Result02.Text = GetValue2((sender as RadioButton).Tag.ToString()); if (tP05_Result02.Text == "") { return; } Clipboard.SetData(DataFormats.Text, tP05_Result02.Text); } private string GetValue2(string tagstring) { if (tP05_tbInput02.Text == "") return ""; string Result = tagstring; if (tP05_RB4 == 0 ) { string tmp_s = tP05_tbInput02.Text; } else { } return Result; } private bool Chkarray(char[] c,out string s) { int vars = 0; ArrayList arr = new ArrayList(); string arrayname = ""; string subname2 = ""; string tmp = ""; for (int i = 0; i < c.Length; i++) { if (c[i] == '[') { vars=1; continue; } if (vars == 1) { if (c[i] != ']') arrayname += c[i]; else { arr.Add(arrayname); arrayname = ""; vars = 2; } } if (vars == 0) { subname2 += c[i]; } } if (arr.Count > 0) { tmp = "'" + subname2 + "'"; intlist.Add(0); for (int i = 0; i < arr.Count;i++ ) { tmp += "," + arr[i].ToString(); intlist.Add(1); } s = tmp; return true; } else { tmp = "'" + subname2 + "'"; intlist.Add(0); s = tmp; return false; } } public bool ChkIntArray(ArrayList al) { double sum = 0; double value = 0; double basevalue = 2.0; double power = 0.0; for (int i = 0; i < al.Count;i++ ) { power = i; value = Math.Pow(basevalue, power); sum += (int)al[i] * value; } sum = (int)sum; if (sum == (int)ary.N0100 || sum == (int)ary.N0101 || sum == (int)ary.N01011 ) { return true; } else { return false; } } private void tP06_Path_Click(object sender, EventArgs e) { string path =""; if (tP06_tbPath.Text != "") { folderBrowserDialog1.SelectedPath = tP06_tbPath.Text; } if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { path = folderBrowserDialog1.SelectedPath; } tP06_tbPath.Text = path; GoRegisty("tP06_tbPath", tP06_tbPath.Text); } private void tP06_BtnCRO_Click(object sender, EventArgs e) { GoRegisty("tP06_tbPath", tP06_tbPath.Text); if (tP06_tbPath.Text == "") { return; } if (isDirectory(tP06_tbPath.Text)) { string p = ""; if (!tP06_tbPath.Text.EndsWith("\\")) { p = tP06_tbPath.Text+"\\"; //p = tP06_tbPath.Text.Substring(0, tP06_tbPath.Text.Length - 1); } p = @""+p+"*.*"+@""; Execute("echo y| attrib " + p +" /S /D -R",0); tP06_Lb01.Text = "資料屬性變更完成!"; tP06_timer1.Enabled = true; } else { tP06_Lb01.Text = "無此目錄!!"; tP06_timer1.Enabled = true; //MessageBox.Show("無此目錄!!", "錯誤"); } } public static string Execute(string command, int seconds) { string output = ""; //输出字符串 if (command != null && !command.Equals("")) { Process process = new Process();//创建进程对象 ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe";//设定需要执行的命令 startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出 startInfo.UseShellExecute = false;//不使用系统外壳程序启动 startInfo.RedirectStandardInput = false;//不重定向输入 startInfo.RedirectStandardOutput = true; //重定向输出 startInfo.CreateNoWindow = true;//不创建窗口 process.StartInfo = startInfo; try { if (process.Start())//开始进程 { if (seconds == 0) { process.WaitForExit();//这里无限等待进程结束 } else { process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒 } output = process.StandardOutput.ReadToEnd();//读取进程的输出 } } catch { } finally { if (process != null) process.Close(); } } return output; } private void tP06_timer1_Tick(object sender, EventArgs e) { tP06_Lb01.Text = ""; tP06_timer1.Enabled = false; } private void tP05_RB3_1_CheckedChanged(object sender, EventArgs e) { if (tP05_RB2 == 0) { string Result = tP05_Result01.Text; if (Result == "") return; //int tmpLen = (sender as RadioButton).Text.Length; string tmp = (sender as RadioButton).Text; string Retmp = nowRP02+"("+tmp+ Result.Substring(9+tmpLen, Result.Length - (9+tmpLen)); //Retmp = tmp + Retmp; tP05_Result01.Text = Retmp; } tmpLen = (sender as RadioButton).Text.Length; Clipboard.SetData(DataFormats.Text, tP05_Result01.Text); } // Create a node sorter that implements the IComparer interface. public class NodeSorter : IComparer { // Compare the length of the strings, or the strings // themselves, if they are the same length. public int Compare(object x, object y) { TreeNode tx = x as TreeNode; TreeNode ty = y as TreeNode; // Compare the length of the strings, returning the difference. if (tx.Text.Length != ty.Text.Length) return tx.Text.Length - ty.Text.Length; // If they are the same length, call Compare. return string.Compare(tx.Text, ty.Text); } } public void LoadPGSections() { LoadPGNameInfo(); } List<string> tp07_lb01_List = new List<string>(); NameValueCollection keylist34 = new NameValueCollection(); NameValueCollection keylistGP2 = new NameValueCollection(); public bool LoadPGNameInfo() { string filename = PGNamePath; SetupIni ini = new SetupIni(); ini.SetFileName(filename); if (!File.Exists(filename)) { WriteDefaultPGName(filename); } StringCollection sectionlist = new StringCollection(); StringCollection sectionlist2 = new StringCollection(); ini.ReadSectionValues("34", keylist34); ini.ReadSectionValues("GP2", keylistGP2); ini.ReadSection("34", sectionlist); ini.ReadSection("GP2", sectionlist2); tp07_lb01.Items.Clear(); try { for (int i = 0; i < sectionlist.Count; i++) { tp07_lb01.Items.Add(sectionlist[i]); tp07_lb01_List.Add(sectionlist[i]); } tp07_lb01.Font = new System.Drawing.Font("微軟正黑體", 14, FontStyle.Bold); } catch (Exception) { throw; } return true; } private void tp07_tb01_EditValueChanged(object sender, EventArgs e) { //tp07_lb01.SelectedIndex = -1; tp07_lb01.Items.Clear(); if (tp07_tb01.Text == "") { for (int i = 0; i < tp07_lb01_List.Count; i++) { tp07_lb01.Items.Add(tp07_lb01_List[i]); } tp07_lb01.SelectedIndex = -1; return; } for (int i = 0; i < tp07_lb01_List.Count; i++) { int j = tp07_lb01_List[i].ToString().IndexOf(tp07_tb01.Text); if (j>=0) { tp07_lb01.Items.Add(tp07_lb01_List[i]); } } for (int i = 0; i < keylist34.Count; i++) { int j = keylist34[i].ToString().IndexOf(tp07_tb01.Text); if (j >= 0) { tp07_lb01.Items.Add(keylist34[i]); } } for (int i = 0; i < keylistGP2.Count; i++) { int j = keylistGP2[i].ToString().IndexOf(tp07_tb01.Text); if (j >= 0) { tp07_lb01.Items.Add(keylistGP2[i]); } } } private void tp07_lb01_SelectedIndexChanged(object sender, EventArgs e) { if (tp07_lb01.SelectedIndex == -1) { tp07_tb02.Text = ""; tp07_tb04.Text = ""; tp07_tb03.Text = ""; tp07_tb05.Text = ""; return; } string filename = PGNamePath; string SectoinName = "34"; SetupIni ini = new SetupIni(); ini.SetFileName(filename); tp07_tb02.Text = ini.ReadString("34", tp07_lb01.Text, ""); tp07_tb04.Text = tp07_lb01.Text; tp07_tb03.Text = ini.ReadString("GP2", tp07_lb01.Text, ""); tp07_tb05.Text = tp07_lb01.Text; if (tp07_tb02.Text == "") { for (int i = 0; i < keylist34.Count; i++) { if (keylist34[i] == tp07_tb04.Text) { tp07_tb02.Text = keylist34.Keys[i]; tp07_tb04.Text = keylist34[i];//ini.ReadString("34", tp07_tb02.Text, ""); ; } } } if (tp07_tb03.Text == "") { for (int i = 0; i < keylistGP2.Count; i++) { if (keylistGP2.GetValues(i)[0] == tp07_tb05.Text) { tp07_tb03.Text = keylistGP2.Keys[i]; tp07_tb05.Text = keylistGP2[i];// ini.ReadString("GP2", tp07_tb03.Text, ""); ; } } } if (tp07_tb02.Text == "" && tp07_tb03.Text != "") { tp07_tb04.Text = ini.ReadString("34", tp07_tb03.Text, ""); if (tp07_tb04.Text != "") { for (int i = 0; i < keylist34.Count; i++) { if (keylist34[i] == tp07_tb04.Text) { tp07_tb02.Text = keylist34.Keys[i]; } } } } if (tp07_tb03.Text == "" && tp07_tb02.Text != "") { tp07_tb05.Text = ini.ReadString("GP2", tp07_tb02.Text, ""); if (tp07_tb05.Text != "") { for (int i = 0; i < keylistGP2.Count; i++) { if (keylistGP2[i] == tp07_tb05.Text) { tp07_tb03.Text = keylistGP2.Keys[i]; } } } } } private void WriteDefaultPGName(string fileName) { if (!Directory.Exists(JsonDir)) { Directory.CreateDirectory(JsonDir); } File.Create(fileName).Close(); try { StreamWriter w = new StreamWriter(@fileName, false, System.Text.Encoding.Default); string[] sr = Split("\r\n", Properties.Resources.PGName); for (int i = 0; i < sr.Length; i++) { w.WriteLine(sr[i]); } w.Close(); } catch (Exception ex) { MessageBox.Show("存檔失敗!!\r\n" + ex.Message); } } //QR private void QRA() {/* qrControl.Text = "QrCode.Net"; BitMatrix qrMatrix = qrControl.GetQrMatrix(); //Qr bit matrix for input string "QrCode.Net". qrControl.Lock(); //Lock class. qrControl.ErrorCorrectLevel = ErrorCorrectionLevel.M; //It won't encode and repaint. qrControl.Text = textEdit1.Text; qrMatrix = qrControl.GetQrMatrix(); //Qr bit matrix for input string "QrCode.Net". qrControl.UnLock(); //Unlock class, re-encode and repaint. qrControl.Freeze(); //Freeze class. */ } private void button1_Click(object sender, EventArgs e) { QRA(); } private void TEST1_Click(object sender, EventArgs e) { /* // 创建接收套接字 serverIp = IPAddress.Parse("127.0.0.1"); serverIPEndPoint = new IPEndPoint(serverIp, int.Parse("4096")); receiveUdpClient = new UdpClient(serverIPEndPoint); // 启动接收线程 Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start();*/ //Pool = new JObject(); // timer_AutoUpdate.Interval = Int32.Parse(tb_Seconds.Text) *1000; // timer_AutoUpdate.Enabled = true; tcpListener = new TcpListener(IPAddress.Any, 4097); listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.Start(); } private void ListenForClients() { this.tcpListener.Start(); int m = 0; int c = 0; while (true) { while (!tcpListener.Pending()) { Thread.Sleep(1000); } ConnectionThread cli = new ConnectionThread(tcpListener, richTextBox1,btn_LoadPool); } } private void TEST2_Click(object sender, EventArgs e) { /* string s = "1,NSD,NSD_PIG"; string value = "False"; AddNode(s, value); string[] s = Split("\"", CurrentNode.Text); CurrentNode.Tag = tb_RValue.Text; CurrentNode.Text = CurrentNode.nodename + ":\"" + CurrentNode.Tag + "\""; tb_VALUE.Text = tb_RValue.Text;*/ } private void AddNode(string path, string value) { FoundNode = null; FindNodes2(MyNode, path, value); if (FoundNode == null) { string[] s = path.Split(','); AddNode2(s,value); } } private void AddNode2(string[] snode, string value) { int i=0; TreeNodeEx a = MyNode; string s = ""; s = snode[i]; while (i<snode.Length) { if (a.Nodes.ContainsKey(s)) { a = (TreeNodeEx)a.Nodes[s]; } else { TreeNodeEx b = new TreeNodeEx(); b.nodename = snode[i]; b.Name = snode[i]; b.index = index++; for (int j=0;j<=i;j++) { b.path += snode[j]; if (j != i) { b.path += ","; } } if (i != snode.Length - 1) //節點 { b.IsHaveChild = true; b.Tag = ""; b.Text = b.nodename; } else { b.IsHaveChild = false; b.Tag = value; b.Text += b.nodename + " : \"" + value + "\""; b.value = value; b.ImageIndex = 2; b.SelectedImageIndex = 2; } a.Nodes.Add(b); a = (TreeNodeEx)a.Nodes[b.Name]; } i++; if (i < snode.Length) { s = snode[i]; } } } private void btnRefresh_Click(object sender, EventArgs e) { treeView1.Nodes.Clear(); treeView1.Nodes.Add(MyNode); treeView1.Nodes[0].Expand(); } public static void ParseJsonProperties(JObject jObject, string paramName) { IEnumerable<JProperty> jObject_Properties = jObject.Properties(); // Build list of valid property and object types JsonTokenType[] validPropertyValueTypes = { JsonTokenType.String, JsonTokenType.Integer, JsonTokenType.Float, JsonTokenType.Boolean, JsonTokenType.Null, JsonTokenType.Date }; List<JsonTokenType> propertyTypes = new List<JsonTokenType>(validPropertyValueTypes); JsonTokenType[] validObjectTypes = { JsonTokenType.String, JsonTokenType.Array, JsonTokenType.Object }; List<JsonTokenType> objectTypes = new List<JsonTokenType>(validObjectTypes); string currentParamName = paramName; //Need to track where we are. foreach (JProperty property in jObject_Properties) { paramName = currentParamName; try { if (propertyTypes.Contains(property.Value.Type)) { string stmp = ""; if (paramName == "") stmp = ""; else stmp = paramName + ","; ParseJsonKeyValue(property, stmp + property.Name.ToString()); } else if (objectTypes.Contains(property.Value.Type)) { //Arrays ex. { names: ["first": "John", "last" : "doe"]} if (property.Value.Type == JsonTokenType.Array && property.Value.HasValues) { ParseJsonArray(property, paramName); } //Objects ex. { name: "john"} if (property.Value.Type == JsonTokenType.Object) { JObject jo = new JObject(); jo = JObject.Parse(property.Value.ToString()); paramName = property.Name.ToString(); jsonKeyValues.Add(paramName, "");//property.Value.ToString()); if (jo.HasValues) { ParseJsonProperties(jo, paramName); } } } } catch (Exception ex) { throw; } } // End of ForEach paramName = currentParamName; } public static void ParseJsonKeyValue(JProperty item, string paramName) { jsonKeyValues.Add(paramName, item.Value.ToString()); } public static void ParseJsonArray(JProperty item, string paramName) { JArray jArray = (JArray)item.Value; if (paramName == "") paramName = item.Name.ToString(); else paramName = paramName + "," + item.Name.ToString(); jsonKeyValues.Add(paramName, item.Value.ToString()); string currentParamName = paramName; //Need track where we are try { for (int i = 0; i < jArray.Count(); i++) { paramName = currentParamName; paramName = i.ToString(); jsonKeyValues.Add(paramName, jArray.Values<object>().ElementAt(i).ToString()); JObject jo = new JObject(); jo = JObject.Parse(jArray[i].ToString()); IEnumerable<JProperty> jArrayEnum = jo.Properties(); foreach (JProperty jaItem in jArrayEnum) { // Prior to JSON.NET VER 5.0, there was no Path property on JTokens. So we had to track the path on our own. var paramNameWithJaItem = jaItem.Name.ToString(); var itemValue = jaItem.Value.ToString(); if (itemValue.Length > 0) { switch (itemValue.Substring(0, 1)) { case "[": //Recusion call to itself ParseJsonArray(jaItem, paramNameWithJaItem); break; case "{": //Create a new JObject and parse JObject joObject = new JObject(); joObject = JObject.Parse(itemValue); //For this value, reparse from the top ParseJsonProperties(joObject, paramNameWithJaItem); break; default: ParseJsonKeyValue(jaItem, paramNameWithJaItem); break; } } } } //end for loop paramName = currentParamName; } catch (Exception ex) { throw; } } class ConnectionThread { public TcpListener threadListener; private static int connections = 0; private static int connThread = 0; private static int countMsg = 0; public RichTextBox rtb = null; public Button btn = null; private byte[] data = new byte[2] { 79, 75 }; public MemoryStream MStream = null; public bool IsDone = false; //public ConnectionThread(TcpListener lis, RichTextBox xrtb, JObject varPool, Button xbtn) public ConnectionThread(TcpListener lis, RichTextBox xrtb, Button xbtn) { threadListener = lis; rtb = xrtb; btn = xbtn; //ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm), varPool); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm), Pool); } public void HandleClientComm(object state) { TcpClient tcpClient = null; NetworkStream clientStream = null; try { tcpClient = threadListener.AcceptTcpClient(); clientStream = tcpClient.GetStream(); } catch (System.Exception ex) { } connThread++; int bytesRead; while (true) { bytesRead = 0; string output = ""; try { if (clientStream.CanRead) { byte[] message = new byte[8192]; do { bytesRead = clientStream.Read(message, 0, message.Length); ASCIIEncoding encoder = new ASCIIEncoding(); output = encoder.GetString(message, 0, bytesRead); } while (clientStream.DataAvailable); clientStream.Write(data, 0, data.Length); if (output.Trim() != "") { JObject r = JObject.Parse(output); string mOptions = ""; if (r["Options"] != null) { mOptions = (string)r["Options"]; if (mOptions == "GetPool") { if (r["Value"] != null) { if ((string)r.Property("Value").Value == "OK") { GetPool(btn); } } } else //ShowListView(r, rtb, (JObject)state); ShowListView(r, rtb); } break; } } else { Console.WriteLine("Sorry. You cannot read from this NetworkStream."); } } catch { break; } } if (tcpClient !=null) { tcpClient.Close(); } connThread--; } private delegate void GetPoolDelegate(Button btn); private void GetPool(Button btn) { if (btn.InvokeRequired) { GetPoolDelegate removedelegate = GetPool; btn.Invoke(removedelegate, btn); } else { btn.PerformClick(); IsCanUpdate = true; } } //private delegate void ShowListViewDelegate(JObject output, RichTextBox xrtb, JObject varPool); //private void ShowListView(JObject output, RichTextBox xrtb, JObject varPool) private delegate void ShowListViewDelegate(JObject output, RichTextBox xrtb); private void ShowListView(JObject output, RichTextBox xrtb) { connections++; if (xrtb.InvokeRequired) { ShowListViewDelegate removedelegate = ShowListView; //xrtb.Invoke(removedelegate, output, xrtb, varPool); xrtb.Invoke(removedelegate, output, xrtb); } else { try { JArray mStratum = null; string mOptions = ""; JToken mValue = null; JObject r = output; string stratum = ""; string[] mtmp = null; if (r["Options"] != null) { mOptions = (string)r["Options"]; } if (mOptions == "SetStratumValue") { if (r["Stratum"] != null) { mStratum = (JArray)r["Stratum"]; } if (r["Value"] != null) { mValue = r.Property("Value").Value; } mtmp = new string[mStratum.Count()]; for (int i = 0; i < mStratum.Count(); i++) { mtmp[i] = ((JValue)mStratum[i]).Value.ToString(); } //SetStratumValue(varPool, mtmp, mValue); SetStratumValue(Pool, mtmp, mValue); } else if (mOptions == "DeleteByName") { if (r["Stratum"] != null) { mStratum = (JArray)r["Stratum"]; stratum = (string)((JValue)mStratum[0]).Value.ToString(); //DeleteByName(varPool, ((JValue)mStratum[0]).Value.ToString()); DeleteByName(Pool, ((JValue)mStratum[0]).Value.ToString()); } } else if (mOptions == "DeleteByStratum") { if (r["Stratum"] != null) { mStratum = (JArray)r["Stratum"]; mtmp = new string[mStratum.Count()]; for (int i = 0; i < mStratum.Count(); i++) { mtmp[i] = ((JValue)mStratum[i]).Value.ToString(); } //DeleteByStratum(varPool, mtmp); DeleteByStratum(Pool, mtmp); } } else if (mOptions == "SendAllToMoitor") { } else if (mOptions == "GetPool") { if (r["Value"] != null) { mValue = r.Property("Value").Value; if (mValue.ToString() == "OK") { } } } //string rstr = r.ToString().Replace("\r\n", ""); //countMsg++; //Console.WriteLine(countMsg.ToString()); //if (countMsg % 50 == 0) if (rtb.Lines.Count() >= 14) { rtb.Text = ""; } //rtb.Text += "[" + countMsg.ToString() + "]" + rstr +"\r\n"; //if (IsLogToTxt) { if (stratum == "") { for (int i = 0; i < mStratum.Count(); i++) { stratum += "'" + (string)((JValue)mStratum[i]).Value.ToString() + "',"; } } string mstr = ""; stratum = stratum.Substring(0, stratum.Length - 1); mstr = " {'" + mOptions.Substring(0, 1); mstr += "',[" + stratum + "],'"; mstr += (string)((JValue)mValue).Value.ToString() + "'}"; countMsg++; rtb.Text += "[" + countMsg.ToString() + "]" + mstr + "\r\n"; if (IsLogToTxt) WriteTotxt(mstr); } IsCanUpdate = true; } catch (System.Exception ex) { WriteTotxt(ex.Message); } } } private void DeleteByName(JObject Owner, string name) { bool mBool = false; JProperty mobj2; mBool = ExistOfName(Owner, name,out mobj2); if (mBool) { Owner[mobj2.Name].Remove(); } } private void DeleteByStratum(JObject Owner, string[] Stratum) { bool mBool = false; bool GODel = false; JProperty mobj2 = null; JProperty mobj3 = null; JObject mobj = Owner; for (int i = 0; i < Stratum.Length;i++ ) { mBool = ExistOfName(mobj, Stratum[i], out mobj2); if (mBool) { GODel = true; mobj3 = mobj.Property(Stratum[i]); mobj = (JObject)mobj3.Value; //mobj = (JObject)mobj.Property(Stratum[i]).Value; } else { return; } } if (GODel) { mobj3.Remove(); } } private void SetStratumValue(JObject Owner, string[] Stratum, JToken Value) { int max; JObject mobj, mobj1; JProperty mobj2; bool mBool = false; JProperty mPar; if (Stratum.Length == 0) return; mobj = Owner; max = Stratum.Length - 1; for (int i = 0; i < max; i++) { mBool = ExistOfName(mobj, Stratum[i],out mobj2); if (!mBool) { mobj1 = new JObject(); mobj.Add(new JProperty(Stratum[i], mobj1)); mobj = mobj1; } else { mPar = new JProperty(mobj.Property(Stratum[i]).Name,mobj.Property(Stratum[i]).Value); if (mPar.Value.Type == JsonTokenType.Object) { mobj = (JObject)mobj.Property(Stratum[i]).Value; //mobj = (JObject)mPar.Value; } else { mobj1 = new JObject(); mPar.Value = mobj1; mobj = mobj1; } } } mBool = ExistOfName(mobj, Stratum[max], out mobj2); if (!mBool) { mobj.Add(new JProperty(Stratum[max], Value)); mBool = false; } else { mobj.Property(Stratum[max]).Value = Value; } } private bool ExistOfName(JObject Owner, string Name, out JProperty item) { bool result = false; item = null; IEnumerable<JProperty> jObject_Properties = Owner.Properties(); foreach (JProperty j in jObject_Properties) { if (j.Name == Name) { item = j; result = true; break; } } return result; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { SendMsgToPOS(0); if (tcpListener != null) { tcpListener.Stop(); } if (listenThread != null) { listenThread.Abort(); } } private void richTextBox1_TextChanged(object sender, EventArgs e) { } private void cboListen_CheckedChanged(object sender, EventArgs e) { int i = 0; if (cboListen.Checked) { i = 1; } SendMsgToPOS(i); } private void tb_GetJsonAll_Click(object sender, EventArgs e) { SendMsgToPOS(2); } private void SendMsgToPOS(int Msg) { IntPtr hwnd = FindWindow("DSC_POSMainAppName", "POS"); if (hwnd != IntPtr.Zero) { IntPtr childHwnd = FindWindowEx(hwnd, IntPtr.Zero, "TfamPOSVI01", null); //获得按钮的句柄 if (childHwnd != IntPtr.Zero) { SendMessage(hwnd, 2592, Msg, 0); //发送点击按钮的消息 } else { MessageBox.Show("没有找到POSVI01S"); } } else { MessageBox.Show("没有找到POSMAINGP"); } } private bool SendMsgToPOS(uint Msg,int type) { IntPtr hwnd = FindWindow("DSC_POSMainAppName", "POS"); if (hwnd != IntPtr.Zero) { IntPtr childHwnd = FindWindowEx(hwnd, IntPtr.Zero, "TfamPOSVI01", null); //获得按钮的句柄 if (childHwnd != IntPtr.Zero) { SendMessage(hwnd, 2592, Msg, type); //发送点击按钮的消息 return true; } else { MessageBox.Show("没有找到POSVI01S"); return false; } } else { MessageBox.Show("没有找到POSMAINGP"); return false; } } private void cboAutoUpdate_CheckedChanged(object sender, EventArgs e) { //timer_AutoUpdate.Enabled = cboAutoUpdate.Checked; timer_AutoUpdate.Interval = Int32.Parse(tb_Seconds.Text)*1000; } private void timer_AutoUpdate_Tick(object sender, EventArgs e) { if (cboAutoUpdate.Checked) { if (IsCanUpdate) { IsCanUpdate = false; btn_UpdatePool.PerformClick(); tP01_btnReFresh.PerformClick(); } } } private static void WriteTotxt(string str) { // 建立檔案串流(@ 可取消跳脫字元 escape sequence) StreamWriter sw = new StreamWriter(@JsonDir + string.Format("{0:yyyyMMdd}", DateTime.Now)+".txt",true); str = "[" + string.Format("{0:00000}", LogLines++) + "]" + str; sw.WriteLine(str); // 寫入文字 sw.Close(); // 關閉串流 } private void chkLogToTxt_CheckedChanged(object sender, EventArgs e) { } private void btn_DelTxt_Click(object sender, EventArgs e) { } private void btn_Opentxt_Click(object sender, EventArgs e) { } private void ShowMsg(string msg) { lbl_Msg.Text = msg; lbl_Msg.ForeColor = Color.Red; } private void tm_Msg_Tick(object sender, EventArgs e) { lbl_Msg.Text = ""; } private void btn_Lock_Click(object sender, EventArgs e) { if (!Checktp02_IsValueExist(tb_PATH.Text)) { uint s = GlobalAddAtom(tb_PATH.Text); if (SendMsgToPOS(s,9)) { AddRowToDGV03(tb_PATH.Text); } } } private bool Checktp02_IsValueExist(string s) { bool IsExist = false; string[] tmp = s.Split(','); for (int j = 0; j < dgv03.RowCount;j++ ) { if (tmp.Length == Int32.Parse(dgv03.Rows[j].Cells[0].Value.ToString())) { for (int i = 0; i < tmp.Length;i++ ) { if (tmp[i] == dgv03.Rows[j].Cells[i + 1].Value.ToString()) { if (i==tmp.Length-1) { IsExist = true; return IsExist; } } } } else { continue; } } return IsExist; } private void AddRowToDGV03(string s) { string[] tmp = s.Split(','); string[] tmp1 = new string[tmp.Length + 1]; tmp1[0] = tmp.Length.ToString(); for (int i = 1; i < tmp1.Length; i++) { tmp1[i] = tmp[i - 1]; } dgv03.Rows.Add(tmp1); dgv03.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } private void tp02_btnDel_Click(object sender, EventArgs e) { if (DGV03_SelectIndex == -1) { return; } string tmp = ""; int count = Int32.Parse(dgv03.Rows[DGV03_SelectIndex].Cells[0].Value.ToString()); for (int i = 1; i < count; i++) { tmp += dgv03.Rows[DGV03_SelectIndex].Cells[i].Value.ToString() + ","; } tmp = tmp.Substring(0, tmp.Length - 1); uint s = GlobalAddAtom(tb_PATH.Text); if (SendMsgToPOS((uint)DGV03_SelectIndex, 8)) { dgv03.Rows.RemoveAt(DGV03_SelectIndex); } } private void dgv03_RowEnter(object sender, DataGridViewCellEventArgs e) { DGV03_SelectIndex = e.RowIndex; } private void btn_ClearLog_Click(object sender, EventArgs e) { richTextBox1.Text = ""; } private void btn_InitPool_Click(object sender, EventArgs e) { Pool = JObject.Parse("{}"); btn_UpdatePool.PerformClick(); } private void tp02_btnEmpty_Click(object sender, EventArgs e) { if (SendMsgToPOS((uint)DGV03_SelectIndex, 7)) { dgv03.Rows.Clear(); } } } }
using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Witsml; using WitsmlExplorer.Api.Jobs; using WitsmlExplorer.Api.Jobs.Common; using WitsmlExplorer.Api.Services; using WitsmlExplorer.Api.Workers; using Xunit; namespace WitsmlExplorer.IntegrationTests.Api.Workers { [SuppressMessage("ReSharper", "xUnit1004")] public class CopyTrajectoryWorkerTests { private readonly CopyTrajectoryWorker worker; private readonly DeleteTrajectoryWorker deleteLogWorker; private readonly IWitsmlClient client; public CopyTrajectoryWorkerTests() { var configuration = ConfigurationReader.GetConfig(); var witsmlClientProvider = new WitsmlClientProvider(configuration); client = witsmlClientProvider.GetClient(); worker = new CopyTrajectoryWorker(witsmlClientProvider); deleteLogWorker = new DeleteTrajectoryWorker(witsmlClientProvider); } [Fact(Skip = "Should only be run manually")] public async Task CopyTrajectory() { var job = new CopyTrajectoryJob { Source = new TrajectoryReference { WellUid = "4d287b3e-9d9c-472a-9b82-d667d9ea1bec", WellboreUid = "a2d2854b-3880-4058-876b-29b14ed7c917", TrajectoryUid = "1YJFL7" }, Target = new WellboreReference { WellUid = "fa53698b-0a19-4f02-bca5-001f5c31c0ca", WellboreUid = "70507fdf-4b01-4d62-a642-5f154c57440d" } }; await worker.Execute(job); } } }
using UnityEngine; using System.Collections; public class LaunchCountController : MonoBehaviour { // Use this for initialization void Start () { int launchCount = PersistentStorage.instance.GetIntValue("launchCount", 0); PersistentStorage.instance.SetIntValue ("launchCount", launchCount + 1); } }
using System; [Serializable] public class GException1 : GException0 { public GException1(string string_0) : base(string_0) { } }
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 MultiplechoiseSystem.DAO; using MultiplechoiseSystem.DTO; namespace MultiplechoiseSystem.FORM { public partial class FShowQuestion : Form { private string Idquestion; public FShowQuestion(string idquestion) { Idquestion = idquestion; InitializeComponent(); } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private RichTextBox RichAnswer(string text, int iscorrect) { RichTextBox richTextBox3 = new RichTextBox(); richTextBox3.BackColor = System.Drawing.SystemColors.ControlLight; richTextBox3.BorderStyle = System.Windows.Forms.BorderStyle.None; richTextBox3.Location = new System.Drawing.Point(3, 9); richTextBox3.ReadOnly = true; richTextBox3.Size = new System.Drawing.Size(972, 33); richTextBox3.Text = text; if (iscorrect == 1) { richTextBox3.ForeColor = Color.MediumSeaGreen; } else richTextBox3.ForeColor = Color.Crimson; return richTextBox3; } private void FShowQuestion_Load(object sender, EventArgs e) { QuestionDTO question = QuenstionDAO.Instance.LoadQuestionByID(Idquestion); richQuestion.Text = question.qText; foreach (Answer i in question.answers) { flp_answers.Controls.Add(RichAnswer(i.text, i.inCorrect)); } } private void flp_answers_Paint(object sender, PaintEventArgs e) { } private void panel3_Paint(object sender, PaintEventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using NUnit.Framework; namespace TextToHTML.Models { public class NotedLineBuilder { private string _line; /// <summary> /// Creates a noted line where no escaping or noting is done on the /// raw string. Not intended to be used on user-entered lines. /// </summary> /// <param name="unescaped"></param> public static NotedLine BuildWithoutEscaping(string unescaped) { var notedLine = new NotedLine(); notedLine.Line = unescaped; return notedLine; } /// <summary> /// Creates a noted line from a user-entered string. /// </summary> /// <param name="x"></param> /// <returns></returns> public static NotedLine Build(string x) { var noter = new NotedLineBuilder(x); return noter.ConvertLine(); } public NotedLineBuilder(string line) { _line = line; } /// <summary> /// Notes position of user-syntax flags and removes escaping backslashes. /// If the line is a list item, wraps it in list item tags. /// </summary> /// <returns></returns> private NotedLine ConvertLine() { var result = new NotedLine(); var code = LineTyper.IsCodeLine(_line); _line = HttpUtility.HtmlEncode(_line); RemoveLeadingFlags(); if (code) { result.Line = _line + "\n"; return result; } string line = ""; bool slashEscaped = false; bool linkContentOpen = false; int linkContentClosePosition = -1; // When the line contains escape characters, flag positions in the // result aren't the same as in the input. The final position is // calculated as i + offset int offset = 0; for (int i = 0; i < _line.Length; i++) { var element = _line[i]; if (UnescapedEscapeFlag(slashEscaped, element)) { slashEscaped = true; offset--; continue; } if (UnescapedBoldFlag(slashEscaped, element)) { result.FlagPositions[Flags.Bold].Add(i + offset); } if (UnescapedItalicFlag(slashEscaped, element)) { result.FlagPositions[Flags.Italics].Add(i + offset); } if (element == Flags.HyperLinkOpen) { int linkClosePosition = _line.IndexOf(Flags.HyperLinkClose, i); linkContentClosePosition = _line.IndexOf(Flags.HyperLinkContentClose, linkClosePosition + 1); if (ProperlyFormattedLink(linkClosePosition, linkContentClosePosition)) { line += LinkTag(i, linkClosePosition); offset += 9; //ignore the closing ], then the loop increment will ignore ( i = linkClosePosition + 1; linkContentOpen = true; slashEscaped = false; continue; } } if (linkContentOpen && i == linkContentClosePosition) { line += "</a>"; linkContentOpen = false; slashEscaped = false; offset += 2; //set offset continue; } slashEscaped = false; line += element; } result.Line = line; return result; } private string LinkTag(int i, int linkClosePosition) { string link = _line.Substring(i + 1, linkClosePosition - i - 1); string linkTag = String.Format("<a href=\"{0}\">", link); return linkTag; } private bool ProperlyFormattedLink(int linkClosePosition, int linkContentClosePosition) { bool properlyClosed = linkClosePosition > 0; bool properlyOpenTextPortion = (linkClosePosition + 1 < _line.Length) && (Flags.HyperLinkContentOpen == _line[linkClosePosition + 1]); bool contentProperlyClosed = linkContentClosePosition > 0; bool properlyFormattedLink = properlyClosed && contentProperlyClosed && properlyOpenTextPortion; return properlyFormattedLink; } private static bool UnescapedItalicFlag(bool slashEscaped, char element) { return !slashEscaped && element == Flags.Italics; } private static bool UnescapedBoldFlag(bool slashEscaped, char element) { return !slashEscaped && element == Flags.Bold; } private static bool UnescapedEscapeFlag(bool slashEscaped, char element) { return !slashEscaped && element.ToString() == @"\"; } private void RemoveLeadingFlags() { if (LineTyper.IsOrderedList(_line) || LineTyper.IsUnorderedList(_line)) { _line = "<li>" + _line.Substring(1) + "</li>"; } else if (LineTyper.IsCodeLine(_line)) { _line = _line.Substring(4); } } } }
using System; using System.Collections.Generic; using System.Text; namespace PatronAdapter { public class AdaptadorImpresora : IImpresoraEPSON { private ImpresoraHP impresora; public AdaptadorImpresora() { impresora = new ImpresoraHP(); } public string ImprimirHD() { return Imprimir(); } public string Laser() { return ImprimirLaser(); } private string Imprimir() { string rta=impresora.Imprimir(); return rta; } private string ImprimirLaser() { string rta = impresora.Imprimir(); return rta; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LevelSelection : MonoBehaviour { public Button Level1; public Button Level2; public Button Boss; // Start is called before the first frame update void Start() { Level1.onClick.AddListener(() => ChangeLevel("House")); Level2.onClick.AddListener(() => ChangeLevel("Garden")); Boss.onClick.AddListener(() => ChangeLevel("Boss")); } // Update is called once per frame void Update() { } void ChangeLevel(string levelname) { SceneManager.LoadScene(levelname); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphicalEditor.Enumerations { public enum ScheduleType { Appointment, EquipmentTransfer, Renovation } }
using EduHome.DataContext; using EduHome.Helpers.Methods; using EduHome.Models.Base; using EduHome.Models.Entity; using EduHome.ViewModels; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace EduHome.Areas.Admin.Controllers { [Area("admin")] public class PostController : Controller { public EduhomeDbContext _context { get; } public IWebHostEnvironment _env { get; } public PostController(EduhomeDbContext context, IWebHostEnvironment env) { _context = context; _env = env; } public IActionResult Index() { PostVM postVM = new PostVM { Posts = _context.Posts.Include(p => p.Course).ThenInclude(p => p.Category).Include(p => p.PostMessages).ToList() }; return View(postVM); } public IActionResult DeleteOrActive(int? id) { if (id == null) { return NotFound(); } Post post = _context.Posts.Include(p => p.Course).ThenInclude(p => p.Category).Include(p => p.PostMessages).FirstOrDefault(p => p.Id == id); if (post == null) { return BadRequest(); } if (post.IsDeleted) post.IsDeleted = false; else post.IsDeleted = true; _context.SaveChanges(); return RedirectToAction(nameof(Index), post); } public IActionResult Details(int? id) { if (id == null) { return NotFound(); } Post post = _context.Posts.Include(p => p.Course).ThenInclude(c => c.Category).Include(p => p.PostMessages). Where(p => p.IsDeleted == false).FirstOrDefault(p => p.Id == id); if (post == null) { return BadRequest(); } return View(post); } public IActionResult Create() { PostCategoryVM postCategory = new PostCategoryVM { Courses = _context.Courses.Include(c => c.Category). Include(c => c.Feature).Include(c=>c.Posts).Include(c=>c.Events).ToList() }; return View(postCategory); } [HttpPost] [AutoValidateAntiforgeryToken] public IActionResult Create(PostCategoryVM postCategory) { if (!ModelState.IsValid) { return View(postCategory.Post); } if (!postCategory.Post.Photo.ContentType.Contains("image")) { return NotFound(); } if (postCategory.Post.Photo.Length / 1024 > 3000) { return NotFound(); } string filename = Guid.NewGuid().ToString() + '-' + postCategory.Post.Photo.FileName; string environment = _env.WebRootPath; string newSlider = Path.Combine(environment, "img", "blog", filename); using (FileStream file = new FileStream(newSlider, FileMode.Create)) { postCategory.Post.Photo.CopyTo(file); } postCategory.Post.Image = filename; _context.Posts.Add(postCategory.Post); _context.SaveChanges(); List<Subscriber> subscribers = _context.Subscribers.ToList(); foreach (var subscriber in subscribers.Where(s=>s.IsDeleted == false)) { BaseMessage message = new BaseMessage(); message.Email = subscriber.Email; message.Subject = "A post created"; message.Message = "We created a post.You can see if you want"; MailOperations.SendMessage(message); } return RedirectToAction(nameof(Index), postCategory); } public IActionResult Update(int? id) { if (id == null) { return NotFound(); } PostCategoryVM postCategory = new PostCategoryVM { Courses = _context.Courses.Include(c => c.Category).Include(c => c.Feature).Include(c => c.Events). Include(c => c.Posts).ToList(), Post = _context.Posts.Include(p => p.Course).ThenInclude(c => c.Category).Include(p => p.PostMessages). Where(p => p.IsDeleted == false).FirstOrDefault(p => p.Id == id), }; if (postCategory.Post == null) { return BadRequest(); } return View(postCategory); } [HttpPost] [AutoValidateAntiforgeryToken] public IActionResult Update(int? id, PostCategoryVM postCategory) { if (id == null) { return NotFound(); } //if user don't choose image program enter here if (postCategory.Post.Photo == null) { postCategory.Post.Image = postCategory.Image; ModelState["Post.Photo"].ValidationState = ModelValidationState.Valid; if (!ModelState.IsValid) { return View(postCategory); } _context.Posts.Update(postCategory.Post); _context.SaveChanges(); return RedirectToAction(nameof(Index), postCategory); } if (id != postCategory.Post.Id) { return NotFound(); } if (!postCategory.Post.Photo.ContentType.Contains("image")) { return NotFound(); } if (postCategory.Post.Photo.Length / 1024 > 3000) { return NotFound(); } //removing old image from local folder string environment = _env.WebRootPath; string folderPath = Path.Combine(environment, "img", "blog", postCategory.Image); FileInfo oldFile = new FileInfo(folderPath); if (System.IO.File.Exists(folderPath)) { oldFile.Delete(); }; //coping new image in local folder string filename = Guid.NewGuid().ToString() + '-' + postCategory.Post.Photo.FileName; string newSlider = Path.Combine(environment, "img", "blog", filename); using (FileStream newFile = new FileStream(newSlider, FileMode.Create)) { postCategory.Post.Photo.CopyTo(newFile); } //new image and category initiliazing to Post class postCategory.Post.Image = filename; if (!ModelState.IsValid) { return View(postCategory.Post); } _context.Posts.Update(postCategory.Post); _context.SaveChanges(); return RedirectToAction(nameof(Index), postCategory); } public IActionResult Comments() { List<PostMessage> postMessages = _context.PostMessages.Include(pm => pm.Contact).Include(pm=>pm.Course).Include(pm => pm.Post). Include(pm => pm.Event).Where(pm => pm.PostId != null).ToList(); return View(postMessages); } public IActionResult MakeDeleteOrActive(int? id) { if (id == null) { return NotFound(); } PostMessage message = _context.PostMessages.Include(pm => pm.Contact).Include(pm => pm.Course).Include(pm => pm.Post). Include(pm => pm.Event).Where(pm => pm.PostId != null).FirstOrDefault(pm => pm.Id == id); if (message == null) { return BadRequest(); } if (message.IsDeleted == true) message.IsDeleted = false; else message.IsDeleted = true; _context.PostMessages.Update(message); _context.SaveChanges(); return RedirectToAction(nameof(Comments)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebTest { public partial class Cache : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //首次查询后会创建缓存,下次再查询时,会按查询条件找到对应的缓存 //以下缓存为异步更新,过期后会按条件异步重新查询最新数据,有线程单独维护 //缓存在两个周期未使用后,会自动清理 protected void Button1_Click(object sender, EventArgs e) { var query = Code.ProductDataManage.Instance.GetLamadaQuery(); //缓存会按条件不同缓存不同的数据,条件不固定时,慎用 query = query.Where(b => b.Id < 700); int exp = 10;//过期分钟 var list = Code.ProductDataManage.Instance.QueryList(query, exp); } protected void Button2_Click(object sender, EventArgs e) { //默认过期时间为5分钟 //AllCache可重写条件和过期时间,在业务类中实现即可 //当插入或更新当前类型对象时,此缓存中对应的项也会更新 var list = Code.ProductDataManage.Instance.QueryItemFromAllCache(b => b.Id ==1); } protected void Button3_Click(object sender, EventArgs e) { var list = Code.ProductDataManage.Instance.AllCache;//指定一个数据源 #region 常规查找 多次计算和内存操作,增加成本 var list2 = list.Where(b => b.Id > 0);//执行一次内存查找 bool a = false; if (a) { list2 = list.Where(b => b.Number > 10);//执行第二次内存查找 } #endregion #region 优化后查找 只需一次 CRL.ExpressionJoin<Code.ProductData> query = new CRL.ExpressionJoin<Code.ProductData>(b=>b.Id>0); if (a) { query.And(b => b.Number > 10);//and 一个查询条件 } list2 = query.Where(list);//返回查询结果 只作一次内存查找 #endregion } } }
using System.Threading.Tasks; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.DraftApprenticeship; using SFA.DAS.ProviderCommitments.Web.Models; namespace SFA.DAS.ProviderCommitments.Web.Mappers { public class ViewSelectOptionsViewModelToUpdateRequestMapper : IMapper<ViewSelectOptionsViewModel, UpdateDraftApprenticeshipApimRequest> { private readonly ICommitmentsApiClient _commitmentsApiClient; public ViewSelectOptionsViewModelToUpdateRequestMapper (ICommitmentsApiClient commitmentsApiClient) { _commitmentsApiClient = commitmentsApiClient; } public async Task<UpdateDraftApprenticeshipApimRequest> Map(ViewSelectOptionsViewModel source) { var apiResponse = await _commitmentsApiClient.GetDraftApprenticeship(source.CohortId, source.DraftApprenticeshipId); return new UpdateDraftApprenticeshipApimRequest { ReservationId = apiResponse.ReservationId, FirstName = apiResponse.FirstName, LastName = apiResponse.LastName, Email = apiResponse.Email, DateOfBirth = apiResponse.DateOfBirth?.Date, Uln = apiResponse.Uln, CourseCode = apiResponse.CourseCode, Cost = apiResponse.Cost, ActualStartDate = apiResponse.ActualStartDate, StartDate = apiResponse.StartDate?.Date, EndDate = apiResponse.EndDate?.Date, Reference = apiResponse.Reference, CourseOption = source.SelectedOption == "-1" ? string.Empty : source.SelectedOption, DeliveryModel = apiResponse.DeliveryModel, EmploymentEndDate = apiResponse.EmploymentEndDate, EmploymentPrice = apiResponse.EmploymentPrice, IsOnFlexiPaymentPilot = apiResponse.IsOnFlexiPaymentPilot }; } } }
// Uncomment to force TweetDeck to load a predefined version of the vendor/bundle scripts and stylesheets // #define FREEZE_TWEETDECK_RESOURCES using System.Collections.Specialized; using CefSharp; using CefSharp.Handler; using TweetDuck.Core.Handling.General; using TweetDuck.Core.Utils; #if FREEZE_TWEETDECK_RESOURCES using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; #endif namespace TweetDuck.Core.Handling{ class RequestHandlerBase : DefaultRequestHandler{ private readonly bool autoReload; public RequestHandlerBase(bool autoReload){ this.autoReload = autoReload; } public override bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture){ return LifeSpanHandler.HandleLinkClick(browserControl, targetDisposition, targetUrl); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (BrowserUtils.HasDevTools){ NameValueCollection headers = request.Headers; headers.Remove("x-devtools-emulate-network-conditions-client-id"); request.Headers = headers; } return base.OnBeforeResourceLoad(browserControl, browser, frame, request, callback); } public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ if (autoReload){ browser.Reload(); } } #if FREEZE_TWEETDECK_RESOURCES private static readonly Regex TweetDeckResourceUrl = new Regex(@"/dist/(.*?)\.(.*?)\.(css|js)$", RegexOptions.Compiled); private static readonly SortedList<string, string> TweetDeckHashes = new SortedList<string, string>(2){ { "vendor.js", "d897f6b9ed" }, { "bundle.js", "851d3877b9" }, { "vendor.css", "ce7cdd10b6" }, { "bundle.css", "c339f07047" } }; public override bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response){ if (request.ResourceType == ResourceType.Script || request.ResourceType == ResourceType.Stylesheet){ string url = request.Url; Match match = TweetDeckResourceUrl.Match(url); if (match.Success && TweetDeckHashes.TryGetValue($"{match.Groups[1]}.{match.Groups[3]}", out string hash)){ if (match.Groups[2].Value == hash){ Debug.WriteLine($"Accepting {url}"); } else{ Debug.WriteLine($"Rewriting {url} hash to {hash}"); request.Url = TweetDeckResourceUrl.Replace(url, $"/dist/$1.{hash}.$3"); return true; } } } return base.OnResourceResponse(browserControl, browser, frame, request, response); } #endif } }
using System; using System.Collections.Generic; using ImagoCore.Util; using ImagoCore.Enums; namespace ImagoCore.Models.Strategies { public class SchadensModifikationNatuerlicherWertBerechnenStrategy : INatuerlicherWertBerechnenStrategy { public int berechneNatuerlicherWert(Dictionary<ImagoAttribut, int> values) { if (values.ContainsKey(ImagoAttribut.Staerke)) { double staerke = values[ImagoAttribut.Staerke]; var result = (staerke-50) / 20; return MathHelper.KaufmaennischRunden(result); } throw new ArgumentException(); } } }
using SpatialEye.Framework.Client; namespace Lite { /// <summary> /// The header page-specific context (viewModel), allowing the header page (view) to bind to /// </summary> public class LitePrintA4Template2HeaderPageContext : PrintPageContext { /// <summary> /// Holds the typed top-level settings /// </summary> private LitePrintA4Template2SettingsContext SettingsContext { get { return PrintContext as LitePrintA4Template2SettingsContext; } } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GameProject { public class Player : GameObject { private Gun gun; public Gun Gun => gun; public bool Stunned { get; set; } = false; private double stunnedTimer; private int stunnedTime = 1; private Vector2 stunnedDir; private float stunnedPower = 6; public Player(Game game) : base(game) { this.gun = new Gun(game, this, FireRate.SemiAuto); } public void Update(GameTime gameTime, List<Enemy> enemies) { if (!Stunned) { Position += InputManager.PlayerDirection; } else { stunnedTimer += Time.ScaledTime; Position += stunnedDir * (stunnedPower * (float)stunnedTimer); if(stunnedTimer > stunnedTime) { Stunned = false; stunnedTimer = 0; sprite.Color = Color.Black; } } gun.Update(gameTime); CheckPlayerOutOfBounds(); UpdateColliderPosition(); CheckEnemyCollision(enemies); } public override void LoadContent() { sprite = new Sprite(game.Content.Load<Texture2D>("ball"), this); sprite.Color = Color.Black; SpriteRenderer.Sprites.Add(sprite); SetStartPosition(); Collider = new Collisions.BoundingCircle(Position, sprite.texture.Width / 2); gun.LoadContent(); } public void CheckPlayerOutOfBounds() { if (Position.X < game.GraphicsDevice.Viewport.X + sprite.texture.Width / 2) { Position = new Vector2(game.GraphicsDevice.Viewport.X + sprite.texture.Width / 2, Position.Y); } else if(Position.X > game.GraphicsDevice.Viewport.Width - sprite.texture.Width / 2) { Position = new Vector2(game.GraphicsDevice.Viewport.Width - sprite.texture.Width / 2, Position.Y); } if (Position.Y < game.GraphicsDevice.Viewport.Y + sprite.texture.Height / 2) { Position = new Vector2(Position.X, game.GraphicsDevice.Viewport.Y + sprite.texture.Height / 2); } else if(Position.Y > game.GraphicsDevice.Viewport.Height - sprite.texture.Height / 2) { Position = new Vector2(Position.X, game.GraphicsDevice.Viewport.Height - sprite.texture.Height / 2); } } public override void SetStartPosition() { Position = new Vector2((game.GraphicsDevice.Viewport.Width / 2) - (sprite.texture.Width / 2), (game.GraphicsDevice.Viewport.Height / 2) - (sprite.texture.Height / 2)); } public void CheckEnemyCollision(List<Enemy> enemies) { foreach(Enemy e in enemies) { if (Collider.CollidesWith(e.Collider)) { if (!Stunned) { Stunned = true; stunnedDir = Vector2.Normalize(this.Position - e.Position); sprite.Color = Color.Red; InputManager.TimeAlive = 0; InputManager.TimesHit++; } e.Kill(); } } } } }
using System; namespace Agora.EventStore.Eventing { public abstract class Event : IEvent { protected Event() { Id = Guid.NewGuid(); RaisedAt = DateTime.UtcNow; } public Guid Id { get; set; } public DateTime RaisedAt { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Simon.Helpers; using Simon.Models; using Simon.Views; using Simon.Views.Popups; using Xamarin.Forms; namespace Simon.ViewModel { public class MessageThreadViewModel : BaseViewModel { string userId, threadId, name; bool bookMarks, sendEnable; int id; string message; JObject jObject = null; private ObservableCollection<messages> _messageList = new ObservableCollection<messages>(); private ObservableCollection<messageUsers> _threadList = new ObservableCollection<messageUsers>(); private ObservableCollection<messages> AllItems = new ObservableCollection<messages>(); private string _plainContent; public ICommand PersonDetailsCommand { get; set; } public ICommand ReplayCommand { get; set; } public ICommand LoadMoreCommand { get; private set; } private bool _isLoadingInfinite = false; private int _totalRecords = 0; private bool _isLoadingInfiniteEnabled = false; private int _CurrentPage = 1; private int _LastPage = 0; private bool _isTeamLoading = false; private ObservableCollection<messageUsers> _messageUserList = new ObservableCollection<messageUsers>(); public ObservableCollection<messageUsers> messageUserList { get { return _messageUserList; } set { _messageUserList = value; OnPropertyChanged(nameof(messageUserList)); } } private string _labelParty; public string LabelParty { get { return _labelParty; } set { SetProperty(ref _labelParty, value); } } private string _labelTopic; public string LabelTopic { get { return _labelTopic; } set { SetProperty(ref _labelTopic, value); } } public string _TypedMessage { get; set; } public string TypedMessage { get { return _TypedMessage; } set { _TypedMessage = value; OnPropertyChanged(TypedMessage); } } public string _ParticipantName { get; set; } public string ParticipantName { get { return _ParticipantName; } set { _ParticipantName = value; OnPropertyChanged(ParticipantName); } } private bool _IsDataNotAvailable { get; set; } = false; public bool IsDataNotAvailable { get { return _IsDataNotAvailable; } set { _IsDataNotAvailable = value; OnPropertyChanged(nameof(IsDataNotAvailable)); } } private bool _IsListDataAvailable { get; set; } = false; public bool IsListDataAvailable { get { return _IsListDataAvailable; } set { _IsListDataAvailable = value; OnPropertyChanged(nameof(IsListDataAvailable)); } } private DateTime _msgCreatedDate; public DateTime MsgCreatedDate { get { return _msgCreatedDate; } set { _msgCreatedDate = value; OnPropertyChanged(nameof(MsgCreatedDate)); } } public bool IsLoadingInfinite { get { return _isLoadingInfinite; } set { SetProperty(ref _isLoadingInfinite, value); } } public int TotalRecords { get { return _totalRecords; } set { SetProperty(ref _totalRecords, value); } } public bool IsLoadingInfiniteEnabled { get { return _isLoadingInfiniteEnabled; } set { SetProperty(ref _isLoadingInfiniteEnabled, value); } } HttpClient httpClient; public ICommand SendMessageCommand { get; set; } public MessageThreadViewModel() { if (Application.Current.Properties.ContainsKey("PARTYNAME")) { LabelParty = Convert.ToString(Application.Current.Properties["PARTYNAME"]); } if (Application.Current.Properties.ContainsKey("TOPIC")) { LabelTopic = Convert.ToString(Application.Current.Properties["TOPIC"]); } if (Application.Current.Properties.ContainsKey("USERID")) { userId = Convert.ToString(Application.Current.Properties["USERID"]); } if (Application.Current.Properties.ContainsKey("THREADID")) { threadId = Convert.ToString(Application.Current.Properties["THREADID"]); } if (Application.Current.Properties.ContainsKey("ID")) { id = Convert.ToInt16(Application.Current.Properties["ID"]); } if (Application.Current.Properties.ContainsKey("NAME")) { name = Convert.ToString(Application.Current.Properties["NAME"]); } HeaderTitle = LabelParty; HeaderLeftImage = "back_arrow.png"; PersonDetailsCommand = new Command(() => PersonDetailsCommandExecute()); ReplayCommand = new Command(() => ReplayCommandExecute()); SendMessageCommand = new Command(() => SendMessageCommandExecute()); LoadMoreCommand = new Command(async () => { await LoadMore_click(); }); } private async void SendMessageCommandExecute() { if (sendEnable) return; sendEnable = true; await SendMessage(); sendEnable = false; } private async Task SendMessage() { try { if(TypedMessage == null || TypedMessage == "" || string.IsNullOrWhiteSpace(TypedMessage)) { return; } else { var message = !string.IsNullOrEmpty(TypedMessage.Trim()) ? TypedMessage.Trim() : string.Empty; var values = new Dictionary<object, object> { {"author",userId }, {"threadId",threadId}, {"plainContent", message}, {"createdDate", DateTime.Now.ToUniversalTime() }, {"memoToFile",null}, {"sendToOfficer",false}, }; httpClient = new HttpClient(); var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(Config.SAVE_MESSAGE_API, content); if (response.StatusCode != System.Net.HttpStatusCode.OK || response.Content == null) { await ClosePopup(); Device.BeginInvokeOnMainThread(async () => { await ShowAlert("Data Not Sent!!", string.Format("Response contained status code: {0}", response.StatusCode)); }); } else { await ClosePopup(); var content1 = await response.Content.ReadAsStringAsync(); Debug.WriteLine(content1); TypedMessage = null; Settings.TypedMessage = TypedMessage; MessageReplayViewModel thisVm = new MessageReplayViewModel(); await FetchThreadUserData(); //await SendThreadUsersAsync(); //await ShowAlertWithAction("Success", content1, "Ok", "Cancel"); //var yesSelected = await DisplayAlert("Simon", content, "Ok", "Cancel"); // the call is awaited //if (yesSelected) // No compile error, as the result will be bool, since we awaited the Task<bool> //{ // await Navigation.PopToRootAsync(); //} //else { return; } } } } catch (Exception ex) { await ClosePopup(); ShowExceptionAlert(ex); } finally { await ClosePopup(); } } private async Task SendThreadUsersAsync() { httpClient = new HttpClient(); if(Settings.MessageThreadUsersData!=null && Settings.MessageThreadUsersData.Count>0) { var content = new StringContent(JsonConvert.SerializeObject(Settings.MessageThreadUsersData), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(Config.SYNC_PARTICIPANTS + threadId, content); if (response.StatusCode != System.Net.HttpStatusCode.OK || response.Content == null) { await ClosePopup(); Device.BeginInvokeOnMainThread(async () => { await ShowAlert("Data Not Sent!!", string.Format("Response contained status code: {0}", response.StatusCode)); }); } else { var responceContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responceContent); } } else { await FetchThreadUserData(); } } private async void ReplayCommandExecute() { MessageReplayViewModel replayViewModel = new MessageReplayViewModel(); replayViewModel.ScreenTitle = Constants.MessageScreenTitle; Settings.TypedMessage = TypedMessage; await App.Current.MainPage.Navigation.PushAsync(new MessageReplyPage(), false); } public void PersonDetailsCommandExecute() { } public string plainContent { get { return _plainContent; } set { _plainContent = value; OnPropertyChanged(nameof(plainContent)); } } public ObservableCollection<messages> MessageList { get { return _messageList; } set { _messageList = value; OnPropertyChanged(nameof(MessageList)); } } public ObservableCollection<messageUsers> ThreadList { get { return _threadList; } set { _threadList = value; OnPropertyChanged(nameof(ThreadList)); } } private bool _IsLoadingInfiniteVisible { get; set; } = false; public bool IsLoadingInfiniteVisible { get { return _IsLoadingInfiniteVisible; } set { _IsLoadingInfiniteVisible = value; OnPropertyChanged(nameof(IsLoadingInfiniteVisible)); } } public async Task FetchThreadUserData() { _isTeamLoading = true; IsLoadingInfiniteEnabled = true; App.buttonClick = 0; try { MessageList = new ObservableCollection<messages>(); IsBusy = true; _CurrentPage = 1; await LoadData(_CurrentPage); } catch (Exception ex) { Debug.WriteLine("Exception:>" + ex); } finally { IsBusy = false; _isTeamLoading = false; } } async Task LoadData(int page) { var tempOpenData = new ObservableCollection<messages>(MessageList); using (HttpClient hc = new HttpClient()) { try { IsBusy = true; bool IsBookMarkSelect = false; if(Settings.TypedMessage != null) { TypedMessage = Settings.TypedMessage; } var jsonString = await hc.GetStringAsync(Config.MESSAGE_THREAD_API + threadId + "/" + page); if (jsonString != "") { var obj = JsonConvert.DeserializeObject<DealMessageThreadList>(jsonString); if (obj != null) { foreach (var user in obj.messages) { ThreadList.Clear(); string authorIdStr = user.authorId; if (user.messageUsers != null) { foreach (var thread in user.messageUsers) { if(thread.userid_10 == userId) { if (thread.followUp == true) { IsBookMarkSelect = true; } else { IsBookMarkSelect = false; } } ThreadList.Add(thread); } if (IsBookMarkSelect == true) { user.BookMarkImg = "orange_bookmark.png"; } else { user.BookMarkImg = "bookmark.png"; } } if (authorIdStr == null) { user.HorizontalOption = LayoutOptions.StartAndExpand; user.IsSenderBookMarkVisible = false; user.IsSenderProfileVisible = true; user.IsProfileVisible = false; user.IsBookMarkVisible = true; } else if (authorIdStr.Equals(userId)) { user.HorizontalOption = LayoutOptions.EndAndExpand; user.IsSenderBookMarkVisible = true; user.IsSenderProfileVisible = false; user.IsProfileVisible = true; user.IsBookMarkVisible = false; } else { user.HorizontalOption = LayoutOptions.StartAndExpand; user.IsSenderBookMarkVisible = false; user.IsSenderProfileVisible = true; user.IsProfileVisible = false; user.IsBookMarkVisible = true; } if (user.plainContent == null) { user.IsStopVisible = false; user.HeightRequest = 0; } else if (user.plainContent.Count() < 150) { user.IsStopVisible = false; user.HeightRequest = 0; } else if (user.plainContent.Count() > 150) { user.IsStopVisible = true; user.moreBtnText = "more"; user.HeightRequest = 35; user.MaxLines = 3; } TotalRecords = obj.totalRecords; _LastPage = Convert.ToInt32(obj.totalPages); tempOpenData.Add(user); } ObservableCollection<messages> OrderbyIdDesc = new ObservableCollection<messages>(tempOpenData.OrderByDescending(x => x.createdDate.Date)); MessageList = new ObservableCollection<messages>(OrderbyIdDesc); } } } finally { IsBusy = false; } } } public async Task LoadMore_click() { using (HttpClient hc = new HttpClient()) { try { if (_LastPage == _CurrentPage) { IsLoadingInfinite = false; IsLoadingInfiniteEnabled = false; return; } if (_isTeamLoading) { IsLoadingInfinite = false; return; } //_CurrentPage++; if (App.isFromAddParticipantPage == true) { App.isFromAddParticipantPage = false; _CurrentPage = 1; } else { _CurrentPage++; } await LoadData(_CurrentPage); } catch (Exception ex) { IsBusy = false; ShowExceptionAlert(ex); } finally { IsBusy = false; } } IsLoadingInfinite = false; } public async Task PostReadThreadData() { using (HttpClient hc = new HttpClient()) { try { IsBusy = true; Object userInfo = new { threadId = threadId, userId = userId }; var kvalues = new Dictionary<string, object> { {"threadId",threadId}, {"userId",userId }, }; var jObject = JsonConvert.SerializeObject(kvalues); var content = new StringContent(jObject, Encoding.UTF8, "application/json"); HttpResponseMessage hs = await hc.PostAsync(Config.MARK_THREADMESSAGE_READ, content); var result = await hs.Content.ReadAsStringAsync(); if (hs.IsSuccessStatusCode) { //return Task; } } finally { IsBusy = false; } } } public ICommand personIcon_Clicked { get { return new Command<messages>(personIcon_Click); } } private async void personIcon_Click(messages list) { ParticipantListPopup ParticipantPopupview = new ParticipantListPopup(); ParticipantPopupview.BindingContext = this; this.GetParticipantData(list); await ShowPopup(ParticipantPopupview); } public void GetParticipantData(messages messages) { messageUserList.Clear(); if (messages.messageUsers.Count != 0) { IsListDataAvailable = true; IsDataNotAvailable = false; foreach (var user in messages.messageUsers) { messageUserList.Add(user); } } else { IsDataNotAvailable = true; IsListDataAvailable = false; } } public ICommand BookMarkCommand { get { return new Command<messages>(BookMark_click); } } private async void BookMark_click(messages list) { if (list.messageUsers != null) { if (list.BookMarkImg == "orange_bookmark.png") { list.BookMarkImg = "bookmark.png"; bookMarks = false; } else { list.BookMarkImg = "orange_bookmark.png"; bookMarks = true; } var values = new Dictionary<object, object> { {"name",name }, {"userid_10",userId}, {"followUp", bookMarks}, }; var client = new HttpClient(); string url = Config.MARK_THREADMESSAGE_BOOKMARK + list.id + "/" + bookMarks + "/" + userId; var content1 = new StringContent(JsonConvert.SerializeObject(jObject), Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content1); if (response.StatusCode != System.Net.HttpStatusCode.OK || response.Content == null) { Device.BeginInvokeOnMainThread(async () => { //await DisplayAlert("Data Not Sent!!", string.Format("Response contained status code: {0}", response.StatusCode), "OK"); }); } else { var content = await response.Content.ReadAsStringAsync(); Debug.WriteLine(content); } } } public ICommand ClosePopup_Command { get { return new Command(ClosePopup_click); } } private async void ClosePopup_click() { await ClosePopup(); } } }
using Google.Protobuf; using Grpc.Core; using Microsoft.Extensions.DependencyInjection; using Sentry.Internal.Extensions; namespace Sentry.AspNetCore.Grpc; /// <summary> /// Scope Extensions /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class ScopeExtensions { /// <summary> /// Populates the scope with the gRPC data /// </summary> public static void Populate<TRequest>(this Scope scope, ServerCallContext context, TRequest? request, SentryAspNetCoreOptions options) where TRequest : class { // Not to throw on code that ignores nullability warnings. if (scope.IsNull() || context.IsNull() || options.IsNull()) { return; } scope.SetTag("grpc.method", context.Method); if (request is IMessage requestMessage) { SetBody(scope, context, requestMessage, options); } } private static void SetBody<TRequest>(Scope scope, ServerCallContext context, TRequest request, SentryAspNetCoreOptions options) where TRequest : class, IMessage { var httpContext = context.GetHttpContext(); var extractors = httpContext.RequestServices .GetService<IEnumerable<IProtobufRequestPayloadExtractor>>(); if (extractors == null) { return; } var dispatcher = new ProtobufRequestExtractionDispatcher(extractors, options, () => options.MaxRequestBodySize); var adapter = new GrpcRequestAdapter<TRequest>(request); var message = dispatcher.ExtractPayload(adapter); if (message != null) { // Convert message into JSON format for readability scope.Request.Data = JsonFormatter.Default.Format(message); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Construction_Project { public partial class tr_update_vehicles : System.Web.UI.Page { string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } //find button protected void Button1_Click(object sender, EventArgs e) { getVehicleById(); } //update button protected void Button2_Click(object sender, EventArgs e) { if (checkIfVehicleIdExists()) { UpdateVehicle(); Response.Redirect("tr_vehicle.aspx"); } else { Response.Write("<script>alert('VEhicle ID is does not exists');</script>"); } } //user define function //check if vehicle ID already Exists bool checkIfVehicleIdExists() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("SELECT * from tr_vehicle where vehicle_id='" + TextBox1.Text.Trim() + "';", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count >= 1) { return true; } else { return false; } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); return false; } } //Update Vehicle function void UpdateVehicle() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("UPDATE tr_vehicle SET vehicle_id=@vehicle_id, vehicle_number=@vehicle_number, color=@color, transmission=@transmission, type=@type WHERE vehicle_id='" + TextBox1.Text.Trim() + "'", con); cmd.Parameters.AddWithValue("@vehicle_id", TextBox1.Text.Trim()); cmd.Parameters.AddWithValue("@vehicle_number", TextBox2.Text.Trim()); cmd.Parameters.AddWithValue("@color", TextBox3.Text.Trim()); cmd.Parameters.AddWithValue("@transmission", DropDownList2.SelectedItem.Value); cmd.Parameters.AddWithValue("@type", DropDownList1.SelectedItem.Value); cmd.ExecuteNonQuery(); SqlCommand cmd2 = new SqlCommand("UPDATE tr_payments SET amount=@amount, date=@date WHERE transport_id='" + TextBox1.Text.Trim() + "'", con); cmd2.Parameters.AddWithValue("@transport_id", TextBox1.Text.Trim()); cmd2.Parameters.AddWithValue("@amount", TextBox8.Text.Trim()); cmd2.Parameters.AddWithValue("@date", TextBox9.Text.Trim()); cmd2.ExecuteNonQuery(); con.Close(); Response.Write("<script>alert('TRANSPORTATION UPDATED SCCESSFULLY');</script>"); //clear placeholders after updated ClearPlaceHolders(); //real time data hadle //GridView1.DataBind(); } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } //Auto fill the placeholders by clicking find button void getVehicleById() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("SELECT * from tr_vehicle where vehicle_id='" + TextBox1.Text.Trim() + "';", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count >= 1) { TextBox2.Text = dt.Rows[0]["vehicle_number"].ToString(); TextBox3.Text = dt.Rows[0]["color"].ToString(); DropDownList2.SelectedValue = dt.Rows[0]["transmission"].ToString().Trim(); DropDownList1.SelectedValue = dt.Rows[0]["type"].ToString().Trim(); } else { Response.Write("<script>alert('Invalid Transport ID');</script>"); } SqlCommand cmd2 = new SqlCommand("SELECT * from tr_payments where transport_id='" + TextBox1.Text.Trim() + "';", con); SqlDataAdapter da2 = new SqlDataAdapter(cmd2); DataTable dt2 = new DataTable(); da2.Fill(dt2); if (dt2.Rows.Count >= 1) { TextBox8.Text = dt2.Rows[0]["amount"].ToString(); TextBox9.Text = dt2.Rows[0]["date"].ToString(); } else { Response.Write("<script>alert('Invalid Vehicle ID');</script>"); } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } //Clear form Placeholders after the action's void ClearPlaceHolders() { TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; DropDownList2.SelectedValue = "Select"; DropDownList1.SelectedValue = "Select"; TextBox8.Text = ""; TextBox9.Text = ""; } } }
#region LICENSE // Funkshun.Core 1.0.0.0 // // Copyright 2011, see AUTHORS.txt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; namespace Funkshun.Core.Extensions { /// <summary> /// Static (extension) class for extending the types: /// <see cref="IResult"/>, /// <see cref="IResult{TResult}"/> /// </summary> public static partial class FunctionResultExtensions { /// <summary> /// Calls a succes action when the function result does not contain errors. /// </summary> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successAction">The action to call when there are no errors.</param> /// <exception cref="ArgumentNullException">Thrown when the parameter is null.</exception> public static void OnSuccess(this IResult functionResult, Action successAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (!functionResult.HasErrors()) { successAction.Invoke(); } } /// <summary> /// Calls a succes action when the function result does not contain errors. /// </summary> /// <typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successAction">The action to call when there are no errors.</param> /// <exception cref="ArgumentNullException">Thrown when the parameter is null.</exception> public static void OnSuccess<TFunctionReturnType>(this IResult<TFunctionReturnType> functionResult, Action<TFunctionReturnType> successAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult.ReturnValue); } } /// <summary> /// Calls a succes action when the function result does not contain errors. /// </summary> /// <typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successAction">The action to call when there are no errors.</param> /// <exception cref="ArgumentNullException">Thrown when the parameter is null.</exception> public static void OnSuccess<TFunctionReturnType>(this IResult<TFunctionReturnType> functionResult, Action<IResult<TFunctionReturnType>> successAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult); } } /// <summary> /// Calls a succes action when the function result does not contain errors. /// </summary> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successAction">The action to call when there are no errors.</param> /// <exception cref="ArgumentNullException">Thrown when the parameter is null.</exception> public static void OnSuccess(this IResult functionResult, Action<IResult> successAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult); } } /// <summary> /// Calls a succes func when the function result does not contain errors. /// </summary> /// <typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> /// <typeparam name="TNewResult">The type of the result of the func.</typeparam> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successFunction">The func to call when there are no errors.</param> /// <returns>A type of TNewResult which is returned by the func.</returns> /// <exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static TNewResult OnSuccess<TFunctionReturnType, TNewResult>( this IResult<TFunctionReturnType> functionResult, Func<IResult<TFunctionReturnType>, TNewResult> successFunction) { if (successFunction == null) throw new ArgumentNullException("successFunction"); return !functionResult.HasErrors() ? successFunction(functionResult) : default(TNewResult); } /// <summary> /// Calls a succes func when the function result does not contain errors. /// </summary> /// <typeparam name="TNewResult">The type of the result of the func.</typeparam> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successFunction">The func to call when there are no errors.</param> /// <returns>A type of TNewResult which is returned by the func.</returns> ///<exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static TNewResult OnSuccess<TNewResult>(this IResult functionResult, Func<IResult, TNewResult> successFunction) { if (successFunction == null) throw new ArgumentNullException("successFunction"); return !functionResult.HasErrors() ? successFunction(functionResult) : default(TNewResult); } //----- /// <summary> /// Calls a succes action when the function result does not contain errors otherwise the else action. /// </summary> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successAction">The action to call when there are no errors.</param> /// <param name="elseAction">The action to call when there are errors.</param> ///<exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static void OnSuccess(this IResult functionResult, Action successAction, Action elseAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (elseAction == null) throw new ArgumentNullException("elseAction"); if (!functionResult.HasErrors()) { successAction.Invoke(); } else { elseAction.Invoke(); } } ///<summary> /// Calls a succes action when the function result does not contain errors otherwise the else action. ///</summary> ///<param name="functionResult">The function result to check for errors.</param> ///<param name="successAction">The action to call when there are no errors.</param> ///<param name="elseAction">The action to call when there are errors.</param> ///<typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> ///<exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static void OnSuccess<TFunctionReturnType>(this IResult<TFunctionReturnType> functionResult, Action<TFunctionReturnType> successAction, Action<TFunctionReturnType> elseAction ) { if (successAction == null) throw new ArgumentNullException("successAction"); if (elseAction == null) throw new ArgumentNullException("elseAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult.ReturnValue); } else { elseAction.Invoke(functionResult.ReturnValue); } } /// <summary> /// Calls a succes action when the function result does not contain errors otherwise the else action. /// </summary> ///<param name="functionResult">The function result to check for errors.</param> ///<param name="successAction">The action to call when there are no errors.</param> ///<param name="elseAction">The action to call when there are errors.</param> ///<typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> /// <exception cref="ArgumentNullException">Thrown when the parameter is null.</exception> public static void OnSuccess<TFunctionReturnType>(this IResult<TFunctionReturnType> functionResult, Action<IResult<TFunctionReturnType>> successAction, Action<IResult<TFunctionReturnType>> elseAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (elseAction == null) throw new ArgumentNullException("elseAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult); } else { elseAction.Invoke(functionResult); } } /// <summary> /// Calls a succes action when the function result does not contain errors otherwise the else action. /// </summary> ///<param name="functionResult">The function result to check for errors.</param> ///<param name="successAction">The action to call when there are no errors.</param> ///<param name="elseAction">The action to call when there are errors.</param> ///<exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static void OnSuccess(this IResult functionResult, Action<IResult> successAction, Action<IResult> elseAction) { if (successAction == null) throw new ArgumentNullException("successAction"); if (elseAction == null) throw new ArgumentNullException("elseAction"); if (!functionResult.HasErrors()) { successAction.Invoke(functionResult); } else { elseAction.Invoke(functionResult); } } /// <summary> /// Calls a succes func when the function result does not contain errors otherwise the else func. /// </summary> /// <typeparam name="TNewResult">The type of the result of the func.</typeparam> ///<typeparam name="TFunctionReturnType">The type of the return value of the function result.</typeparam> ///<param name="functionResult">The function result to check for errors.</param> /// <param name="successFunction">The func to call when there are no errors.</param> ///<param name="elseFunction">The func to call when there are errors.</param> ///<returns>A type of TNewResult which is returned by the func.</returns> ///<exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static TNewResult OnSuccess<TFunctionReturnType, TNewResult>( this IResult<TFunctionReturnType> functionResult, Func<IResult<TFunctionReturnType>, TNewResult> successFunction, Func<IResult<TFunctionReturnType>, TNewResult> elseFunction ) { if (successFunction == null) throw new ArgumentNullException("successFunction"); if (elseFunction == null) throw new ArgumentNullException("elseFunction"); return !functionResult.HasErrors() ? successFunction(functionResult) : elseFunction(functionResult); } /// <summary> /// Calls a succes func when the function result does not contain errors otherwise the else func. /// </summary> /// <typeparam name="TNewResult">The type of the result of the func.</typeparam> /// <param name="functionResult">The function result to check for errors.</param> /// <param name="successFunction">The func to call when there are no errors.</param> /// <param name="elseFunction">The func to call when there are errors.</param> /// <returns>A type of TNewResult which is returned by the func.</returns> /// <exception cref="ArgumentNullException">Thrown when the parameters are null.</exception> public static TNewResult OnSuccess<TNewResult>(this IResult functionResult, Func<IResult, TNewResult> successFunction, Func<IResult, TNewResult> elseFunction) { if (successFunction == null) throw new ArgumentNullException("successFunction"); if (elseFunction == null) throw new ArgumentNullException("elseFunction"); return !functionResult.HasErrors() ? successFunction(functionResult) : elseFunction(functionResult); } } }
using System.Threading.Tasks; using System.Collections.Generic; using Notify.Interfaces; using Sfa.Poc.ResultsAndCertification.Notifications.Configuration; using Sfa.Poc.ResultsAndCertification.Notifications.Interface; namespace Sfa.Poc.ResultsAndCertification.Notifications.Services { public class NotificationService : INotificationService { private readonly ResultsAndCertificationConfiguration _configuration; private readonly IAsyncNotificationClient _notificationClient; public NotificationService(ResultsAndCertificationConfiguration configuration, IAsyncNotificationClient notificationClient) { _configuration = configuration; _notificationClient = notificationClient; } public async Task SendNotification(string templateName, string toAddress, dynamic tokens) { var templateId = templateName == Constants.TlevelsQueryTemplateName ? Constants.TlevelsQueryTemplateId : ""; var personalisationTokens = new Dictionary<string, dynamic>(); foreach (var property in tokens.GetType().GetProperties()) { personalisationTokens[property.Name] = property.GetValue(tokens); } var emailNotificationResponse =await _notificationClient.SendEmailAsync( emailAddress: toAddress, templateId: templateId, personalisation: personalisationTokens); var result = emailNotificationResponse; } } }
//------------------------------------------------------------------------------ // <copyright file="InfoMarginFactory.cs" company="Company"> // Copyright (c) Company. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace SSMSX { /// <summary> /// Export a <see cref="IWpfTextViewMarginProvider"/>, which returns an instance of the margin for the editor to use. /// </summary> [Export(typeof(IWpfTextViewMarginProvider))] [Name(InfoMargin.MarginName)] [Order(After = PredefinedMarginNames.HorizontalScrollBar)] // Ensure that the margin occurs below the horizontal scrollbar [MarginContainer(PredefinedMarginNames.Bottom)] // Set the container to the bottom of the editor window [ContentType("sql")] // Show this margin for all text-based types [TextViewRole(PredefinedTextViewRoles.Interactive)] internal sealed class InfoMarginFactory : IWpfTextViewMarginProvider { #region IWpfTextViewMarginProvider /// <summary> /// Creates an <see cref="IWpfTextViewMargin"/> for the given <see cref="IWpfTextViewHost"/>. /// </summary> /// <param name="wpfTextViewHost">The <see cref="IWpfTextViewHost"/> for which to create the <see cref="IWpfTextViewMargin"/>.</param> /// <param name="marginContainer">The margin that will contain the newly-created margin.</param> /// <returns>The <see cref="IWpfTextViewMargin"/>. /// The value may be null if this <see cref="IWpfTextViewMarginProvider"/> does not participate for this context. /// </returns> public IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer) { return new InfoMargin(wpfTextViewHost.TextView); } #endregion } }
using System; namespace P01.HarvestingFields { class Program { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace SmartLinkCalculator { /// <summary> /// Interaction logic for DeviceButtonAsFunction.xaml /// </summary> public partial class DeviceButtonAsFunction : Button,IDeviveButton { public int DevicePower { set; get; } public DeviceButtonAsFunction() { InitializeComponent(); } public DeviceButtonAsFunction Clone() { DeviceButtonAsFunction fun = new DeviceButtonAsFunction(); fun.Code.Content = this.Code.Content; fun.Tag1.Content = this.Tag1.Content; fun.Tag2.Content = this.Tag2.Content; fun.Tag3.Content = this.Tag3.Content; fun.Tag4.Content = this.Tag4.Content; fun.Tag5.Content = this.Tag5.Content; fun.DevicePower = this.DevicePower; fun.Power.Content = this.Power.Content; return fun; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Les7Exercise1 { //Сергей в коде встречаются одинаковые наборы строк, напримир: // lblCount.Text = "0"; // count = 0; // lblNumber.Text = "1"; // numbers.Clear(); // numbers.Push(1); // Стоит ли их обединять в какой либо метод? //Ронжин Л. // а) Добавить в программу «Удвоитель» подсчёт количества отданных команд удвоителю. // б) Добавить меню и команду «Играть». При нажатии появляется сообщение, //какое число должен получить игрок.Игрок должен получить это число за минимальное //количество ходов. // в) * Добавить кнопку «Отменить», которая отменяет последние ходы. //Используйте обобщенный класс Stack. // Вся логика игры должна быть реализована в классе с удвоителем. static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FWF_Udvoitel()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Manual : MonoBehaviour { void Start() { Cursor.visible = false; } void Update() { if (Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadScene("Menu"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MinistryPlatform.Translation.Models.DTO; namespace MinistryPlatform.Translation.Repositories.Interfaces { public interface IKioskRepository { MpKioskConfigDto GetMpKioskConfigByIdentifier(Guid kioskConfigId); MpPrinterMapDto GetPrinterMapById(int printerMapId); } }
using Knjizara.Models; // dodato da bi se koristilo RacunMenadzer using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Knjizara.Controllers { [Autorizacija(Roles = "Menadzer")] public class MenadzerRacunController : Controller { // GET: MenadzerRacunView public ActionResult MenadzerRacunView() { IzborZaposlenog(); return View(); } // metoda koja popunjava dropdownlist podacima iz tabele Korisnik public void IzborZaposlenog() { SelectList sviZaposleni = RacunMenadzer.IzaberiZaposleni(); if (sviZaposleni != null) { ViewBag.podaciZaposleni = sviZaposleni; } } // metoda koja prikazuje racune zaposlenog izabranog iz dropdownlist [HttpPost] public ActionResult RacuniZaposlenog(FormCollection forma) { IzborZaposlenog(); TempData["zaposleni"] = forma["listaZaposleni"]; return View("MenadzerRacunView"); } } }
namespace Web.Models { public class BlogViewModel { public string Author { get; set; } public int BlogId { get; set; } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BList { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { static List<Person> people = new List<Person>(); private static string dir = @"c:\blacklist\"; private string serializationFile = System.IO.Path.Combine(dir, "blacklist.bin"); public MainWindow() { if (File.Exists(serializationFile)) { OpenFile(); } else { DirectoryInfo di = Directory.CreateDirectory(dir); } InitializeComponent(); } private void Home_Click(object sender, RoutedEventArgs e) { var window = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault(); window.Show(); } private void Search_Click(object sender, RoutedEventArgs e) { Window1 win2 = new Window1(); OpenFile(); win2.populateList(people); win2.Show(); } private void Blacklist_Click(object sender, RoutedEventArgs e) { if ((string.IsNullOrEmpty(textFirstName.Text)) || (string.IsNullOrEmpty(textLastName.Text)) || (string.IsNullOrEmpty(textPhoneNumber.Text)) || (string.IsNullOrEmpty(textBlacklist.Text)) || (!Regex.IsMatch(textPhoneNumber.Text, @"^[0-9]{10}$"))) { MessageBox.Show("Please check to see if the inputs are empty. Ensure that the phone number follows a format of: 5550001234"); } else { Person result = people.Find(person => person.FirstName.Equals(textFirstName.Text) && person.LastName.Equals(textLastName.Text) && person.PhoneNumber.Equals(textPhoneNumber.Text)); if (result == null) { //Not Duplicate Person person = new Person { FirstName = textFirstName.Text, LastName = textLastName.Text, PhoneNumber = textPhoneNumber.Text, Reason = textBlacklist.Text }; people.Add(person); MessageBox.Show(textFirstName.Text + " " + textLastName.Text + " was successfully blacklisted."); textFirstName.Text = String.Empty; textLastName.Text = String.Empty; textPhoneNumber.Text = String.Empty; textBlacklist.Text = String.Empty; WriteFile(); } else { //Dupe MessageBox.Show("That person is already blacklisted!"); } } } private void WriteFile() { //serialize using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, people); stream.Close(); } } private void OpenFile() { //deserialize using (Stream stream = File.Open(serializationFile, FileMode.Open)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); people = (List<Person>)bformatter.Deserialize(stream); stream.Close(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cutting : MonoBehaviour { [SerializeField] private Transform cutLinePrefab; [SerializeField] private Transform cutItems; [SerializeField] private Transform cookPot; private int currCutPoint; private int currCutItem; private bool end_minigame; public float knifeSpeed = 0.01f; private Vector3 initialKnifePos; private int score; Timer timer; // Use this for initialization void Start () { //initialize game object pointers currCutItem = 0; currCutPoint = 0; //Display 1st item cutItems.GetChild(currCutItem).gameObject.SetActive(true); score = 0; end_minigame = false; initialKnifePos = this.transform.position; // Create the timer timer = new Timer(); // Register for the events timer.OnTimeUp += HandleTimeUp; timer.OnSecondsChanged += HandleSecondsChanged; // Start the timer timer.SetTimer(30); timer.StartTimer(); } public int GetScore() { return score; } void HandleTimeUp() { //end game Debug.Log("Kinves Down!"); //end_minigame = true; //GameManager.Instance.CookingScore += score; //LevelManager.Instance.LoadScene(Level.MainGame); //add transition to main game from minigame } void HandleSecondsChanged(int secondsRemaining) { //Debug.Log("Seconds Remaining: " + secondsRemaining); } // Update is called once per frame void FixedUpdate () { timer.Update(); //Debug.Log(score); //Move knife across screen if (this.transform.position.x < 2) { this.transform.position += new Vector3(knifeSpeed, 0); } else { this.transform.position = initialKnifePos; } //Cut Item on mouse click, if there is an item on the cut board (i.e. !end_minigame) if (Input.GetMouseButtonDown(0) || Input.GetKeyDown("space")) { if (!end_minigame) { // Check if knife is over item if (transform.position.x > cutItems.GetChild(currCutItem).GetComponent<SpriteRenderer>().bounds.min.x && transform.position.x < cutItems.GetChild(currCutItem).GetComponent<SpriteRenderer>().bounds.max.x) { //increment score score += 1; //Create new cut line Transform newCut = Instantiate(cutLinePrefab); newCut.position = transform.position; //Make it a child of the item newCut.parent = cutItems.GetChild(currCutItem).GetChild(1); //Get cut points Transform cutPoints = cutItems.GetChild(currCutItem).GetChild(0); //Child 0 should be the cut points cutItems.GetChild(currCutItem).GetChild(0).GetChild(currCutPoint).gameObject.SetActive(false); if (newCut.position.x >= cutPoints.GetChild(currCutPoint).position.x - 0.02f && newCut.position.x <= cutPoints.GetChild(currCutPoint).position.x + 0.02f) { //increment score for accuracy score += 1; } //next cut point currCutPoint++; //check if item fully sliced if (currCutPoint == cutPoints.childCount) { //Hide chopped up items cutItems.GetChild(currCutItem).gameObject.SetActive(false); cutItems.GetChild(currCutItem).GetChild(2).parent = cookPot; cookPot.GetChild(currCutItem).localPosition = new Vector3(0, 0, 0); //show diced items in pot cookPot.GetChild(currCutItem).gameObject.SetActive(true); //next item currCutItem++; //check if last item if (currCutItem == cutItems.childCount) { //end game end_minigame = true; GameManager.Instance.CookingScore += score; if(score > 30) { GameManager.Instance.CurrentNPCScript.ChangeMentalState((int)GameManager.Kindness.Best); } GameManager.Instance.CurrentNPCScript.ChangeMentalState((int)GameManager.Kindness.Good); Debug.Log(GameManager.Instance.CookingScore); GameManager.Instance.playedJon = true; LevelManager.Instance.LoadScene(Level.MainGame); //add transition to main game from minigame } else { //show next item to be cut cutItems.GetChild(currCutItem).gameObject.SetActive(true); currCutPoint = 0; } } } } } } }
using System.Collections.Generic; using DataAccess.Model; using KioskClient.Domain; namespace KioskClient { public interface IMainWindow { void NavigateToMovieDetails(Movie movie); void NavigateToMovieCatalog(); void NavigateToShowtimeList(Movie movie); void NavigateToAuditoriumMap(Showtime showtime); void NavigateBack(); void NavigateToCheckoutPage(Showtime showtime, IEnumerable<AuditoriumSeat> seats); void NavigateToThanksPage(); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SiteDataEnricher.cs" company="Jeroen Stemerdink"> // Copyright © 2019 Jeroen Stemerdink. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace EPi.Libraries.Logging.Serilog.Enrichers.Cms { using System; using EPiServer.Web; using global::Serilog.Core; using global::Serilog.Events; /// <summary> /// Class SiteDataEnricher. /// </summary> /// <seealso cref="ILogEventEnricher" /> public class SiteDataEnricher : ILogEventEnricher { /// <summary> /// The site identifier property name /// </summary> public const string SiteIdPropertyName = "SiteId"; /// <summary> /// The site name property name /// </summary> public const string SiteNamePropertyName = "SiteName"; /// <summary> /// The site URL property name /// </summary> public const string SiteUrlPropertyName = "SiteUrl"; /// <summary> /// Enrich the log event. /// </summary> /// <param name="logEvent">The log event to enrich.</param> /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) { return; } SiteDefinition siteDefinition = SiteDefinition.Current; if (!string.IsNullOrWhiteSpace(value: siteDefinition.Name)) { logEvent.AddPropertyIfAbsent( new LogEventProperty( name: SiteNamePropertyName, value: new ScalarValue(value: SiteDefinition.Current.Name))); } if (siteDefinition.Id != Guid.Empty) { logEvent.AddPropertyIfAbsent( new LogEventProperty( name: SiteIdPropertyName, value: new ScalarValue(value: SiteDefinition.Current.Id))); } if (siteDefinition.SiteUrl != null) { logEvent.AddPropertyIfAbsent( new LogEventProperty( name: SiteUrlPropertyName, value: new ScalarValue(value: SiteDefinition.Current.SiteUrl))); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlaneGenerator : MonoBehaviour { public GameObject Plane; int x, z; // Start is called before the first frame update void Start() { for (x = 0; x <= HomeDirector.width; x++) { for (z = 0; z <= HomeDirector.height; z++) { GameObject PlaneGen = Instantiate(Plane) as GameObject; PlaneGen.transform.position = new Vector3(x, 0, z); } } } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Futbol5.DAL.Repositories; using Futbol5.DAL.Infrastructure; using Futbol5.Entities; namespace Futbol5.ServiceAgent { public class CampeonatoService : ICampeonatoService { private ICampeonatoRepository repository; private IUnitOfWork unitOfWork; public CampeonatoService(ICampeonatoRepository repository, IUnitOfWork unitOfWork) { this.repository = repository; this.unitOfWork = unitOfWork; } public IEnumerable<Campeonato> ObtenerCampeonatos() { return repository.GetAll(); } public Campeonato AgregarCampeonato(Campeonato campeonato) { repository.Add(campeonato); SaveChanges(); return campeonato; } public Campeonato ObtenerCampeonatoPorId(int id) { return repository.GetById(id); } public Campeonato ModificarCampeonato(Campeonato campeonato) { repository.Update(campeonato); SaveChanges(); return campeonato; } public void EliminarCampeonato(int id) { var campeonato = repository.GetById(id); repository.Delete(campeonato); SaveChanges(); } public void SaveChanges() { unitOfWork.SaveChanges(); } } public interface ICampeonatoService { IEnumerable<Campeonato> ObtenerCampeonatos(); Campeonato AgregarCampeonato(Campeonato campeonato); Campeonato ObtenerCampeonatoPorId(int id); Campeonato ModificarCampeonato(Campeonato campeonato); void EliminarCampeonato(int campeonatoId); } }
using CoreSystems.Transition.Scripts; using UnityEngine; namespace CoreSystems.Menu.Scripts { public class PauseMenu : MonoBehaviour, IPauseMenu { public bool IsPaused { get; private set; } private GameObject _canvas; void Awake() { _canvas = transform.GetChild(0).gameObject; } void Start() { UnpauseGame(); } public void Toggle() { if (IsPaused) { UnpauseGame(); } else { PauseGame(); } } public void PauseGame() { Time.timeScale = 0; IsPaused = true; _canvas.SetActive(true); Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } public void UnpauseGame() { Time.timeScale = 1; IsPaused = false; _canvas.SetActive(false); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } public void Back() { UnpauseGame(); Cursor.lockState = CursorLockMode.None; Cursor.visible = true; LevelLoader.Instance.LoadLevel(Level.Menu); } } }
 namespace PhotonInMaze.Common.Controller { public interface IMazeConfiguration { int Columns { get; } int Rows { get; } int SecondsToStart { get; } MazeGenerationAlgorithm Algorithm { get; } float CellSideLength { get; } string Name { get; } IMazeGenerator GetGenerator(); } }
 namespace Fbtc.Domain.Entities { public class Endereco: EnderecoCep { public int EnderecoId { get; set; } public int PessoaId { get; set; } public string Numero { get; set; } public string Complemento { get; set; } public string TipoEndereco { get; set; } public string OrdemEndereco { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using gMediaTools.Extensions; using gMediaTools.Models; namespace gMediaTools.Services.AviSynth { public class AviSynthVfrToCfrConversionService { public string GetConvertVfrToCfrScript(List<VideoFrameInfo> videoFrameList, List<VideoFrameSection> videoFrameSections, decimal? targetVideoFrameRate = null) { // Check if we have been provided with a target frame rate if (!targetVideoFrameRate.HasValue) { // Find the most appropriate CFR frame rate targetVideoFrameRate = videoFrameList.GetNearestCfrFrameRate(); } // Calculate target duration decimal targetDuration = 1000.0m / targetVideoFrameRate.Value; // Define maximum frame range int maxFrameRound = 5; // Check for sections if (!videoFrameSections.Any()) { // If no sections, create a dummy section for the whole video videoFrameSections.Add( new VideoFrameSection() { StartFrameNumber = 0, EndFrameNumber = videoFrameList.Count - 1, Name = "wholeVideo" } ); } int sectionCounter = 0; decimal frameGlitch = 0.0m; decimal frameSectionGlitch = 0.0m; // Loop for every section foreach (VideoFrameSection section in videoFrameSections) { // Reset data just to be sure section.FramesToDelete.Clear(); section.FramesToDuplicate.Clear(); // Declare needed variables int currentSectionFrame = 0; decimal sectionStartTime = videoFrameList.FirstOrDefault(f => f.Number == section.StartFrameNumber).StartTime; int gatherStartFrame = section.StartFrameNumber; int gatherEndFrame = section.EndFrameNumber; decimal currentCheckTime = 0.0m; decimal currentShouldBeTime = 0.0m; decimal currentTimeDiff = 0.0m; // Check Section Name if (string.IsNullOrWhiteSpace(section.Name)) { // If no section name, set a default section.Name = $"Section{sectionCounter + 1}"; } // Loop for all the frames in the section for (int currentFrameNumber = section.StartFrameNumber; currentFrameNumber <= section.EndFrameNumber; currentFrameNumber++) { // Increase the current frame counter currentSectionFrame++; // Calculate the current time to check by removing the section start time currentCheckTime = videoFrameList.FirstOrDefault(f => f.Number == currentFrameNumber).EndTime - sectionStartTime; // Calculate the expected time based on the CFR duration currentShouldBeTime = (currentSectionFrame - section.FramesToDelete.Count + section.FramesToDuplicate.Count) * targetDuration; // Calculate the time difference currentTimeDiff = currentCheckTime - currentShouldBeTime; // Calculate how many frames off we are based on time diff and target duration frameGlitch = currentTimeDiff / targetDuration; // Add the cumulative frame glitch frameGlitch += frameSectionGlitch; // Check if we have more than 1 frame glitch if (frameGlitch > -1.0m && frameGlitch < 1.0m) { continue; } // Check if we need to delete or duplicate frames if (frameGlitch <= -1.0m) { // Negative frame glitch, we need to delete // Decide how many frames we need to delete // We use the lowest possible number of frames // e.g -1.9 => 1 frame to delete int numberOfFramesToDelete = -Convert.ToInt32(Math.Ceiling(frameGlitch)); // Set the current frame as the end range frame gatherEndFrame = currentFrameNumber; // Check frame range based on the previously set start frame if (gatherEndFrame - gatherStartFrame > maxFrameRound) { // We exceeded the max range of frames per round // Reevaluate the start frame gatherStartFrame = gatherEndFrame - maxFrameRound; } // Delete frames // Update frame section glitch frameSectionGlitch = frameGlitch + DeleteFrames(videoFrameList, section, gatherStartFrame, gatherEndFrame, numberOfFramesToDelete); } else if (frameGlitch >= 1.0m) { // Positive frame glitch, we need to duplicate // Decide how many frames we need to duplicate // We use the lowest possible number of frames // e.g 1.9 => 1 frame to duplicate int numberOfFramesToDuplicate = Convert.ToInt32(Math.Floor(frameGlitch)); // Set the current frame as the end range frame gatherEndFrame = currentFrameNumber; // Check frame range based on the previously set start frame if (gatherEndFrame - gatherStartFrame > maxFrameRound) { // We exceeded the max range of frames per round // Reevaluate the start frame gatherStartFrame = gatherEndFrame - maxFrameRound; } // Duplicate frames // Update frame section glitch frameSectionGlitch = frameGlitch - DuplicateFrames(videoFrameList, section, gatherStartFrame, gatherEndFrame, numberOfFramesToDuplicate); } // Set the gather start frame if (currentFrameNumber + 1 > videoFrameList.Last().Number) { gatherStartFrame = videoFrameList.Last().Number; } else { gatherStartFrame = currentFrameNumber + 1; } } // Increase the section counter sectionCounter++; // Set the frame Section Glitch frameSectionGlitch = frameGlitch; } StringBuilder sb = new StringBuilder(); // Assume framerate sb.AppendFormat("AssumeFPS({0}, false)", targetVideoFrameRate.Value.ToString("##0.000###", CultureInfo.InvariantCulture)); sb.AppendLine(); // Write the delete and duplicate frame for each section foreach (VideoFrameSection section in videoFrameSections) { sb.AppendLine(KienzanString(section)); } // Write the last line to concat the sections sb.AppendFormat("last = {0}", string.Join(" + ", videoFrameSections.Select(s => s.Name))); sb.AppendLine(); return sb.ToString(); } private int DuplicateFrames(List<VideoFrameInfo> allFrames, VideoFrameSection videoFrameSection, int startFrame, int endFrame, int numberOfFramesToDuplicate) { // Create a temporary list with only the frame range List<VideoFrameInfo> list = allFrames.Where(f => f.Number >= startFrame && f.Number <= endFrame).ToList(); IOrderedEnumerable<VideoFrameInfo> orderedList; // if the list is CFR then sort by frame difference, else by frame numer if (list.IsCFR()) { // Sort all frames by difference orderedList = list.OrderBy(f => f.DifferencePercentageFromPreviousFrame); //list.Sort(VideoFrameList.SortType.ByFrameDifference, VideoFrameList.SortOrder.Ascending); } else { // Sort the first addFrames by frame number orderedList = list.OrderBy(f => f.Number); //list.Sort(VideoFrameList.SortType.ByFrameNumber, VideoFrameList.SortOrder.Ascending); } // Finally sort all the frames by duration orderedList = orderedList.ThenByDescending(f => f.Duration); //list.Sort(VideoFrameList.SortType.ByDuration, VideoFrameList.SortOrder.Descending); // Check if the muber of frames to duplicate is more than the range of frames if (numberOfFramesToDuplicate > endFrame - startFrame + 1) { // We have to duplicate more frames than we have // That means we are going to duplicate some frames more than once int framesDuppedCounter = 0; while (framesDuppedCounter < numberOfFramesToDuplicate) { foreach (var vf in list) { videoFrameSection.FramesToDuplicate.Add(vf); framesDuppedCounter++; } } } else { // We have to duplicate less frames than the ones we have // Select the first numberOfFramesToDuplicate frames from the ordered list for (int i = 0; i < numberOfFramesToDuplicate; i++) { videoFrameSection.FramesToDuplicate.Add(list[i]); } } return numberOfFramesToDuplicate; } private int DeleteFrames(List<VideoFrameInfo> allFrames, VideoFrameSection videoFrameSection, int startFrame, int endFrame, int numberOfFrameToDelete) { // Create a temporary list with only the frame range List<VideoFrameInfo> list = allFrames.Where(f => f.Number >= startFrame && f.Number <= endFrame).ToList(); IOrderedEnumerable<VideoFrameInfo> orderedList; // if the list is CFR then sort by frame numer, else by frame difference if (list.IsCFR()) { // Sort the first cutFrames by frame number orderedList = list.OrderBy(f => f.Number); //list.Sort(VideoFrameList.SortType.ByFrameNumber, VideoFrameList.SortOrder.Ascending); } else { // Sort all frames by difference orderedList = list.OrderBy(f => f.DifferencePercentageFromPreviousFrame); //list.Sort(VideoFrameList.SortType.ByFrameDifference, VideoFrameList.SortOrder.Ascending); } // Finally sort all the frames by duration orderedList = orderedList.ThenByDescending(f => f.Duration); //list.Sort(VideoFrameList.SortType.ByDuration, VideoFrameList.SortOrder.Descending); // Apply the order to the list list = orderedList.ToList(); // Check if the muber of frames to delete is more than the range of frames if (numberOfFrameToDelete > endFrame - startFrame + 1) { // We have to delete more frames than we have // That means we are going to delete all the frames from the list // which are going to be less than the numberOfFrameToDelete foreach (var vf in list) { videoFrameSection.FramesToDelete.Add(vf); } return list.Count; } else { // We have to delete less frames than the ones we have // Select the first numberOfFrameToDelete frames from the ordered list for (int i = 0; i < numberOfFrameToDelete; i++) { videoFrameSection.FramesToDelete.Add(list[i]); } return numberOfFrameToDelete; } } private string KienzanString(VideoFrameSection videoFrameSection) { // Create the string builder StringBuilder sb = new StringBuilder(); // Write the comment line for the section sb.AppendFormat("#{0} FramesDeleted : {1} FramesDuplicated : {2}", videoFrameSection.Name, videoFrameSection.FramesToDelete.Count, videoFrameSection.FramesToDuplicate.Count); sb.AppendLine(); // Write the first trim sb.AppendFormat("{0} = trim(0, {1})", videoFrameSection.Name, videoFrameSection.EndFrameNumber); sb.AppendLine(); // Write the delete frames (if any) if (videoFrameSection.FramesToDelete.Any()) { // Ensure sorted list by frame number // Descending sorting order to avoid clumsy remapping later var framesToDeleteOrdered = videoFrameSection.FramesToDelete.OrderByDescending(f => f.Number); // Create counter int numberOfFramesDeleted = 0; // Write filter first sb.AppendFormat("{0} = DeleteFrame({0}", videoFrameSection.Name); foreach (var vf in framesToDeleteOrdered) { // Check if we already appended 900 frames (AviSynth limitation) if (numberOfFramesDeleted == 900) { // Close the previous filter sb.AppendLine(")"); // Begin a new one sb.AppendFormat("{0} = DeleteFrame({0}", videoFrameSection.Name); // Write the frame number sb.AppendFormat(", {0}", vf.Number); // Reset the counter numberOfFramesDeleted = 1; } else { // Write the frame number sb.AppendFormat(", {0}", vf.Number); // Increase the counter numberOfFramesDeleted++; } } // Close the last filter sb.AppendLine(")"); } // Write the remapped duplicate frames (if any) if (videoFrameSection.FramesToDuplicate.Any()) { // Create new remapped list of duplicate frames // First Delete the frames // So remap the frames to duplicate var remappedFramesToDuplicate = GetRemappedFramesToDuplicate(videoFrameSection); // Ensure sorted list by frame number // Descending sorting order to avoid clumsy remapping later remappedFramesToDuplicate = remappedFramesToDuplicate.OrderByDescending(f => f.Number).ToList(); // Create counter int numberOfFramesDuplicated = 0; // Write filter first sb.AppendFormat("{0} = DuplicateFrame({0}", videoFrameSection.Name); foreach (var vf in remappedFramesToDuplicate) { // Check if we already appended 900 frames (AviSynth limitation) if (numberOfFramesDuplicated == 900) { // Close the previous filter sb.AppendLine(")"); // Begin a new one sb.AppendFormat("{0} = DuplicateFrame({0}", videoFrameSection.Name); // Write the frame number sb.AppendFormat(", {0}", vf.Number); // Reset the counter numberOfFramesDuplicated = 1; } else { // Write the frame number sb.AppendFormat(", {0}", vf.Number); // Increase the counter numberOfFramesDuplicated++; } } // Close the last filter sb.AppendLine(")"); } // If section starts from the first video frame (framestart = 0) then there is no reason for the final trim if (videoFrameSection.StartFrameNumber > 0) { // Write the final trim sb.AppendFormat("{0} = trim({0}, {1}, 0)", videoFrameSection.Name, videoFrameSection.StartFrameNumber); sb.AppendLine(); } return sb.ToString(); } private enum VideoFrameProcessType { Delete, Duplicate } private class VideoFrameInfoWithProcessType { public VideoFrameInfo VideoFrameInfo { get; set; } public VideoFrameProcessType VideoFrameProcessType { get; set; } } public List<VideoFrameInfo> GetRemappedFramesToDuplicate(VideoFrameSection videoFrameSection) { // Merge the frame lists List<VideoFrameInfoWithProcessType> mergeList = videoFrameSection.FramesToDuplicate.Select( f => new VideoFrameInfoWithProcessType { VideoFrameInfo = f, VideoFrameProcessType = VideoFrameProcessType.Duplicate } ).ToList() .Concat( videoFrameSection.FramesToDelete.Select( f => new VideoFrameInfoWithProcessType { VideoFrameInfo = f, VideoFrameProcessType = VideoFrameProcessType.Delete } ).ToList() ).ToList(); // Sort the merge list by frame number mergeList = mergeList.OrderBy(f => f.VideoFrameInfo.Number).ToList(); // Create new remapped list of duplicate frames List<VideoFrameInfo> remappedFramesToDuplicate = new List<VideoFrameInfo>(); // Frames int framesDeletedSoFar = 0; foreach (var vf in mergeList) { if (vf.VideoFrameProcessType == VideoFrameProcessType.Delete) { // Increase the counter framesDeletedSoFar++; continue; } else if (vf.VideoFrameProcessType == VideoFrameProcessType.Duplicate) { // Remap the frame number // Add it to the remapped list remappedFramesToDuplicate.Add( new VideoFrameInfo { Number = vf.VideoFrameInfo.Number - framesDeletedSoFar, StartTime = vf.VideoFrameInfo.StartTime, Duration = vf.VideoFrameInfo.Duration } ); } } return remappedFramesToDuplicate; } } }
using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.IO; using System; [CustomEditor(typeof(GameSystem), true)] [CanEditMultipleObjects] public class GameSystemEditor : Editor { #region Static private static SceneAsset FindSceneInEditorBuildSettings(string name) { if (string.IsNullOrEmpty(name)) return null; foreach (var editorScene in EditorBuildSettings.scenes) { if (Path.GetFileNameWithoutExtension(editorScene.path) == name) return AssetDatabase.LoadAssetAtPath(editorScene.path, typeof(SceneAsset)) as SceneAsset; } Debug.LogWarningFormat("Scene [{0}] cannot be used. You must first add this scene to the 'Scenes in the Build' in the project build settings.", name); return null; } #endregion #region Properties private SerializedProperty splashGraphicProperty; private SerializedProperty fadeGraphicProperty; private SerializedProperty fadeDurationProperty; private SerializedProperty loadingSceneNameProperty; private SerializedProperty hudSceneNameProperty; private SerializedProperty menuSceneNameProperty; private SerializedProperty creditsSceneNameProperty; private SerializedProperty levelSceneNameProperty; private ReorderableList levelList; #endregion #region Labels private GUIContent splashGraphicLabel; private GUIContent fadeGraphicLabel; private GUIContent fadeDurationLabel; private GUIContent loadingSceneNameLabel; private GUIContent hudSceneNameLabel; private GUIContent menuSceneNameLabel; private GUIContent creditsSceneNameLabel; private GUIContent levelSceneLabel; #endregion #region Editor void OnEnable() { // Properties splashGraphicProperty = serializedObject.FindProperty("splashGraphic"); fadeGraphicProperty = serializedObject.FindProperty("fadeGraphic"); fadeDurationProperty = serializedObject.FindProperty("fadeDuration"); loadingSceneNameProperty = serializedObject.FindProperty("loadingSceneName"); hudSceneNameProperty = serializedObject.FindProperty("hudSceneName"); menuSceneNameProperty = serializedObject.FindProperty("menuSceneName"); creditsSceneNameProperty = serializedObject.FindProperty("creditsSceneName"); levelSceneNameProperty = serializedObject.FindProperty("levelSceneName"); levelList = new ReorderableList(serializedObject, levelSceneNameProperty); levelList.elementHeight = 16; // The list uses a default 16x16 icon. Other sizes make it stretch. levelList.drawHeaderCallback = LevelListDrawHeader; levelList.drawElementCallback = LevelListDrawChild; // Labels splashGraphicLabel = new GUIContent("Splash Graphic"); fadeGraphicLabel = new GUIContent("Fade Graphic"); fadeDurationLabel = new GUIContent("Fade Duration"); loadingSceneNameLabel = new GUIContent("Loading Screen"); hudSceneNameLabel = new GUIContent("HUD"); menuSceneNameLabel = new GUIContent("Menu"); creditsSceneNameLabel = new GUIContent("Credits"); levelSceneLabel = new GUIContent(); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginDisabledGroup(Application.isPlaying); ShowSplash(); ShowFade(); ShowScenes(); EditorGUI.EndDisabledGroup(); serializedObject.ApplyModifiedProperties(); } #endregion private void ShowSplash() { EditorGUILayout.PropertyField(splashGraphicProperty, splashGraphicLabel); } private void ShowFade() { EditorGUILayout.PropertyField(fadeGraphicProperty, fadeGraphicLabel); EditorGUILayout.PropertyField(fadeDurationProperty, fadeDurationLabel); } private void ShowScene(SerializedProperty property, GUIContent label, Rect? rect = null) { var obj = FindSceneInEditorBuildSettings(property.stringValue); EditorGUI.BeginChangeCheck(); var scene = (rect == null) ? EditorGUILayout.ObjectField(label, obj, typeof(SceneAsset), false) : EditorGUI.ObjectField(rect.Value, label, obj, typeof(SceneAsset), false); if (EditorGUI.EndChangeCheck()) { if (scene == null) { property.stringValue = string.Empty; } else { string value = scene.name; if (value != property.stringValue) { if (FindSceneInEditorBuildSettings(value) != null) property.stringValue = value; } } } } private void ShowScenes() { ShowScene(loadingSceneNameProperty, loadingSceneNameLabel); ShowScene(hudSceneNameProperty, hudSceneNameLabel); ShowScene(menuSceneNameProperty, menuSceneNameLabel); ShowScene(creditsSceneNameProperty, creditsSceneNameLabel); { float labelWidth = EditorGUIUtility.labelWidth; try { EditorGUIUtility.labelWidth = 30; levelList.DoLayoutList(); } finally { EditorGUIUtility.labelWidth = labelWidth; } } } #region Level List Callbacks private void LevelListDrawHeader(Rect headerRect) { GUI.Label(headerRect, "Levels"); } private void LevelListDrawChild(Rect r, int index, bool isActive, bool isFocused) { SerializedProperty element = levelSceneNameProperty.GetArrayElementAtIndex(index); levelSceneLabel.text = string.Format("{0}:", index); ShowScene(element, levelSceneLabel, r); } #endregion }
using System; using System.ComponentModel; using System.Windows.Forms; namespace SharpMap.Extensions { public partial class GridConversionDialog : Form { public GridConversionDialog() { InitializeComponent(); this.convertTabPage.Text = "Convert"; this.resampleTabPage.Text = "Resample"; this.attributeSelectionGroupBox.Text = "Destination attributes"; this.inputFileButton.Text = "Browse .."; this.outputFileButton.Text = "Browse .."; this.inputFileLabel.Text = "File name"; this.outputFileLabel.Text = "Destination path"; this.dataTypeComboBox.DataSource = new BindingList<string> { "Byte (8 bits)", "Integer (16 bits)", "Single (32 bits)", "Double(64 bits)" }; this.dataTypeLabel.Text = "Data type"; this.blockWidthLabel.Text = "Block width"; this.validCellsLabel.Text = "Nr valid cells"; this.generateStatisticsLabel.Text = "Generate statistics"; this.optionLabel.Text = "Option"; generateStatisticsCheckBox.Text = ""; startLabel.Text = "Start"; endLabel.Text = "End"; columnLabel.Text = "Column"; rowLabel.Text = "Row"; this.dataTypeComboBox1.DataSource = new BindingList<string> { "Unknown", "Byte (8 bits)", "Integer (16 bits)", "Single (32 bits)", "Double(64 bits)" }; resampleMethodComboBox.DataSource = new BindingList<string> { "Unknown", "Triangulation", "Hab area-area " }; } private void groupBox2_Enter(object sender, EventArgs e) { } private void RowsLabel_Click(object sender, EventArgs e) { } private void ColumnsLabel_Click(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerCollision : MonoBehaviour { void OnTriggerEnter(Collider other) { if(other.gameObject.name == "Asteroid") { //die Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.Text; namespace Middleware.Business.Commons { public class BusinessConstants { public class RequestOrigin { public const string PostmanToken = "Postman-Token"; public const string HostToken = "Host"; public const string SigfoxToken = "SIGFOX"; } public sealed class RequestType { public const string Get = "GET"; public const string Post = "POST"; public const string Put = "PUT"; public const string Delete = "DELETE"; } public class DelegateNames { public const string PostmanDelegate = "PostmanDelegate"; public const string HostDelegate = "HostDelegate"; } } }
using System.ComponentModel.DataAnnotations; namespace DgKMS.Cube { public class FundEditDto { /// <summary> /// Id /// </summary> [Required(ErrorMessage = "Id不能为空")] public long Id { get; set; } /// <summary> /// 标题 /// </summary> [MaxLength(20, ErrorMessage = "标题超出最大长度")] [MinLength(1, ErrorMessage = "标题小于最小长度")] [Required(ErrorMessage = "标题不能为空")] public string ItemName { get; set; } /// <summary> /// 描述 /// </summary> [MaxLength(250, ErrorMessage = "描述超出最大长度")] [MinLength(0, ErrorMessage = "描述小于最小长度")] [Required(ErrorMessage = "描述不能为空")] public string Description { get; set; } /// <summary> /// 操作人 /// </summary> public long MemberId { get; set; } /// <summary> /// 修改时间 /// </summary> // [Required(ErrorMessage = "修改时间不能为空")] // public DateTime ModifiedTime { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Utils { public class Constants { public static readonly string categoryFormat = "~/Images/Categories/{0}.png"; public static readonly string defaultCategoryImage = "~/Images/Categories/defaultCategory.png"; } }