text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using SimpleJSON; public class InboxContent : MonoBehaviour { public string EventID; public Text Description,Title; public Button Claimed; public Home HomeScript; public GameObject Loading, Dialog; public void ClaimIt(){ StartCoroutine (RedeemIt ()); } IEnumerator RedeemIt() { Loading.SetActive (true); //yield return new WaitForSeconds(0.3f); var url = "http://139.59.100.192/PH/ClaimInbox"; var form = new WWWForm(); form.AddField("ID", EventID); form.AddField("PID", PlayerPrefs.GetString(Link.ID)); WWW www = new WWW(url, form); yield return www; Debug.Log(www.text); if (www.error == null) { var jsonString = JSON.Parse (www.text); // Debug.Log(jsonString["data"][0]["QS1"]); int ResCode = int.Parse (jsonString ["code"]); switch (ResCode) { case 9: print ("pop up already sent it"); // complete_button.interactable = false; break; case 8: print ("pop up expired event"); // complete_button.interactable = false; break; case 7: print ("Whadya want?"); break; case 6: print ("nothing to see yet"); break; case 1: string Quantity = jsonString ["data"] ["Quantity"]; string ItemName = jsonString ["data"] ["ItemClaimName"]; Loading.SetActive (false); Dialog.transform.Find ("Text").GetComponent<Text> ().text = "You got \n" + Quantity + " " + ItemName + "."; Claimed.interactable = false; Dialog.SetActive (true); HomeScript.GDUShop(); print ("You Got"); break; default: break; } } { Loading.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Escribir un programa que imprima por pantalla una pirámide como la siguiente: //* //*** //***** //******* //********* //El usuario indicará cuál será la altura de la pirámide ingresando un número entero positivo. Para el ejemplo anterior la altura ingresada fue de 5. Nota: Utilizar estructuras repetitivas y selectivas. namespace Ejercicio_09 { class Ejercicio_09 { static void Main(string[] args) { Console.Title = "Ejercicio 09"; bool flag = true; string stars = "*";//en la 1ra vuelta hay 1 sola estrella Console.Write("Ingresar altura piramide a dibujar: "); int.TryParse(Console.ReadLine(), out int alto); for(int i = 0; i < alto ; i++) { if (flag) { Console.WriteLine(stars);//1ra vuelta flag = false; } else { stars += "**";//sumo 2 mas por vuelta Console.WriteLine(stars); } } Console.ReadKey(); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace MyNiceBlog.Migrations { public partial class blogdbmigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Author", columns: table => new { AuthorId = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AuthorName = table.Column<string>(maxLength: 50, nullable: false), DateOfBirth = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Author", x => x.AuthorId); }); migrationBuilder.CreateTable( name: "Tag", columns: table => new { TagId = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), TagName = table.Column<string>(name: "TagName ", maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tag", x => x.TagId); }); migrationBuilder.CreateTable( name: "Post", columns: table => new { PostId = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(maxLength: 50, nullable: false), PostText = table.Column<string>(maxLength: 500, nullable: false), DatePublished = table.Column<DateTime>(name: "DatePublished ", nullable: false), AuthorId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Post", x => x.PostId); table.ForeignKey( name: "FK_Post_Author_AuthorId", column: x => x.AuthorId, principalTable: "Author", principalColumn: "AuthorId", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PostTag", columns: table => new { PostId = table.Column<int>(nullable: false), TagId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PostTag", x => new { x.TagId, x.PostId }); table.ForeignKey( name: "FK_PostTag_Post_PostId", column: x => x.PostId, principalTable: "Post", principalColumn: "PostId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PostTag_Tag_TagId", column: x => x.TagId, principalTable: "Tag", principalColumn: "TagId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Post_AuthorId", table: "Post", column: "AuthorId"); migrationBuilder.CreateIndex( name: "IX_PostTag_PostId", table: "PostTag", column: "PostId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PostTag"); migrationBuilder.DropTable( name: "Post"); migrationBuilder.DropTable( name: "Tag"); migrationBuilder.DropTable( name: "Author"); } } }
namespace gView.GraphicsEngine.Threading { public interface IThreadLocker { } }
using Core; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace Core.ApplicationDbContext { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) { var created = Database.EnsureCreatedAsync().Result; } public DbSet<Item> Items { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { var products = modelBuilder.Entity<Item>().ToContainer("Items"); products.OwnsMany<ItemImage>(x => x.Images, b => { b.OwnsMany<ImageAttribute>(x => x.Attributes); }); //also fails //products.OwnsMany(x => x.Images).OwnsMany(x => x.Attributes); } } }
using System.Reflection; [assembly: AssemblyTitle("SkipIntro")] [assembly: AssemblyVersion("1.8.2")]
using Microsoft.EntityFrameworkCore; namespace Aranda.Users.BackEnd.Models { public partial class Aranda_User_Context : DbContext { public Aranda_User_Context() { } public Aranda_User_Context(DbContextOptions<Aranda_User_Context> options) : base(options) { } public virtual DbSet<Permission> Permission { get; set; } public virtual DbSet<Role> Role { get; set; } public virtual DbSet<RolePermission> RolePermission { get; set; } public virtual DbSet<User> User { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("ProductVersion", "2.2.3-servicing-35854"); modelBuilder.Entity<Permission>(entity => { entity.Property(e => e.Action) .HasMaxLength(250) .IsUnicode(false); }); modelBuilder.Entity<Role>(entity => { entity.Property(e => e.Name) .IsRequired() .HasMaxLength(50) .IsUnicode(false); }); modelBuilder.Entity<RolePermission>(entity => { entity.ToTable("Role_Permission"); entity.HasOne(d => d.Permission) .WithMany(p => p.RolePermission) .HasForeignKey(d => d.PermissionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Role_Permission_Permission"); entity.HasOne(d => d.Rol) .WithMany(p => p.RolePermission) .HasForeignKey(d => d.RolId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Role_Permission_Role"); }); modelBuilder.Entity<User>(entity => { entity.Property(e => e.Address) .HasMaxLength(250) .IsUnicode(false); entity.Property(e => e.CreatedDate).HasColumnType("datetime"); entity.Property(e => e.Email) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(250) .IsUnicode(false); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Password) .IsRequired() .HasMaxLength(250) .IsUnicode(false); entity.Property(e => e.Telephone).HasColumnType("numeric(18, 0)"); entity.Property(e => e.UpdatedDate).HasColumnType("datetime"); entity.HasOne(d => d.Role) .WithMany(p => p.User) .HasForeignKey(d => d.RoleId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_User_Role"); }); } } }
namespace DZzzz.Net.Http.Configuration { public class HttpServiceClientConfiguration { public string BaseUrl { get; set; } } }
using MonitorBoletos.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonitorBoletos.Business { public class LicencaBusiness { public bool validarLicenca(Licenca licenca) { if (licenca is null) { return false; } else { return true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Tools.Ribbon; using Common.DataModel; using Client_Outlook.ViewModel; namespace Client_Outlook { public partial class MainContainerRibbon { #region ViewModel private RibbonViewModel _viewModel = null; public RibbonViewModel ViewModel { get { if (_viewModel == null) { _viewModel = new RibbonViewModel(); _viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_userData_PropertyChanged); } return _viewModel; } private set { _viewModel = value; } } #endregion #region PPTIES public bool IsConnected { get; private set; } #endregion void _userData_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "IsConnected") { IsConnected = ViewModel.IsConnected; } } private void ToggleVIewButton_Click_1(object sender, RibbonControlEventArgs e) { Globals.ThisAddIn.TaskPane.Visible = !Globals.ThisAddIn.TaskPane.Visible; } private void ConnectButton_Click(object sender, RibbonControlEventArgs e) { string[] infos = {EmailEditBox.Text, PasswordEditBox.Text }; ViewModel.Connect.Execute(infos as Object); } private void AddFeedButton_Click(object sender, RibbonControlEventArgs e) { if (ViewModel.IsConnected) { ViewModel.AddFeed.Execute(FeedEditBox.Text as Object); } } private void RefreshButton_Click(object sender, RibbonControlEventArgs e) { if (ViewModel.IsConnected) { ViewModel.RefreshFeeds.Execute(null); } } private void SearchBox_TextChanged(object sender, RibbonControlEventArgs e) { SearchDataModel.Instance.Search = (sender as RibbonEditBox).Text; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MES { /// <summary> /// 变更明细内容 /// </summary> public class OpenChangeInfo { /// <summary> /// 事实编号 /// </summary> public long FactID { get; set; } /// <summary> /// 交易号 /// </summary> public long TransactNo { get; set; } /// <summary> /// 变更类别叶标识 /// </summary> public int T276LeafID { get; set; } /// <summary> /// 变更类别名称 /// </summary> public string T276Name { get; set; } /// <summary> /// 变更号 /// </summary> public string ECorAlertNo { get; set; } /// <summary> /// 变更内容 /// </summary> public string ChangeContent { get; set; } /// <summary> /// 预计实施日期 /// </summary> public string ToImplementDate { get; set; } /// <summary> /// 预计关闭日期 /// </summary> public string ToCloseDate { get; set; } /// <summary> /// 实际实施日期 /// </summary> public string ActualImplementDate { get; set; } public OpenChangeInfo Clone() { return MemberwiseClone() as OpenChangeInfo; } } }
using System.Web.Mvc; using DevExpress.Web.Mvc; using System.Threading; namespace DevExpress.Web.Demos { public partial class CommonController: DemoController { public ActionResult AjaxForm() { return DemoView("AjaxForm", new AjaxFormValidationData()); } [HttpPost] public ActionResult AjaxForm(AjaxFormValidationData validationData) { if (!Request.IsAjaxRequest()) { // Theme changing ModelState.Clear(); return DemoView("AjaxForm", validationData); } // Intentionally pauses server-side processing, // to demonstrate the Loading Panel functionality. Thread.Sleep(1000); if (ModelState.IsValid) { object redirectActionName = "AjaxForm"; return PartialView("ValidationSuccessPartial", redirectActionName); } else return PartialView("AjaxFormPartial", validationData); } } }
using System; using System.Collections.Generic; using System.Text; namespace EmberKernel { public interface IKernelService { } }
using UnityEngine; using System.Collections; using TNet; using Netplayer = TNet.Player; [RequireComponent ( typeof (TNObject) )] /* This is where we are going deal with the session management. */ public class SessionManager : TNSingleton<SessionManager> { [SerializeField] private int _maxNetworkUpdatesPerSecond = 4; public int maxNetworkUpdatesPerSecond{ get{ return _maxNetworkUpdatesPerSecond; } } protected override void Awake(){ //If we're not the only instance of this, that means we're didn't start on this scene. Destroy this instance. Purely for testing purposes if (instance != null) { Debug.Log( "Destroying this instance of Session Manager" ); Destroy( this ); return; } base.Awake (); DontDestroyOnLoad( this ); //DEBUG FUNCTIONALITY PlayerSettings.currentProfile = PlayerProfile.newDefaultPlayerProfile(); } //Mission Selection, for persistence //TODO Saved game load //TODO After Mission end, do stuff }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using MainCharacter; using System.Text; using System.IO; public class Spawner : MonoBehaviour { public List<GameObject> enemyToSpawn; public float spawnRate; private Queue<float> enemySpawnTimes; private Queue<string> enemyDetails; private Queue<float> waveTimes = new Queue<float>(); private float? curWaveTime; private float levelTimeCounter; private float lastSpawnTime; public int level = 1; public bool showTimer = false; void OnGUI () { if(showTimer) { GUI.Label(new Rect(0, 0, 100, 50), levelTimeCounter.ToString()); } } // Use this for initialization public void Start () { levelTimeCounter = 0; Debug.Log("Loading level " + level); if (!Load("level" + level)) { Debug.Log("Failed to read spawn data for level " + level); } GameObject.Find("Background").AddComponent<ScrollBackground>().numSeconds = lastSpawnTime; Debug.Log("Level has " + enemyDetails.Count + " enemies"); BackgroundUI.Instance.AddGameEndEvent(delegate() { gameObject.SetActive(false); }); } // source: http://answers.unity3d.com/questions/279750/loading-data-from-a-txt-file-c.html private bool Load(string fileName) { enemySpawnTimes = new Queue<float>(); enemyDetails = new Queue<String>(); lastSpawnTime = 0; TextAsset levelData = (TextAsset)Resources.Load(fileName, typeof(TextAsset)); StringReader reader = new StringReader(levelData.text); // Handle any problems that might arise when reading the text try { string line; // While there's lines left in the text file, do this: do { line = reader.ReadLine(); // don't try to do anything if we didn't get any text // also ignore lines starting with a # if (line != null && !line.Trim().Equals("") && line[0] != '#') { string[] entries = line.Split(','); if (entries.Length == 6) { // format: enemyType, whenToAppear, xPos, yPos, movementPattern, stop float timeToAppear = float.Parse(entries[1]); string otherDetails = entries[0] + "," + entries[2] + "," + entries[3] + "," + entries[4] + "," + entries[5]; enemySpawnTimes.Enqueue(timeToAppear); if (timeToAppear > lastSpawnTime) { lastSpawnTime = timeToAppear; } enemyDetails.Enqueue(otherDetails); } else if (entries.Length==3) { if (entries[0].Trim().ToLower().Equals("wave")) { float timeToAppear = float.Parse(entries[1]); Debug.Log("there is a wave here"); waveTimes.Enqueue(timeToAppear); } } } } while (line != null); } // If anything broke in the try block, we throw an exception with information // on what didn't work catch (Exception e) { Console.WriteLine("{0}\n", e.Message); return false; } return true; } // Update is called once per frame void Update () { levelTimeCounter += Time.deltaTime; //get through the waves while (waveTimes.Count > 0 && waveTimes.Peek() <= levelTimeCounter) { waveTimes.Dequeue(); } // there is something to spawn, and the current object should have been spawned by now while (enemySpawnTimes.Count > 0 && enemySpawnTimes.Peek() <= levelTimeCounter) { enemySpawnTimes.Dequeue(); string[] details = enemyDetails.Dequeue().Split(','); GameObject spawn = null; var enemy = details[0].IndexOf("GOB"); var enemyNum = int.MaxValue; if (enemy != -1) { try{ enemyNum = Convert.ToInt32 (details[0].Substring(enemy+3)); spawn = enemyToSpawn[enemyNum]; }catch(FormatException){ Debug.LogError(details[0] + " is not a valid gameobject string in the level script. SPAWNING FIRST ENEMY IN LIST"); spawn = enemyToSpawn[0]; } } else { Debug.LogError("Cannot find enemy " + details[0] + ". SPAWNING FIRST ENEMY IN LIST"); spawn = enemyToSpawn[0]; } if(enemyNum >= enemyToSpawn.Count){ Debug.LogError("Attempted to spawn GameObject that is not in list. SPAWNING FIRST ENEMY IN LIST"); spawn = enemyToSpawn[0]; } float xPos = float.Parse(details[1]); float yPos = float.Parse(details[2]); int movementPattern = int.Parse(details[3]); bool stops; if (int.Parse(details[4]) == 1) stops = true; else stops = false; GameObject ship = (GameObject)Instantiate(spawn, transform.position + Vector3.down * (2 + yPos) + Vector3.right * xPos, spawn.transform.rotation); ship.GetComponent<EnemyMovement>().pattern = movementPattern; ship.GetComponent<EnemyMovement>().stops = stops; var multi = gameObject.GetComponent<MultiplierScript>(); EnemyDeath enemyDeath = ship.GetComponent<EnemyDeath>(); if(enemyDeath!=null) { enemyDeath.health *= multi.enemyHealthMultiplier; } Wave wave = ship.GetComponent<Wave>(); if(wave!=null) { //should this ever be null? wave.cooldown *= multi.enemyCooldownMultiplier; } if (enemyDetails.Count == 0) { GameObject.Find("Main Camera").AddComponent<EndLevel>(); } } } }
using System; namespace WebAPI { public static class Program { public static void Main(string[] args) { Main(args, new ConsoleMethods()); } public static void Main(string[] args, IConsoleMethods console) { try { using (Listener = new Listener(80)) { console.WriteLine("WebAPI is running on port 80...\n\nPress ENTER to terminate."); console.ReadLine(); } } catch (Exception e) { Console.WriteLine(e); Environment.ExitCode = 1; } } public static Listener Listener { get; set; } } }
using UnityEngine; using UnityEngine.UI; //using UnityEditor; using UnityEngine.EventSystems; using System.Collections; using System.Collections.Generic; using System.IO; public class editor_menu : MonoBehaviour { public Camera m_MainCamera; public Image m_SelectedTool; private int m_iSelectedToolId = 1; private int m_iUpdateToolId = 1; public Material[] m_vMaterials; public Material m_SelectedMaterial; public GameObject m_GridHolder; public GameObject m_GridElementPrefab; public GameObject m_SpawnPrefab; public GameObject m_OverRect; public GameObject m_SelectedRect; public InputField m_WidthInput; public InputField m_HeightInput; private int m_iWidth = 0; private int m_iHeight = 0; private int m_iNewWidth = 10; private int m_iNewHeight = 10; private GameObject[,] m_tTerrainGridElements; private GameObject[,] m_tRiverGridElements; private GameObject[,] m_tConstructionGridElements; private GameObject[,] m_tItemGridElements; private int[,] m_tTerrainGridElementValues; private int[,] m_tRiverGridElementValues; private int[,] m_tConstructionGridElementValues; private int[,] m_tItemGridElementValues; public GameObject m_SpanwOptionPopup; List<Spawn> m_tSpawns = new List<Spawn>(); public GameObject m_SelectedSpawn; private bool m_bReplaceLevel = false; public InputField m_FileNameInput; public GameObject m_OveridePopup; public GameObject m_LevelListPanel; public GameObject m_LevelNamePrefab; public Toggle[] m_LevelPlayerCountToggles; public GameObject m_ServerListPanel; public GameObject m_StartServerButton; public GameObject m_StopServerButton; public GameObject m_DisconnectFromServerButton; private bool m_bWaitingForServerList = false; // Use this for initialization void Start() { loadLevelList(); updateGrid(); m_OveridePopup.SetActive(false); MasterServer.ipAddress = "78.236.192.198"; //Network.natFacilitatorIP = "78.236.192.198"; getServerList(); } void OnApplicationQuit() { if (Network.isServer) { MasterServer.UnregisterHost(); } Network.Disconnect(); } void ComputeRaycast(GridElement gridElem) { if (m_iSelectedToolId < 18) { if (Network.isClient || Network.isServer) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, gridElem.m_iX, gridElem.m_iY, m_iSelectedToolId, true, 0); } else { SetGridElementMaterial(gridElem.m_iX, gridElem.m_iY, m_iSelectedToolId, true, 0); } } if (m_iSelectedToolId == 18) { if (gridElem.m_iLayer == 5) { m_SelectedSpawn = gridElem.gameObject; Spawn spawn = gridElem.GetComponent<Spawn>(); m_SpanwOptionPopup.GetComponent<SpawnOption>().SetSelectedPlayer(spawn.m_iPlayerID); } else { if (Network.isClient || Network.isServer) { GetComponent<NetworkView>().RPC("CreateSpawn", RPCMode.Others, gridElem.m_iX, gridElem.m_iY, false); } CreateSpawn(gridElem.m_iX, gridElem.m_iY, true); m_SpanwOptionPopup.GetComponent<SpawnOption>().SetSelectedPlayer(1); } m_SelectedRect.transform.position = new Vector3(gridElem.m_iX * 10, gridElem.m_iY * 10, -0.06f); m_SelectedRect.SetActive(true); m_SpanwOptionPopup.SetActive(true); } } // Update is called once per frame void Update() { if (!m_OveridePopup.activeSelf && !m_SpanwOptionPopup.activeSelf) { #if UNITY_IPHONE || UNITY_ANDROID if (Input.touchCount == 1) { Touch touchZero = Input.GetTouch(0); if (touchZero.phase == TouchPhase.Began && !Camera.main.GetComponent<editor_camera>().isInInterface(touchZero.position)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfos; if (Physics.Raycast(ray, out hitInfos)) { GridElement gridElem = hitInfos.collider.gameObject.GetComponent<GridElement>(); m_OverRect.transform.position = new Vector3(gridElem.m_iX * 10, gridElem.m_iY * 10, -0.06f); ComputeRaycast(gridElem); } } } #else if (!EventSystem.current.IsPointerOverGameObject()) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfos; if (Physics.Raycast(ray, out hitInfos)) { GridElement gridElem = hitInfos.collider.gameObject.GetComponent<GridElement>(); m_OverRect.transform.position = new Vector3(gridElem.m_iX * 10, gridElem.m_iY * 10, -0.06f); if (Input.GetMouseButtonDown(0)) { ComputeRaycast(gridElem); } if (Input.GetMouseButton(0) && m_iSelectedToolId < 18) { if (Network.isClient || Network.isServer) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, gridElem.m_iX, gridElem.m_iY, m_iSelectedToolId, false, 0); } else { SetGridElementMaterial(gridElem.m_iX, gridElem.m_iY, m_iSelectedToolId, false, 0); } } } } #endif } if (m_bWaitingForServerList) { m_bWaitingForServerList = !ShowServerList(); } } //Level Edition [RPC] void SetGridElementMaterial(int x, int y, int id, bool _bRotate, int _iRotation) { if (id == 12) { if (m_tConstructionGridElements[x, y] != null) { GameObject.Destroy(m_tConstructionGridElements[x, y]); m_tConstructionGridElementValues[x, y] = 0; } } else if (id == 17) { if (m_tRiverGridElements[x, y] != null) { GameObject.Destroy(m_tRiverGridElements[x, y]); m_tRiverGridElementValues[x, y] = 0; } } else if (id >= 8 && id <= 11) { if (m_tTerrainGridElementValues[x, y] != 2) { if (m_tConstructionGridElements[x, y] == null) { GameObject newGridElement = (GameObject)Instantiate(m_GridElementPrefab, new Vector3(x * 10, y * 10, -0.02f), Quaternion.identity); newGridElement.GetComponent<GridElement>().Init(x, y, 2); newGridElement.transform.SetParent(m_GridHolder.transform); newGridElement.transform.Rotate(Vector3.forward, _iRotation); m_tConstructionGridElements[x, y] = newGridElement; } if (m_tConstructionGridElementValues[x, y] == id) { if (_bRotate) { m_tConstructionGridElements[x, y].transform.Rotate(Vector3.forward, -90); } } else { m_tConstructionGridElements[x, y].GetComponent<Renderer>().material = m_vMaterials[id]; m_tConstructionGridElementValues[x, y] = id; } } } else if (id >= 13 && id <= 16) { if (m_tTerrainGridElementValues[x, y] != 2) { if (m_tRiverGridElements[x, y] == null) { GameObject newGridElement = (GameObject)Instantiate(m_GridElementPrefab, new Vector3(x * 10, y * 10, -0.01f), Quaternion.identity); newGridElement.GetComponent<GridElement>().Init(x, y, 1); newGridElement.transform.SetParent(m_GridHolder.transform); newGridElement.transform.Rotate(Vector3.forward, _iRotation); m_tRiverGridElements[x, y] = newGridElement; } if (m_tRiverGridElementValues[x, y] == id) { if (_bRotate) { m_tRiverGridElements[x, y].transform.Rotate(Vector3.forward, -90); } } else { m_tRiverGridElements[x, y].GetComponent<Renderer>().material = m_vMaterials[id]; m_tRiverGridElementValues[x, y] = id; } } } else if(id > 17) { } else { m_tTerrainGridElements[x, y].GetComponent<Renderer>().material = m_vMaterials[id]; m_tTerrainGridElementValues[x, y] = id; if (id == 2) { if (m_tConstructionGridElements[x, y] != null) { GameObject.Destroy(m_tConstructionGridElements[x, y]); m_tConstructionGridElementValues[x, y] = 0; } if (m_tRiverGridElements[x, y] != null) { GameObject.Destroy(m_tRiverGridElements[x, y]); m_tRiverGridElementValues[x, y] = 0; } } } } [RPC] void ResetGrid(int _iWidth, int _iHeight) { m_WidthInput.text = _iWidth.ToString(); m_HeightInput.text = _iHeight.ToString(); m_iNewWidth = _iWidth; m_iNewHeight = _iHeight; resetMap(); } [RPC] void SetGridSize(int _iWidth, int _iHeight, int _iUpdateToolId) { m_iUpdateToolId = _iUpdateToolId; m_WidthInput.text = _iWidth.ToString(); m_HeightInput.text = _iHeight.ToString(); m_iNewWidth = _iWidth; m_iNewHeight = _iHeight; } public void changeSelected(Image _oClickedButton) { m_SelectedTool.color = _oClickedButton.color; m_SelectedTool.sprite = _oClickedButton.sprite; } public void SetSelectToolID(int _itoolID) { m_iSelectedToolId = _itoolID; } public void changeSelectedMaterial(Material _material) { m_SelectedMaterial = _material; } public void updateGridButtonPressed() { m_iUpdateToolId = m_iSelectedToolId; if (Network.isClient || Network.isServer) { GetComponent<NetworkView>().RPC("SetGridSize", RPCMode.Others, m_iNewWidth, m_iNewHeight, m_iSelectedToolId); GetComponent<NetworkView>().RPC("updateGrid", RPCMode.All); } else { updateGrid(); } } [RPC] void updateGrid() { // old arrays GameObject[,] oldTerrainGridElements = m_tTerrainGridElements; GameObject[,] oldRiverGridElements = m_tRiverGridElements; GameObject[,] oldConstructionGridElements = m_tConstructionGridElements; GameObject[,] oldItemGridElements = m_tItemGridElements; int[,] oldTerrainGridElementValues = m_tTerrainGridElementValues; int[,] oldRiverGridElementValues = m_tRiverGridElementValues; int[,] oldConstructionGridElementValues = m_tConstructionGridElementValues; int[,] oldItemGridElementValues = m_tItemGridElementValues; // new arrays m_tTerrainGridElements = new GameObject[m_iNewWidth, m_iNewHeight]; m_tRiverGridElements = new GameObject[m_iNewWidth, m_iNewHeight]; m_tConstructionGridElements = new GameObject[m_iNewWidth, m_iNewHeight]; m_tItemGridElements = new GameObject[m_iNewWidth, m_iNewHeight]; m_tTerrainGridElementValues = new int[m_iNewWidth, m_iNewHeight]; m_tRiverGridElementValues = new int[m_iNewWidth, m_iNewHeight]; m_tConstructionGridElementValues = new int[m_iNewWidth, m_iNewHeight]; m_tItemGridElementValues = new int[m_iNewWidth, m_iNewHeight]; int maxWidth = Mathf.Max(m_iWidth, m_iNewWidth); int maxHeight = Mathf.Max(m_iHeight, m_iNewHeight); for (int i = 0; i < maxWidth; i++) { for (int j = 0; j < maxHeight; j++) { if (i >= m_iNewWidth || j >= m_iNewHeight) { GameObject.Destroy(oldTerrainGridElements[i, j]); if (oldRiverGridElementValues[i, j] > 0) { GameObject.Destroy(oldRiverGridElements[i, j]); } if (oldConstructionGridElementValues[i, j] > 0) { GameObject.Destroy(oldConstructionGridElements[i, j]); } if (oldItemGridElementValues[i, j] > 0) { GameObject.Destroy(oldItemGridElements[i, j]); } if (Network.isClient || Network.isServer) { GetComponent<NetworkView>().RPC("DeleteSpawn", RPCMode.All, i, j); } else { DeleteSpawn(i, j); } } else if (i >= m_iWidth || j >= m_iHeight) { GameObject newGridElement = (GameObject)Instantiate(m_GridElementPrefab, new Vector3(i * 10, j * 10), Quaternion.identity); newGridElement.GetComponent<GridElement>().Init(i, j, 0); newGridElement.transform.SetParent(m_GridHolder.transform); m_tTerrainGridElements[i, j] = newGridElement; m_tRiverGridElements[i, j] = null; m_tConstructionGridElements[i, j] = null; m_tItemGridElements[i, j] = null; m_tTerrainGridElementValues[i, j] = 1; m_tRiverGridElementValues[i, j] = 0; m_tConstructionGridElementValues[i, j] = 0; m_tItemGridElementValues[i, j] = 0; SetGridElementMaterial(i, j, m_iUpdateToolId, false, 0); } else { m_tTerrainGridElements[i, j] = oldTerrainGridElements[i, j]; m_tRiverGridElements[i, j] = oldRiverGridElements[i, j]; m_tConstructionGridElements[i, j] = oldConstructionGridElements[i, j]; m_tItemGridElements[i, j] = oldItemGridElements[i, j]; m_tTerrainGridElementValues[i, j] = oldTerrainGridElementValues[i, j]; m_tRiverGridElementValues[i, j] = oldRiverGridElementValues[i, j]; m_tConstructionGridElementValues[i, j] = oldConstructionGridElementValues[i, j]; m_tItemGridElementValues[i, j] = oldItemGridElementValues[i, j]; } } } m_iWidth = m_iNewWidth; m_iHeight = m_iNewHeight; Camera.main.GetComponent<editor_camera>().SetMaxPosition(new Vector2((m_iWidth - 1) * 10, (m_iHeight - 1) * 10)); } public void changeHeight(string _sValue) { int iHeight = int.Parse('0' + _sValue); if (iHeight > 0 && iHeight <= 200) { m_iNewHeight = iHeight; } } public void changeWidth(string _sValue) { int iWidth = int.Parse('0' + _sValue); if (iWidth > 0 && iWidth <= 200) { m_iNewWidth = iWidth; } } public void resetMapButtonPressed() { if (Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("resetMap", RPCMode.All); } else { resetMap(); } } [RPC] void resetMap() { foreach (Transform child in m_GridHolder.transform) { GameObject.Destroy(child.gameObject); } m_tSpawns.Clear(); m_iWidth = 0; m_iHeight = 0; m_FileNameInput.text = ""; updateGrid(); } [RPC] void CreateSpawn(int _iX, int _iY, bool _AmICreator) { GameObject newGridElement = (GameObject)Instantiate(m_SpawnPrefab, new Vector3(_iX * 10, _iY * 10, -0.03f), Quaternion.identity); newGridElement.GetComponent<GridElement>().Init(_iX, _iY, 5); newGridElement.transform.SetParent(m_GridHolder.transform); m_tSpawns.Add(newGridElement.GetComponent<Spawn>()); if(_AmICreator) { m_SelectedSpawn = newGridElement; } } public void DeleteSpawnButtonClicked() { if (m_SelectedSpawn != null) { GridElement elem = m_SelectedSpawn.GetComponent<GridElement>(); if (Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("DeleteSpawn", RPCMode.All, elem.m_iX, elem.m_iY); } else { DeleteSpawn(elem.m_iX, elem.m_iY); } m_SelectedSpawn = null; } m_SpanwOptionPopup.SetActive(false); m_SelectedRect.SetActive(false); } [RPC] void DeleteSpawn(int _iX, int _iY) { Spawn spawnToDelete = null; foreach (Spawn spawn in m_tSpawns) { GridElement elem = spawn.GetComponent<GridElement>(); if(elem.m_iX == _iX && elem.m_iY == _iY) { spawnToDelete = spawn; break; } } if (spawnToDelete != null) { m_tSpawns.Remove(spawnToDelete); GameObject.Destroy(spawnToDelete.gameObject); } } public void ApplySpawnOtionClicked() { int iPlayerId = m_SpanwOptionPopup.GetComponent<SpawnOption>().GetSelectedPlayer(); if(m_SelectedSpawn != null) { GridElement elem = m_SelectedSpawn.GetComponent<GridElement>(); if (Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("UpdateSpawn", RPCMode.All, elem.m_iX, elem.m_iY, iPlayerId); } else { UpdateSpawn(elem.m_iX, elem.m_iY, iPlayerId); } m_SelectedSpawn = null; } m_SpanwOptionPopup.SetActive(false); m_SelectedRect.SetActive(false); } [RPC] void UpdateSpawn(int _iX, int _iY, int _iPlayerID) { foreach(Spawn spawn in m_tSpawns) { GridElement elem = spawn.GetComponent<GridElement>(); if(elem.m_iX == _iX && elem.m_iY == _iY) { spawn.m_iPlayerID = _iPlayerID; } } } // Level Management void loadLevelList() { foreach (Transform child in m_LevelListPanel.transform) { GameObject.Destroy(child.gameObject); } string[] tLevels = Directory.GetFiles(Application.persistentDataPath + "/Levels"); int iLevelId = 0; m_LevelListPanel.GetComponent<RectTransform>().sizeDelta = new Vector2(130, Mathf.Max(5 + 35 * tLevels.Length, 110)); m_LevelListPanel.transform.localPosition = new Vector3(0, Mathf.Min((-5 - 35 * tLevels.Length) / 2 + 55, 0), 0); foreach(string path in tLevels) { string szLevel = Path.GetFileNameWithoutExtension(path); GameObject oNewLevelName = (GameObject)Instantiate(m_LevelNamePrefab); oNewLevelName.transform.SetParent(m_LevelListPanel.transform, false); Button oNewButton = oNewLevelName.GetComponent<Button>(); oNewLevelName.transform.localPosition = new Vector3(0, -20 - 35 * iLevelId + m_LevelListPanel.GetComponent<RectTransform>().sizeDelta.y / 2, 0); oNewLevelName.transform.GetChild(0).GetComponent<Text>().text = szLevel; AddListenerToLevelButton(oNewButton, szLevel); iLevelId++; } } void AddListenerToLevelButton(Button _oBbutton, string _szLevel) { _oBbutton.onClick.AddListener(() => loadMap(_szLevel)); } int GetMaxPlayerCount() { for (int i = 0; i < m_LevelPlayerCountToggles.Length; i++) { if (m_LevelPlayerCountToggles[i].isOn) { return (i+1) *2; } } return 0; } int SetMaxPlayerCount(int _iMaxPlayerCount) { for (int i = 0; i < m_LevelPlayerCountToggles.Length; i++) { if (_iMaxPlayerCount == (i+1)*2) { m_LevelPlayerCountToggles[i].isOn = true; } else { m_LevelPlayerCountToggles[i].isOn = false; } } return 0; } public void saveMap() { if(m_FileNameInput.text.Length > 0) { string szFilePath = Application.persistentDataPath + "/Levels/" + m_FileNameInput.text + ".lvl"; if (!File.Exists(szFilePath) || m_bReplaceLevel) { BinaryWriter bw; //create the file try { bw = new BinaryWriter(new FileStream(szFilePath, FileMode.Create)); } catch (IOException e) { Debug.Log(e.Message + "\n Cannot create file."); return; } //write in the file try { bw.Write(m_iWidth); bw.Write(m_iHeight); bw.Write(GetMaxPlayerCount()); for (int i = 0; i < m_iWidth; i++) { for (int j = 0; j < m_iHeight; j++) { bw.Write(m_tTerrainGridElementValues[i, j]); bw.Write(m_tRiverGridElementValues[i, j]); if (m_tRiverGridElements[i, j] != null) { bw.Write((int)(m_tRiverGridElements[i, j].transform.rotation.eulerAngles.z)); } else { bw.Write(0); } bw.Write(m_tConstructionGridElementValues[i, j]); if (m_tConstructionGridElements[i, j] != null) { bw.Write((int)(m_tConstructionGridElements[i, j].transform.rotation.eulerAngles.z)); } else { bw.Write(0); } bw.Write(m_tItemGridElementValues[i, j]); } } bw.Write(m_tSpawns.Count); foreach(Spawn spawn in m_tSpawns) { GridElement elem = spawn.GetComponent<GridElement>(); bw.Write(elem.m_iX); bw.Write(elem.m_iY); bw.Write(spawn.m_iPlayerID); } } catch (IOException e) { Debug.Log(e.Message + "\n Cannot write to file."); return; } bw.Close(); if (m_bReplaceLevel) { m_bReplaceLevel = false; } else { loadLevelList(); } } else { m_OveridePopup.SetActive(true); } } } public void forceSaveMap(bool _bForce) { if(_bForce) { m_bReplaceLevel = true; saveMap(); } m_OveridePopup.SetActive(false); } public void loadMap(string _sMapName) { string szFilePath = Application.persistentDataPath + "/Levels/" + _sMapName + ".lvl"; if (File.Exists(szFilePath)) { BinaryReader br; //create the file try { br = new BinaryReader(new FileStream(szFilePath, FileMode.Open)); } catch (IOException e) { Debug.Log(e.Message + "\n Cannot open file."); return; } //read the file try { m_iNewWidth = br.ReadInt32(); m_iNewHeight = br.ReadInt32(); int iPlayerCount = br.ReadInt32(); SetMaxPlayerCount(iPlayerCount); if (Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("ResetGrid", RPCMode.All, m_iNewWidth, m_iNewHeight); } else { ResetGrid(m_iNewWidth, m_iNewHeight); } for (int i = 0; i < m_iWidth; i++) { for (int j = 0; j < m_iHeight; j++) { int iTerrainMaterialId = br.ReadInt32(); int iRiverMaterialId = br.ReadInt32(); int iRiverRotation = br.ReadInt32(); int iConstructionMaterialId = br.ReadInt32(); int iConstructionRotation = br.ReadInt32(); int iItemMaterialId = br.ReadInt32(); if(Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, i, j, iTerrainMaterialId, false , 0); if(iRiverMaterialId != 0) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, i, j, iRiverMaterialId, false, iRiverRotation); } if (iConstructionMaterialId != 0) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, i, j, iConstructionMaterialId, false, iConstructionRotation); } if (iItemMaterialId != 0) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", RPCMode.All, i, j, iItemMaterialId, false, 0); } } else { SetGridElementMaterial(i, j, iTerrainMaterialId, false , 0); if (iRiverMaterialId != 0) { SetGridElementMaterial(i, j, iRiverMaterialId, false, iRiverRotation); } if (iConstructionMaterialId != 0) { SetGridElementMaterial(i, j, iConstructionMaterialId, false, iConstructionRotation); } if (iItemMaterialId != 0) { SetGridElementMaterial(i, j, iItemMaterialId, false , 0); } } } } int iSpawnCount = br.ReadInt32(); for (int i = 0; i < iSpawnCount; i++) { int iX = br.ReadInt32(); int iY = br.ReadInt32(); int iPlayerID = br.ReadInt32(); if (Network.isServer || Network.isClient) { GetComponent<NetworkView>().RPC("CreateSpawn", RPCMode.All, iX, iY, false); GetComponent<NetworkView>().RPC("UpdateSpawn", RPCMode.All, iX, iY, iPlayerID); } else { CreateSpawn(iX, iY, false); UpdateSpawn(iX, iY, iPlayerID); } } } catch (IOException e) { Debug.Log(e.Message + "\n Cannot read file."); return; } br.Close(); m_FileNameInput.text = _sMapName; } } // network management (server) public void startServer() { if (!Network.isClient) { Network.InitializeServer(5, 6000, true); MasterServer.RegisterHost("WeatherTacticsEditor", "Tsan editor", "trololol"); m_StartServerButton.SetActive(false); m_StopServerButton.SetActive(true); } else { Debug.Log("can't start server you are already connected to a server"); } } public void stopServer() { if (Network.isServer) { Network.Disconnect(); MasterServer.UnregisterHost(); m_StartServerButton.SetActive(true); m_StopServerButton.SetActive(false); } } void OnPlayerConnected(NetworkPlayer _oPlayer) { Debug.Log("new player connected"); GetComponent<NetworkView>().RPC("ResetGrid", _oPlayer, m_iNewWidth, m_iNewHeight); for (int i = 0; i < m_iWidth; i++) { for (int j = 0; j < m_iHeight; j++) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", _oPlayer, i, j, m_tTerrainGridElementValues[i, j], false, 0); if (m_tRiverGridElementValues[i, j] != 0 && m_tRiverGridElements[i, j] != null) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", _oPlayer, i, j, m_tRiverGridElementValues[i, j], false, (int)m_tRiverGridElements[i, j].transform.rotation.eulerAngles.z); } if (m_tConstructionGridElementValues[i, j] != 0 && m_tConstructionGridElements[i, j] != null) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", _oPlayer, i, j, m_tConstructionGridElementValues[i, j], false, (int)m_tConstructionGridElements[i, j].transform.rotation.eulerAngles.z); } if (m_tItemGridElementValues[i, j] != 0 && m_tItemGridElements[i, j] != null) { GetComponent<NetworkView>().RPC("SetGridElementMaterial", _oPlayer, i, j, m_tItemGridElementValues[i, j], false, 0); } } } foreach (Spawn spawn in m_tSpawns) { GridElement elem = spawn.GetComponent<GridElement>(); int iX = elem.m_iX; int iY = elem.m_iY; GetComponent<NetworkView>().RPC("CreateSpawn", _oPlayer, iX, iY, false); GetComponent<NetworkView>().RPC("UpdateSpawn", _oPlayer, iX, iY, spawn.m_iPlayerID); } } void OnPlayerDisconnected(NetworkPlayer _oPlayer) { Debug.Log("player disconnected : " + _oPlayer); } // network management (client) bool ShowServerList() { HostData[] tServeurs = MasterServer.PollHostList(); if (tServeurs.Length > 0) { int iServerId = 0; m_ServerListPanel.GetComponent<RectTransform>().sizeDelta = new Vector2(130, Mathf.Max(5 + 35 * tServeurs.Length, 110)); m_ServerListPanel.transform.localPosition = new Vector3(0, Mathf.Min((-5 - 35 * tServeurs.Length) / 2 + 55, 0), 0); foreach (HostData oServer in tServeurs) { string szServerName = oServer.gameName; /*foreach(string ip in oServer.ip) { Debug.Log(ip); } Debug.Log(oServer.port.ToString());*/ GameObject oNewServerName = (GameObject)Instantiate(m_LevelNamePrefab); oNewServerName.transform.SetParent(m_ServerListPanel.transform, false); Button oNewButton = oNewServerName.GetComponent<Button>(); oNewServerName.transform.localPosition = new Vector3(0, -20 - 35 * iServerId + m_ServerListPanel.GetComponent<RectTransform>().sizeDelta.y / 2, 0); oNewServerName.transform.GetChild(0).GetComponent<Text>().text = szServerName + " " + oServer.connectedPlayers + "/" + oServer.playerLimit; AddListenerToServerButton(oNewButton, oServer); iServerId++; } return true; } else { return false; } } void AddListenerToServerButton(Button _oButton, HostData _oServer) { _oButton.onClick.AddListener(() => ConnectToServer(_oServer)); } public void getServerList() { MasterServer.ClearHostList(); MasterServer.RequestHostList("WeatherTacticsEditor"); foreach (Transform child in m_ServerListPanel.transform) { GameObject.Destroy(child.gameObject); } m_bWaitingForServerList = true; } void ConnectToServer(HostData _oServer) { if (!Network.isServer) { if(!Network.isClient) { Network.Connect(_oServer); } else { Debug.Log("can't connect to server you are already connected to a server"); } } else { Debug.Log("can't connect to server you are already a server"); } } public void DisconnectFromServer() { Network.Disconnect(); } void OnConnectedToServer() { Debug.Log("Connected to server"); m_DisconnectFromServerButton.SetActive(true); } void OnDisconnectedFromServer(NetworkDisconnection _oInfo) { Debug.Log("Disconnected from server"); m_DisconnectFromServerButton.SetActive(false); } }
using GraphicalEditor.Enumerations; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphicalEditor.DTO { public class RoomSchedulesDTO { public DateTime ScheduleTime { get; set; } public ScheduleType ScheduleType { get; set; } public int Id { get; set; } public RoomSchedulesDTO() { } public RoomSchedulesDTO(DateTime scheduleTime, ScheduleType scheduleType, int id) { ScheduleTime = scheduleTime; ScheduleType = scheduleType; Id = id; } } }
using Sales.Models; using System; using System.Collections.Generic; using System.Linq; namespace Sales.Services { public class SafeServices { public void AddSafe(Safe safe) { using (SalesDB db = new SalesDB()) { db.Safes.Add(safe); db.SaveChanges(); } } public void DeleteSafe(Safe safe) { using (SalesDB db = new SalesDB()) { db.Safes.Attach(safe); db.Safes.Remove(safe); db.SaveChanges(); } } public void DeleteSafe(DateTime dt) { using (SalesDB db = new SalesDB()) { var safe = db.Safes.SingleOrDefault(s => s.RegistrationDate == dt); if (safe != null) { db.Safes.Attach(safe); db.Safes.Remove(safe); db.SaveChanges(); } } } public int GetSafesNumer(string key) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => w.Statement.Contains(key)).Count(); } } public int GetSafesNumer(string key, DateTime dtFrom, DateTime dtTo) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => w.Statement.Contains(key) && w.Date >= dtFrom && w.Date <= dtTo).Count(); } } public decimal? GetCurrentAccount() { using (SalesDB db = new SalesDB()) { return db.Safes.Sum(s => s.Amount); } } public decimal? GetTotalIncome(string key, DateTime dtFrom, DateTime dtTo) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => w.Amount > 0 && w.Statement.Contains(key) && w.Date >= dtFrom && w.Date <= dtTo).Sum(s => s.Amount); } } public decimal? GetTotalOutgoings(string key, DateTime dtFrom, DateTime dtTo) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => w.Amount < 0 && w.Statement.Contains(key) && w.Date >= dtFrom && w.Date <= dtTo).Sum(s => s.Amount); } } public decimal? GetItemSum(string key, DateTime dtFrom, DateTime dtTo, int source) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => w.Source == source && w.Statement.Contains(key) && w.Date >= dtFrom && w.Date <= dtTo).Sum(s => s.Amount); } } public List<string> GetStatementSuggetions() { using (SalesDB db = new SalesDB()) { List<string> newData = new List<string>(); var data = db.Safes.Where(w => w.CanDelete == true).OrderBy(o => o.Statement).Select(s => new { s.Statement }).Distinct().ToList(); foreach (var item in data) { newData.Add(item.Statement); } return newData; } } public List<Safe> SearchSafes(string search, int page) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => (w.Statement).Contains(search)).OrderByDescending(o => o.RegistrationDate).Skip((page - 1) * 17).Take(17).ToList(); } } public List<Safe> SearchSafes(string search, int page, DateTime dtFrom, DateTime dtTo) { using (SalesDB db = new SalesDB()) { return db.Safes.Where(w => (w.Statement).Contains(search) && w.Date >= dtFrom && w.Date <= dtTo).OrderByDescending(o => o.RegistrationDate).Skip((page - 1) * 17).Take(17).ToList(); } } } }
using MediaBrowser.Common.IO; using MediaBrowser.Common.MediaInfo; using MediaBrowser.Common.ScheduledTasks; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers.MediaInfo; using MediaBrowser.Model.Entities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.ScheduledTasks { /// <summary> /// Class VideoImagesTask /// </summary> public class VideoImagesTask : IScheduledTask { /// <summary> /// Gets or sets the image cache. /// </summary> /// <value>The image cache.</value> public FileSystemRepository ImageCache { get; set; } /// <summary> /// The _library manager /// </summary> private readonly ILibraryManager _libraryManager; /// <summary> /// The _media encoder /// </summary> private readonly IMediaEncoder _mediaEncoder; /// <summary> /// The _iso manager /// </summary> private readonly IIsoManager _isoManager; /// <summary> /// The _locks /// </summary> private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>(); /// <summary> /// Initializes a new instance of the <see cref="AudioImagesTask" /> class. /// </summary> /// <param name="libraryManager">The library manager.</param> /// <param name="mediaEncoder">The media encoder.</param> /// <param name="isoManager">The iso manager.</param> public VideoImagesTask(ILibraryManager libraryManager, IMediaEncoder mediaEncoder, IIsoManager isoManager) { _libraryManager = libraryManager; _mediaEncoder = mediaEncoder; _isoManager = isoManager; ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.VideoImagesDataPath); } /// <summary> /// Gets the name of the task /// </summary> /// <value>The name.</value> public string Name { get { return "Video image extraction"; } } /// <summary> /// Gets the description. /// </summary> /// <value>The description.</value> public string Description { get { return "Extracts images from video files that do not have external images."; } } /// <summary> /// Gets the category. /// </summary> /// <value>The category.</value> public string Category { get { return "Library"; } } /// <summary> /// Executes the task /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="progress">The progress.</param> /// <returns>Task.</returns> public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress) { var allItems = _libraryManager.RootFolder.RecursiveChildren.ToList(); var localTrailers = allItems.SelectMany(i => i.LocalTrailers); var themeVideos = allItems.SelectMany(i => i.ThemeVideos); var videos = allItems.OfType<Video>().ToList(); var items = videos; items.AddRange(localTrailers); items.AddRange(themeVideos); items.AddRange(videos.OfType<Movie>().SelectMany(i => i.SpecialFeatures).ToList()); items = items.Where(i => { if (!string.IsNullOrEmpty(i.PrimaryImagePath)) { return false; } if (i.LocationType != LocationType.FileSystem) { return false; } if (i.VideoType == VideoType.HdDvd) { return false; } if (i.VideoType == VideoType.Iso && !i.IsoType.HasValue) { return false; } return i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video); }).ToList(); progress.Report(0); var numComplete = 0; foreach (var item in items) { cancellationToken.ThrowIfCancellationRequested(); var filename = item.Id + "_" + item.DateModified.Ticks + "_primary"; var path = ImageCache.GetResourcePath(filename, ".jpg"); var success = true; if (!ImageCache.ContainsFilePath(path)) { var semaphore = GetLock(path); // Acquire a lock await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); // Check again if (!ImageCache.ContainsFilePath(path)) { try { await ExtractImage(item, path, cancellationToken).ConfigureAwait(false); } catch { success = false; } finally { semaphore.Release(); } } else { semaphore.Release(); } } numComplete++; double percent = numComplete; percent /= items.Count; progress.Report(100 * percent); if (success) { // Image is already in the cache item.PrimaryImagePath = path; await _libraryManager.SaveItem(item, cancellationToken).ConfigureAwait(false); } } progress.Report(100); } /// <summary> /// Extracts the image. /// </summary> /// <param name="video">The video.</param> /// <param name="path">The path.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> private async Task ExtractImage(Video video, string path, CancellationToken cancellationToken) { var isoMount = await MountIsoIfNeeded(video, cancellationToken).ConfigureAwait(false); try { // If we know the duration, grab it from 10% into the video. Otherwise just 10 seconds in. // Always use 10 seconds for dvd because our duration could be out of whack var imageOffset = video.VideoType != VideoType.Dvd && video.RunTimeTicks.HasValue && video.RunTimeTicks.Value > 0 ? TimeSpan.FromTicks(Convert.ToInt64(video.RunTimeTicks.Value * .1)) : TimeSpan.FromSeconds(10); InputType type; var inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type); await _mediaEncoder.ExtractImage(inputPath, type, imageOffset, path, cancellationToken).ConfigureAwait(false); video.PrimaryImagePath = path; } finally { if (isoMount != null) { isoMount.Dispose(); } } } /// <summary> /// The null mount task result /// </summary> protected readonly Task<IIsoMount> NullMountTaskResult = Task.FromResult<IIsoMount>(null); /// <summary> /// Mounts the iso if needed. /// </summary> /// <param name="item">The item.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task{IIsoMount}.</returns> protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken) { if (item.VideoType == VideoType.Iso) { return _isoManager.Mount(item.Path, cancellationToken); } return NullMountTaskResult; } /// <summary> /// Gets the default triggers. /// </summary> /// <returns>IEnumerable{BaseTaskTrigger}.</returns> public IEnumerable<ITaskTrigger> GetDefaultTriggers() { return new ITaskTrigger[] { new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) } }; } /// <summary> /// Gets the lock. /// </summary> /// <param name="filename">The filename.</param> /// <returns>System.Object.</returns> private SemaphoreSlim GetLock(string filename) { return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace lab_018 { public partial class Form1 : Form { string znak = null; bool startEdit = true; double number1, number2; public Form1() { InitializeComponent(); this.Text = "Калькулятор"; button1.Text = "1"; button2.Text = "2"; button3.Text = "3"; button4.Text = "4"; button5.Text = "5"; button6.Text = "6"; button7.Text = "7"; button8.Text = "8"; button9.Text = "9"; button10.Text = "0"; button11.Text = "="; button12.Text = "+"; button13.Text = "-"; button14.Text = "*"; button15.Text = "/"; button16.Text = "Очистить"; textBox1.Text = "0"; textBox1.TextAlign = HorizontalAlignment.Right; this.button1.Click += new System.EventHandler(this.Digit); this.button2.Click += new System.EventHandler(this.Digit); this.button3.Click += new System.EventHandler(this.Digit); this.button4.Click += new System.EventHandler(this.Digit); this.button5.Click += new System.EventHandler(this.Digit); this.button6.Click += new System.EventHandler(this.Digit); this.button7.Click += new System.EventHandler(this.Digit); this.button8.Click += new System.EventHandler(this.Digit); this.button9.Click += new System.EventHandler(this.Digit); this.button10.Click += new System.EventHandler(this.Digit); this.button12.Click += new System.EventHandler(this.Operation); this.button13.Click += new System.EventHandler(this.Operation); this.button14.Click += new System.EventHandler(this.Operation); this.button15.Click += new System.EventHandler(this.Operation); this.button11.Click += new System.EventHandler(this.Equal); this.button16.Click += new System.EventHandler(this.Clear); } private void Digit(object sender, EventArgs e) { Button button = (Button)sender; string digit = button.Text; if (startEdit == true) { textBox1.Text = digit; startEdit = false; return; } else { textBox1.Text = textBox1.Text + digit; } } private void Operation(object sender, EventArgs e) { number1 = double.Parse(textBox1.Text); Button button = (Button)sender; znak = button.Text; startEdit = true; } private void Equal(object sender, EventArgs e) { double result = 0; number2 = double.Parse(textBox1.Text); switch (znak) { case "+": result = number1 + number2; break; case "-": result = number1 - number2; break; case "*": result = number1 * number2; break; case "/": result = number1 / number2; break; } znak = null; textBox1.Text = result.ToString(); number1 = result; startEdit = true; } private void Clear(object sender, EventArgs e) { textBox1.Text = "0"; znak = null; startEdit = true; } } }
using p2_shop.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace p2_shop.Controllers { public class AccountController : Controller { private ShopingEntities db = new ShopingEntities(); // GET: Account public ActionResult Index() { return View(); } public ActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(Korisnici korisnik) { if (ModelState.IsValid) { db.Korisnicis.Add(korisnik); db.SaveChanges(); return RedirectToAction("Index", "Shoping"); } return View(); } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(Korisnici korisnik) { if (ModelState.IsValid) { var detalji = (from userlist in db.Korisnicis where userlist.Korisničko_ime == korisnik.Korisničko_ime && userlist.Šifra == korisnik.Šifra select new { userlist.Korisnik_ID, userlist.Korisničko_ime, userlist.Admin }).ToList(); if (detalji.FirstOrDefault() != null) { Session["Korisnik_ID"] = detalji.FirstOrDefault().Korisnik_ID; Session["Korisničko_ime"] = detalji.FirstOrDefault().Korisničko_ime; Session["Admin"] = detalji.FirstOrDefault().Admin; return RedirectToAction("Welcome"); } } else { ModelState.AddModelError("", "Pogrešne informacije"); } return View(korisnik); } public ActionResult Welcome() { return View(); } public ActionResult LoginMenu() { return PartialView(); } public ActionResult Logout() { Session.Abandon(); return RedirectToAction("Index","Shoping"); } public ActionResult Administracija() { return View(); } } }
using System; using NUnit.Framework; namespace Seterlund.CodeGuard.UnitTests { [TestFixture] public class ComparableValidatorTests { #region ----- Fixture setup ----- /// <summary> /// Called once before first test is executed /// </summary> [TestFixtureSetUp] public void Init() { // Init tests } /// <summary> /// Called once after last test is executed /// </summary> [TestFixtureTearDown] public void Cleanup() { // Cleanup tests } #endregion #region ------ Test setup ----- /// <summary> /// Called before each test /// </summary> [SetUp] public void Setup() { // Setup test } /// <summary> /// Called before each test /// </summary> [TearDown] public void TearDown() { // Cleanup after test } #endregion [Test] public void IsGreaterThan_WhenArgumentIsLessThan_Throws() { // Arrange int arg1 = 0; int arg2 = 1; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsGreaterThan(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsGreaterThan_WhenArgumentIsEqual_Throws() { // Arrange int arg1 = 0; int arg2 = 0; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsGreaterThan(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsGreaterThan_WhenArgumentIsGreather_DoesNotThrow() { // Arrange int arg1 = 1; int arg2 = 0; // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg1).IsGreaterThan(arg2); }); } [Test] public void IsLessThan_WhenArgumentIsGreaterThan_Throws() { // Arrange int arg1 = 1; int arg2 = 0; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsLessThan(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsLessThan_WhenArgumentIsEqual_Throws() { // Arrange int arg1 = 0; int arg2 = 0; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsLessThan(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsLessThan_WhenArgumentIsLess_DoesNotThrow() { // Arrange int arg1 = 0; int arg2 = 1; // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg1).IsLessThan(arg2); }); } [Test] public void IsEqual_WhenArgumentIsNotEqual_Throws() { // Arrange int arg1 = 0; int arg2 = 1; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsEqual(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsEqual_WhenArgumentIsEqual_DoesNotThrow() { // Arrange int arg1 = 0; int arg2 = 0; // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg1).IsEqual(arg2); }); } [Test] public void IsEqual2_WhenArgumentIsNotEqual_Throws() { // Arrange int arg1 = 0; int arg2 = 1; // Act ArgumentOutOfRangeException exception = GetException<ArgumentOutOfRangeException>(() => Guard.Check(() => arg1).IsEqual(arg2)); // Assert AssertArgumentOfRangeException(exception, "arg1"); } [Test] public void IsEqual2_WhenArgumentIsEqual_DoesNotThrow() { // Arrange int arg1 = 0; int arg2 = 0; // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg1).IsEqual(arg2); }); } [Test] public void IsInRange_WhenArgumentBetweenStartAndStop_DoesNotThrow() { // Arrange DateTime arg = DateTime.Now; DateTime start = DateTime.Now.AddDays(-1); DateTime stop = DateTime.Now.AddDays(1); // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg).IsInRange(start, stop); }); } [Test] public void IsInRange_WhenArgumentEqualsStart_DoesNotThrow() { // Arrange DateTime arg = DateTime.Now; DateTime start = arg; DateTime stop = DateTime.Now.AddDays(1); // Act/Assert Assert.DoesNotThrow(() => { Guard.Check(() => arg).IsInRange(start, stop); }); } [Test] public void IsInRange_WhenArgumentOutOfRange_Throws() { // Arrange DateTime arg = DateTime.Now.AddDays(-1); DateTime start = DateTime.Now; DateTime stop = DateTime.Now.AddDays(1); // Act/Assert Assert.Throws<ArgumentOutOfRangeException>(() => { Guard.Check(() => arg).IsInRange(start, stop); }); } #region ----- Helper functions ----- private T GetException<T>(Action action) where T : Exception { T actualException = null; try { action(); } catch (T ex) { actualException = ex; } return actualException; } private static void AssertArgumentOfRangeException(ArgumentOutOfRangeException exception, string message, string paramName, object actualValue) { Assert.IsNotNull(exception); Assert.AreEqual(paramName, exception.ParamName); Assert.AreEqual(actualValue, exception.ActualValue); Assert.AreEqual(string.Format("{0}\r\nParameter name: {1}\r\nActual value was {2}.", message, paramName, actualValue), exception.Message); } private static void AssertArgumentOfRangeException(ArgumentOutOfRangeException exception, string paramName) { Assert.IsNotNull(exception); Assert.AreEqual(paramName, exception.ParamName); Assert.AreEqual(string.Format("Specified argument was out of the range of valid values.\r\nParameter name: {0}", paramName), exception.Message); } private static void AssertArgumentException(ArgumentException exception, string paramName, string message) { Assert.IsNotNull(exception); Assert.AreEqual(paramName, exception.ParamName); Assert.AreEqual(message, exception.Message); } private static void AssertArgumentNullException(ArgumentNullException exception, string paramName, string message) { Assert.IsNotNull(exception); Assert.AreEqual(paramName, exception.ParamName); Assert.AreEqual(message, exception.Message); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AxisPosCore { public interface IInputDataView:IInputView { /// <summary> /// Заголовок формы /// </summary> string Caption { set; } /// <summary> /// Запрос ввода /// </summary> string labelCaption { set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace Roguelord { public class CameraController : MonoBehaviour { // public GameObject player; private Vector3 offset; private bool moveCamera = false; public float panSpeed = 20f; public float panBorderThickness = 10f; public Vector2 panLimit; public float scrollSpeed = 20f; public float minY = 20f; public float maxY = 120f; private Vector3 moveToGrid; private float dist; public float dragSpeed = 5f; private Vector3 dragOrigin; // private Vector3 MouseStart, MouseMove; // private Vector3 derp; // Start is called before the first frame update void Start() { // offset = transform.position - player.transform.position; dist = transform.position.z; // InvokeRepeating("doMove", 0.0f, 3.0f); } public void doMove(Vector3 grid) { Debug.Log("== doMove ==" + grid); // hide sphere beneath map grid.y = -6f; moveToGrid = grid; moveCamera = true; } // Update is called once per frame void Update() { // Vector3 pos = transform.position; // player.transform.position = new Vector3(player.transform.position.x + 0.1f, player.transform.position.y, player.transform.position.z); // Debug.Log(Time.realtimeSinceStartup); // if (Input.GetMouseButtonDown(1)) // { // Debug.Log("* mousebuttondown"); // MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.z, dist); // } // else if (Input.GetMouseButton(1)) // { // Debug.Log("* mousebutton 1"); // MouseMove = new Vector3(Input.mousePosition.x - MouseStart.x, Input.mousePosition.z - MouseStart.z, dist); // // MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.z, dist); // transform.position = new Vector3(transform.position.x + MouseMove.x * Time.deltaTime, transform.position.z + MouseMove.z * Time.deltaTime, dist); // } // if (moveCamera == true) // { // moveCamera = false; // StartCoroutine("MoveCamera"); // } /* if (Input.GetKey("w") || Input.mousePosition.y >= Screen.height - panBorderThickness) { pos.z += panSpeed * Time.deltaTime; } if (Input.GetKey("s") || Input.mousePosition.y <= panBorderThickness) { pos.z -= panSpeed * Time.deltaTime; } if (Input.GetKey("a") || Input.mousePosition.x <= panBorderThickness) { pos.x -= panSpeed * Time.deltaTime; } if (Input.GetKey("d") || Input.mousePosition.x >= Screen.width - panBorderThickness) { pos.x += panSpeed * Time.deltaTime; } */ if (Input.GetAxis("Mouse ScrollWheel") != 0 && !EventSystem.current.IsPointerOverGameObject()) { Vector3 pos = transform.position; Debug.Log("y " + pos.y); float scroll = Input.GetAxis("Mouse ScrollWheel"); pos.y -= scroll * scrollSpeed * 100f * Time.deltaTime; if (pos.y < 15) pos.y = 15; else if (pos.y > 200) pos.y = 200; transform.position = pos; } // pos.x = Mathf.Clamp(pos.x, -panLimit.x, panLimit.x); // pos.y = Mathf.Clamp(pos.y, minY, maxY); // pos.z = Mathf.Clamp(pos.z, -panLimit.y, panLimit.y); // transform.position = pos; } // LateUpdate is called once per frame (after all items in Update have been processed) void LateUpdate() { // if pointer on UI get out! // if (IsPointerOverUIObject()) return; if (EventSystem.current.IsPointerOverGameObject()) return; // if (Input.GetMouseButtonDown(0)) // transform.position = player.transform.position + offset; if (Input.GetMouseButtonDown(0)) { dragOrigin = Input.mousePosition; return; } if (!Input.GetMouseButton(0)) return; Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin); Vector3 move = new Vector3(-pos.x * dragSpeed, 0, -pos.y * dragSpeed); transform.Translate(move, Space.World); } /*IEnumerator MoveCamera() { // var p = player.transform.position; // Debug.Log("MoveCamera " + player.transform.position.x + "/" + moveToGrid.x); /////////////////////////////////// // move /////////////////////////////////// // float seconds = 0.5f; // yield return StartCoroutine(MoveObject(player.transform, player.transform.position, moveToGrid, seconds)); // var targ = new Vector3(player.transform.position.x + 500.0f, player.transform.position.y, player.transform.position.z); // player.transform.position = Vector3.Lerp(player.transform.position, targ, Time.deltaTime); // pos += lerpSpeed; }*/ IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time) { Debug.Log("== MoveObject =="); var i = 0.0f; var rate = 1.0f / time; while (i < 1.0f) { i += Time.deltaTime * rate; thisTransform.position = Vector3.Slerp(startPos, endPos, i); yield return null; } } // private bool IsPointerOverUIObject() // { // PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current); // eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); // List<RaycastResult> results = new List<RaycastResult>(); // EventSystem.current.RaycastAll(eventDataCurrentPosition, results); // return results.Count > 0; // } } }
using System; namespace Day5 { partial class Computer { private readonly int[] _memory; public Computer(int[] memory) { _memory = memory; } public void RunProgram() { var instructionPointer = 0; while (_memory[instructionPointer] != 99) { var instruction = new Instruction(_memory[instructionPointer]); instructionPointer = instruction.opCode switch { 1 => ADD(instructionPointer, instruction), 2 => MUL(instructionPointer, instruction), 3 => INPUT(instructionPointer, instruction), 4 => OUTPUT(instructionPointer, instruction), 5 => JMP_IF_TRUE(instructionPointer, instruction), 6 => JMP_IF_FALSE(instructionPointer, instruction), 7 => JMP_IF_LESS_THAN(instructionPointer, instruction), 8 => JMP_IF_EQUALS(instructionPointer, instruction), _ => throw new System.Exception($"Unexpected opcode {instruction.opCode}") }; } } private int JMP_IF_EQUALS(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); var value2 = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); var address3 = _memory[instructionPointer + 3]; if (value1 == value2) _memory[address3] = 1; else _memory[address3] = 0; return instructionPointer + 4; } private int JMP_IF_LESS_THAN(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); var value2 = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); var address3 = _memory[instructionPointer + 3]; if (value1 < value2) _memory[address3] = 1; else _memory[address3] = 0; return instructionPointer + 4; } private int JMP_IF_FALSE(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); if (value1 == 0) { var newInstructionPointer = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); return newInstructionPointer; } return instructionPointer + 3; } private int JMP_IF_TRUE(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); if (value1 != 0) { var newInstructionPointer = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); return newInstructionPointer; } return instructionPointer + 3; } private int ReadMemory(int address, bool immediateMode) { var location = immediateMode ? address : _memory[address]; return _memory[location]; } private int ADD(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); var value2 = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); var address3 = _memory[instructionPointer + 3]; _memory[address3] = value1 + value2; return instructionPointer + 4; } private int MUL(int instructionPointer, Instruction instruction) { var value1 = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); var value2 = ReadMemory(instructionPointer + 2, instruction.Parameter2InImmediateMode); var address3 = _memory[instructionPointer + 3]; _memory[address3] = value1 * value2; return instructionPointer + 4; } private int INPUT(int instructionPointer, Instruction instruction) { var address1 = _memory[instructionPointer + 1]; Console.Write("> "); var input = int.Parse(Console.ReadLine()); _memory[address1] = input; return instructionPointer + 2; } private int OUTPUT(int instructionPointer, Instruction instruction) { var output = ReadMemory(instructionPointer + 1, instruction.Parameter1InImmediateMode); Console.WriteLine(output); return instructionPointer + 2; } } }
using MQTTnet.Protocol; namespace MQTTnet.Packets { public sealed class MqttConnAckPacket : MqttBasePacket { public MqttConnectReturnCode ReturnCode { get; set; } /// <summary> /// Added in MQTT 3.1.1. /// </summary> public bool IsSessionPresent { get; set; } /// <summary> /// Added in MQTT 5.0.0. /// </summary> public MqttConnectReasonCode ReasonCode { get; set; } /// <summary> /// Added in MQTT 5.0.0. /// </summary> public MqttConnAckPacketProperties Properties { get; set; } = new MqttConnAckPacketProperties(); public override string ToString() { return string.Concat("ConnAck: [ReturnCode=", ReturnCode, "] [ReasonCode=", ReasonCode, "] [IsSessionPresent=", IsSessionPresent, "]"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LinqTOSQL { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HREntities hREntities = new HREntities(); var emp = from employee in hREntities.Employees where employee.cCity == "Norton" select employee; GridView1.DataSource = emp.ToList(); GridView1.DataBind(); } } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace AspCoreBl.Model { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { [Required] [MaxLength(60)] public string FirstName { get; set; } [Required] [MaxLength(60)] public string LastName { get; set; } public bool isSocialLogin { get; set; } } }
using System; namespace Calc { public class Class1 { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace TYNMU.manger { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Session["IsLogin"] = ""; } //登录 protected void BtnOK_Click(object sender, EventArgs e) { string passwd = TxtPassWD.Text.ToString(); //解加密 passwd = Data.DAO.GetMD5(passwd); Response.Write(passwd); string sSql = "select * from T_User where UserName='" + TxtAccount.Text.ToString() + "'and UserPassWD='" + passwd + "'"; DataSet ds = new DataSet(); ds = Data.DAO.Query(sSql); int Rows; Rows = ds.Tables[0].Rows.Count; if (Rows > 0) { Session["UserLevel"] = ds.Tables[0].Rows[0][3].ToString(); Session["IsLogin"] = "Login"; Response.Redirect("TYNFrameset.html"); } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TitanBlog.Data; using TitanBlog.Models; namespace TitanBlog.Controllers.ApiControllers { [Route("api/[controller]")] [ApiController] public class PostsServiceController : ControllerBase { private readonly ApplicationDbContext _context; public PostsServiceController(ApplicationDbContext context) { _context = context; } //This will be where I write the GetTopXPosts //Provide an endpoint to the user (localhost:5001/api/PostsService/GetTopXPosts/4) /// <summary> /// Allow a consumer to request the latest X number of Blog Posts /// </summary> /// <remarks> /// This is what it looks like when you use the remarks tag /// </remarks> /// <param name="num">The number of Posts you want</param> /// <returns></returns> [HttpGet("/GetTopXPosts/{num}")] public async Task<ActionResult<IEnumerable<Post>>> GetTopXPosts(int num) { return await _context.Post.OrderByDescending(p => p.Created).Take(num).ToListAsync(); } } }
using System.Collections.Generic; using System.Windows; using System.Windows.Input; using Slayer.Commands; using Slayer.Models; using Slayer.Services; namespace Slayer.ViewModels { public interface IViewModel { IStatsViewModel StatsViewModel { get; set; } IFightViewModel FightViewModel { get; set; } ILoadViewModel LoadViewModel { get; set; } bool IsSaveCharEnabled { get; } ICommand CreateCharacterCommand { get; } RelayCommand SaveCreateCharCommand { get; } ICommand CancelCreateCharCommand { get; } ICommand VentureOnCommand { get; } Visibility IntroVisibility { get; set; } Visibility AdventureVisibility { get; set; } Visibility CreateCharVisibility { get; set; } Visibility FightVisibility { get; set; } Visibility StatsVisibility { get; set; } Visibility LoadVisibility { get; set; } void CreateCharacter(); void SaveCreateChar(); void CancelCreateChar(); void VentureOn(); } public class ViewModel : BaseViewModel, IViewModel { private readonly IStorageService _storageService; public IGameSystem GameSystem { get; set; } public ViewModel(IStorageService storageService, IGameSystem gameSystem) { _storageService = storageService; GameSystem = gameSystem; IntroVisibility = Visibility.Visible; CreateCharacterCommand = new RelayCommand(CreateCharacter, true); SaveCreateCharCommand = new RelayCommand(SaveCreateChar, IsSaveCharEnabled); LoadCharCommand = new RelayCommand(LoadChar, true); CancelCreateCharCommand = new RelayCommand(CancelCreateChar, true); VentureOnCommand = new RelayCommand(VentureOn, true); } private void CancelLoadChar() { IntroVisibility = Visibility.Visible; } public bool IsSaveCharEnabled { get { bool result = StatsViewModel != null && GameSystem.Character != null && !string.IsNullOrEmpty(CharacterName) && GameSystem.Character.AvailableStatPoints == 0; return result; } } public string CharacterName { get { return GameSystem.Character != null ? GameSystem.Character.Name : string.Empty; } set { GameSystem.Character.Name = value; OnPropertyChanged(); } } public ICommand CreateCharacterCommand { get; private set; } public void CreateCharacter() { GameSystem.NewGame(); StatsViewModel = new StatsViewModel(GameSystem.Character); StatsViewModel.PropertyChanged += delegate { SaveCreateCharCommand.IsEnabled = IsSaveCharEnabled; }; this.PropertyChanged += delegate { SaveCreateCharCommand.IsEnabled = IsSaveCharEnabled; }; CreateCharVisibility = Visibility.Visible; } public RelayCommand SaveCreateCharCommand { get; private set; } public void SaveCreateChar() { _storageService.Save(GameSystem.Character, GameSystem.Character.Name); AdventureVisibility = Visibility.Visible; } public RelayCommand LoadCharCommand { get; private set; } public void LoadChar() { LoadViewModel = new LoadViewModel(); LoadViewModel.Files = new List<string> { "a", "b", "c" }; LoadViewModel.CancelLoadCharCommand = new RelayCommand(CancelLoadChar, true); LoadVisibility = Visibility.Visible; } public ICommand CancelCreateCharCommand { get; private set; } public void CancelCreateChar() { IntroVisibility = Visibility.Visible; GameSystem.Character = null; SaveCreateCharCommand.IsEnabled = IsSaveCharEnabled; OnPropertyChanged("CharacterName"); } public ICommand VentureOnCommand { get; private set; } public void VentureOn() { FightViewModel = new FightViewModel(GameSystem.Character, new Character { Name = "Goblin" }); FightVisibility = Visibility.Visible; } private IStatsViewModel _statsViewModel; public IStatsViewModel StatsViewModel { get { return _statsViewModel; } set { _statsViewModel = value; OnPropertyChanged(); OnPropertyChanged("GameSystem"); } } private ILoadViewModel _loadViewModel; public ILoadViewModel LoadViewModel { get { return _loadViewModel; } set { _loadViewModel = value; OnPropertyChanged(); } } private IFightViewModel _fightViewModel; public IFightViewModel FightViewModel { get { return _fightViewModel; } set { _fightViewModel = value; OnPropertyChanged(); } } private void HideAllViews() { IntroVisibility = Visibility.Collapsed; AdventureVisibility = Visibility.Collapsed; CreateCharVisibility = Visibility.Collapsed; FightVisibility = Visibility.Collapsed; StatsVisibility = Visibility.Collapsed; LoadVisibility = Visibility.Collapsed; } private Visibility _introVisibility; public Visibility IntroVisibility { get { return _introVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _introVisibility = value; OnPropertyChanged(); } } private Visibility _adventureVisibility; public Visibility AdventureVisibility { get { return _adventureVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _adventureVisibility = value; OnPropertyChanged(); } } private Visibility _createCharVisibility; public Visibility CreateCharVisibility { get { return _createCharVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _createCharVisibility = value; OnPropertyChanged(); } } private Visibility _fightVisibility; public Visibility FightVisibility { get { return _fightVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _fightVisibility = value; OnPropertyChanged(); } } private Visibility _statsVisibility; public Visibility StatsVisibility { get { return _statsVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _statsVisibility = value; OnPropertyChanged(); } } private Visibility _loadVisibility; public Visibility LoadVisibility { get { return _loadVisibility; } set { if (value == Visibility.Visible) HideAllViews(); _loadVisibility = value; OnPropertyChanged(); } } } }
//============================================================================== // Copyright (c) 2012-2020 Fiats Inc. All rights reserved. // https://www.fiats.asia/ // using System; using System.Linq; using System.Reactive.Disposables; namespace Financial.Extensions { public static class DateTimeExtensions { public static DateTime Round(this DateTime dt, TimeSpan unit) { return new DateTime(dt.Ticks / unit.Ticks * unit.Ticks, dt.Kind); } } public static class RxUtil { public static TResult AddTo<TResult>(this TResult resource, CompositeDisposable disposable) where TResult : IDisposable { disposable.Add(resource); return resource; } public static void DisposeReverse(this CompositeDisposable disposable) { disposable.Reverse().ForEach(e => e.Dispose()); } } }
using Newtonsoft.Json; namespace SmartHome.Model { public class Scopes { [JsonProperty("scopeId")] public string scopeId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace BanSupport { //[CustomEditor(typeof(ScrollSystem))] public class ScrollSystemEditor : Editor { private ScrollSystem script { get { return target as ScrollSystem; } } public override void OnInspectorGUI() { if (Application.isPlaying) { GUILayout.Label("-----只在运行时候显示-----"); var dic = script.ObjectPoolDic; foreach (var key in dic.Keys) { GUILayout.BeginHorizontal(); GUILayout.Label("预制体:" + key); GUILayout.Label("库存数量:" + dic[key].pool.countInactive.ToString()); GUILayout.EndHorizontal(); } } else { GUILayout.BeginHorizontal(); if (GUILayout.Button("子物体手动刷新")) { script.SetContent(); } if (GUILayout.Button("打开几乘几设置窗口")) { ScrollSystemSetSizeWindow.ShowWindow(script); } GUILayout.EndHorizontal(); //默认排列 //int newCorner = GUILayout.SelectionGrid(script.startCorner, new string[] { //"Left Up", "Right Up" , "Left Down", "Right Down" }, 2); //if (script.startCorner != newCorner) //{ // script.startCorner = newCorner; // script.SetContentChildren(); // EditorUtility.SetDirty(script); //} } DrawDefaultInspector(); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ExpressionEvaluator.Operators { internal class BinaryOperator : Operator<Func<Expression, Expression, Expression>> { public BinaryOperator(string value, int precedence, bool leftassoc, Func<Expression, Expression, Expression> func, ExpressionType expressionType) : base(value, precedence, leftassoc, func) { Arguments = 2; ExpressionType = expressionType; } } internal class TernaryOperator : Operator<Func<Expression, Expression, Expression, Expression>> { public TernaryOperator(string value, int precedence, bool leftassoc, Func<Expression, Expression, Expression, Expression> func) : base(value, precedence, leftassoc, func) { Arguments = 3; } } }
// <copyright file="DatabaseCreator.cs" company="TreverGannonsMadExperiment"> // Copyright (c) TreverGannonsMadExperiment. All rights reserved. // </copyright> namespace Database { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Database.DatabaseUpdates; using Microsoft.Extensions.Configuration; using Npgsql; /// <summary> /// A class used to create a database for the fitness tracker app. /// </summary> public class DatabaseCreator { /// <summary> /// Initializes a new instance of the <see cref="DatabaseCreator"/> class. /// </summary> /// <param name="configuration">The configuration to use. Needs to contain a connection string.</param> public DatabaseCreator(IConfiguration configuration) { this.Configuration = configuration; } /// <summary> /// Gets the configuration the solution is using. /// </summary> public IConfiguration Configuration { get; } /// <summary> /// Gets or Sets connection string to use. /// </summary> public string ConnectionStringName { get; set; } = "Creation"; /// <summary> /// Gets value of the connection string. /// </summary> private string ConnectionString { get { return this.Configuration.GetConnectionString(this.ConnectionStringName); } } /// <summary> /// Drops the existing database with that name, and creates a new one. WARNING DANGEROUS. /// Please ensure the databaseName exists in the appsettings.json. /// </summary> /// <param name="databaseName">The database name to create.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task CreateDatabase(string databaseName) { using (var con = new NpgsqlConnection(this.ConnectionString)) { con.Open(); using (var cmd = new NpgsqlCommand( $@"DROP DATABASE IF EXISTS {databaseName}; CREATE DATABASE {databaseName};", con)) { await cmd.ExecuteScalarAsync(); } } await this.UpdateDatabase(databaseName); } /// <summary> /// Destorys a database, and all of its tables. (Not the tables!). /// </summary> /// <param name="databaseName">The database to destroy.</param> /// <returns>A task to execute the destory.</returns> public async Task DestoryDatabaseMuhahaha(string databaseName) { using (var con = new NpgsqlConnection(this.ConnectionString)) { con.Open(); using (var cmd = new NpgsqlCommand( $@" SELECT pid, pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid(); DROP DATABASE IF EXISTS {databaseName};", con)) { await cmd.ExecuteScalarAsync(); } } } private async Task UpdateDatabase(string databaseName) { this.ConnectionStringName = databaseName; using (var con = new NpgsqlConnection(this.ConnectionString)) { con.Open(); var updates = this.GetClassesThatImplementInterface<IUpdate>(); foreach (var update in updates) { using (var cmd = new NpgsqlCommand(update.UpdateSQL, con)) { await cmd.ExecuteScalarAsync(); } } } } private List<T> GetClassesThatImplementInterface<T>() { return Assembly.GetExecutingAssembly() .GetTypes() .Where(type => typeof(T).IsAssignableFrom(type)) .Where(type => !type.IsAbstract && !type.IsGenericType && type.GetConstructor(new Type[0]) != null) .Select(type => (T)Activator.CreateInstance(type)) .ToList(); } } }
namespace Proyecto.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Administrador", c => new { IdAdministrador = c.Int(nullable: false, identity: true), Nombre = c.String(), ApPaterno = c.String(), ApMaterno = c.String(), Dni = c.String(), Direccion = c.String(), Pass = c.String(), }) .PrimaryKey(t => t.IdAdministrador); CreateTable( "dbo.Cliente", c => new { IdCliente = c.Int(nullable: false, identity: true), Nombre = c.String(), Dni = c.String(), Direccion = c.String(), }) .PrimaryKey(t => t.IdCliente); CreateTable( "dbo.DetalleVenta", c => new { IdDetalleVenta = c.Int(nullable: false, identity: true), IdCliente = c.Int(nullable: false), IdProducto = c.Int(nullable: false), IdVendedor = c.Int(nullable: false), Fecha = c.DateTime(nullable: false), Total = c.Decimal(nullable: false, precision: 18, scale: 2), Cantidad = c.Int(nullable: false), Estado = c.Int(nullable: false), }) .PrimaryKey(t => t.IdDetalleVenta); CreateTable( "dbo.Producto", c => new { IdProducto = c.Int(nullable: false, identity: true), Nombre = c.String(), Stock = c.Int(nullable: false), Precio = c.Decimal(nullable: false, precision: 18, scale: 2), Descripcion = c.String(), UnidadMedida = c.String(), }) .PrimaryKey(t => t.IdProducto); CreateTable( "dbo.Vendedor", c => new { IdVendedor = c.Int(nullable: false, identity: true), Nombre = c.String(), ApPaterno = c.String(), ApMaterno = c.String(), Dni = c.String(), Direccion = c.String(), Pass = c.String(), }) .PrimaryKey(t => t.IdVendedor); } public override void Down() { DropTable("dbo.Vendedor"); DropTable("dbo.Producto"); DropTable("dbo.DetalleVenta"); DropTable("dbo.Cliente"); DropTable("dbo.Administrador"); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; namespace _06.Zipping_Sliced_Files { class ZippingSlicedFile { const string InputFile = @"..\..\input.txt"; const string OutputFolder = @"..\..\_SplitFilesOutput\"; const int Parts = 5; static List<string> files; private static void Main() { SplitFiles(Parts, InputFile, OutputFolder); AssembleFiles(); } static void SplitFiles(int parts, string inputFile, string outputFolder) { using (var inputStream = new FileStream(inputFile, FileMode.Open)) { files = new List<string>(); for (int part = 1; part <= parts; part++) { string outputFileName = Path.GetFileNameWithoutExtension(inputFile) + "-Part" + part + Path.GetExtension(inputFile) + ".gz"; string outputFilePath = outputFolder + outputFileName; files.Add(outputFilePath); var partSize = (int)Math.Ceiling((double)inputStream.Length / parts); using (var outputStream = new FileStream(outputFilePath, FileMode.Create)) { var buffer = new byte[partSize]; int readBytes = inputStream.Read(buffer, 0, partSize); using (var zipStream = new GZipStream(outputStream, CompressionMode.Compress, false)) zipStream.Write(buffer, 0, readBytes); //outputStream.Write(buffer, 0, readBytes); } } } Console.WriteLine("Done! Files written at " + Path.GetFullPath(outputFolder)); } static void AssembleFiles() { var outputFile = $"{OutputFolder}{Path.GetFileName(InputFile)}"; if (File.Exists(outputFile)) File.Delete(outputFile); using (var destination = new FileStream(outputFile, FileMode.Append)) { foreach (var file in files) { using (var source = new FileStream(file, FileMode.Open)) { using (var gZip = new GZipStream(source, CompressionMode.Decompress)) { var buffer = new byte[file.Length]; while (true) { int readBytes = gZip.Read(buffer, 0, buffer.Length); if (readBytes == 0) { break; } destination.Write(buffer, 0, readBytes); } } } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Domaci8_9_10 { public partial class frmPlacanje : Form { List<Placanje> placanjeList = new List<Placanje>(); string akcija = ""; int indeksSelektovanog = -1; public frmPlacanje() { InitializeComponent(); dgPlacanje.AllowUserToAddRows = false; dgPlacanje.AllowUserToDeleteRows = false; dgPlacanje.ReadOnly = true; dgPlacanje.AutoGenerateColumns = false; dgPlacanje.Columns.Add("ID", "ID"); dgPlacanje.Columns["ID"].Visible = false; dgPlacanje.Columns.Add("Nacin", "Nacin"); dgPlacanje.Columns.Add("datumKupovine", "Datum"); txtDisabled(); btnChangeEnabled(); btnSubmitDisabled(); prikaziPlacanjeDGV(); } private void txtDisabled() { txtNacin.Enabled = false; dtpPlacanje.Enabled = false; } private void txtEnabled() { txtNacin.Enabled = true; dtpPlacanje.Enabled = true; } private void btnChangeDisabled() { btnDodaj.Enabled = false; btnPromeni.Enabled = false; btnObrisi.Enabled = false; } private void btnChangeEnabled() { btnDodaj.Enabled = true; btnPromeni.Enabled = true; btnObrisi.Enabled = true; } private void btnSubmitDisabled() { btnPotvrdi.Enabled = false; btnOdustani.Enabled = false; } private void btnSubmitEnabled() { btnPotvrdi.Enabled = true; btnOdustani.Enabled = true; } private void ponistiUnosTxt() { txtNacin.Text = ""; dtpPlacanje.Value = DateTime.Now; } private void prikaziPlacanjeTxt() { int idSelektovanog = (int)dgPlacanje.SelectedRows[0].Cells["ID"].Value; Placanje selektovaniPlacanje = placanjeList.Where(x => x.ID == idSelektovanog).FirstOrDefault(); if (selektovaniPlacanje != null) { txtNacin.Text = selektovaniPlacanje.NacinPlacanja; dtpPlacanje.Value = selektovaniPlacanje.Datum; } } private void prikaziPlacanjeDGV() { placanjeList = new Placanje().ucitajPlacanje(); dgPlacanje.Rows.Clear(); for (int i = 0; i < placanjeList.Count; i++) { dgPlacanje.Rows.Add(); dgPlacanje.Rows[i].Cells["ID"].Value = placanjeList[i].ID; dgPlacanje.Rows[i].Cells["Nacin"].Value = placanjeList[i].NacinPlacanja; dgPlacanje.Rows[i].Cells["datumKupovine"].Value = placanjeList[i].Datum; } ponistiUnosTxt(); dgPlacanje.CurrentCell = null; if (placanjeList.Count > 0) { if (indeksSelektovanog != -1) dgPlacanje.Rows[indeksSelektovanog].Selected = true; else dgPlacanje.Rows[0].Selected = true; prikaziPlacanjeTxt(); } } private void btnDodaj_Click(object sender, EventArgs e) { ponistiUnosTxt(); txtEnabled(); btnSubmitEnabled(); btnChangeDisabled(); akcija = "dodaj"; } private void btnObrisi_Click(object sender, EventArgs e) { if (dgPlacanje.SelectedRows.Count > 0) { if (MessageBox.Show("Da li zelite da obrisete odabrano placanje?", "Potvrda brisanja", MessageBoxButtons.YesNo) == DialogResult.Yes) { int idSelektovanog = (int)dgPlacanje.SelectedRows[0].Cells["ID"].Value; Placanje selektovaniPlacanje = placanjeList.Where(x => x.ID == idSelektovanog).FirstOrDefault(); if (selektovaniPlacanje != null) { selektovaniPlacanje.obrisiPlacanje(); } indeksSelektovanog = -1; prikaziPlacanjeDGV(); } } else { MessageBox.Show("Nema unetih podataka"); } } private void btnPromeni_Click(object sender, EventArgs e) { if (dgPlacanje.SelectedRows.Count > 0) { txtEnabled(); btnSubmitEnabled(); btnChangeDisabled(); akcija = "promeni"; } else { MessageBox.Show("Nema unetih podataka"); } } private void btnPotvrdi_Click(object sender, EventArgs e) { try { if (akcija == "promeni") { int idSelektovanog = (int)dgPlacanje.SelectedRows[0].Cells["ID"].Value; Placanje selektovaniPlacanje = placanjeList.Where(x => x.ID == idSelektovanog).FirstOrDefault(); selektovaniPlacanje.NacinPlacanja = txtNacin.Text; selektovaniPlacanje.Datum = dtpPlacanje.Value.Date; selektovaniPlacanje.azurirajPlacanje(); indeksSelektovanog = dgPlacanje.SelectedRows[0].Index; } else if (akcija == "dodaj") { Placanje Placanje = new Placanje(); Placanje.NacinPlacanja = txtNacin.Text; Placanje.Datum = dtpPlacanje.Value; Placanje.dodajPlacanje(); indeksSelektovanog = dgPlacanje.Rows.Count; } txtDisabled(); btnSubmitDisabled(); btnChangeEnabled(); akcija = ""; prikaziPlacanjeDGV(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnOdustani_Click(object sender, EventArgs e) { txtDisabled(); btnSubmitDisabled(); btnChangeEnabled(); } private void dgPlacanjeovi_CellClick(object sender, DataGridViewCellEventArgs e) { if (dgPlacanje.CurrentRow != null) { dgPlacanje.Rows[dgPlacanje.CurrentRow.Index].Selected = true; prikaziPlacanjeTxt(); } } } }
public class Story { //陌生人 public static int meet(int task_id, int step) { Task.talk("陌生人","少年,我看你骨骼惊奇,天资聪慧,今有鞋精作怪,你可愿意帮忙?","role/face4_2.png",Message.Face.RIGHT); Task.talk("主角","鞋精?","role/face2_1.png"); Task.talk("陌生人","没错,自从这鞋精有了法力后,村里不得安宁,希望你可以出手相助!","role/face4_2.png",Message.Face.RIGHT); Task.talk("主角","好吧!","role/face2_1.png"); Task.talk("陌生人", "这是我家祖传的短剑,也许可以帮助下你。", "role/face4_2.png", Message.Face.RIGHT); Task.tip("获得短剑X3"); Task.add_item(2,3); return 0; } public static int aftermeet(int task_id, int step) { Task.talk("陌生人","村子就靠你了","role/face4_2.png",Message.Face.RIGHT); return 0; } public static int reward(int task_id, int step) { Task.talk("陌生人", "虽然打败鞋精,但是我怕他会回来报仇,将来可能会更难对付。我这有本祖传秘籍,记载了些法术,我自己看不懂,倒不如送给你。若鞋精再来,还可以助你", "role/face4_2.png", Message.Face.RIGHT); Task.tip("获得《九阳真经》"); Task.add_item(5,1); return 0; } public static int afterreward(int task_id, int step) { Task.talk("陌生人","若鞋精再来,望少侠出手。","role/face4_2.png",Message.Face.RIGHT); return 0; } public static int shoe(int task_id, int step) { Task.tip("一双破鞋"); return 0; } public static int shoefight(int task_id, int step) { if (step == 0) { Task.talk("鞋子怪", "(生气)mmp", ""); Player.status = Player.Status.WALK; Task.fight(new int[] { -1, 1, -1 }, "fight/f_scene.png", 0, 0, 1, -1, 10); Task.block(); return 1; } else { if (Fight.iswin == 1) { Task.tip("捡起破鞋"); Task.set_npc_pos(6, -1000, -1000); Task.p[0] = 2; return 0; } else { return 0; } } } public static int save(int task_id, int step) { Task.talk("女孩","我可以保存游戏哦!",""); Save.show(0); Task.block(); return 0; } public static int shop(int task_id, int step) { Shop.show(new int[] { 0, 1, 2, 3, 4, -1, -1 }); //商人所卖物品 Task.block(); return 0; } public static int play_anm(int task_id, int step) { Task.play_npc_anm(4,0); return 0; } public static int tip(int task_id, int step) { Task.tip("我会动!"); return 0; } }
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests { public class GetAccountLegalEntityRequest : IGetApiRequest { private readonly long _accountLegalEntityId; public string GetUrl => $"accountLegalEntity/{_accountLegalEntityId}"; public GetAccountLegalEntityRequest(long accountLegalEntityId) { _accountLegalEntityId = accountLegalEntityId; } } }
namespace SubC.Attachments { using System; using System.Collections.Generic; using UnityEngine; [Serializable] public abstract class AttachEventTrigger { [Serializable] public class Entry { public AttachEventType eventType; public AttachEvent callback = new AttachEvent(); public bool hideInInspector = true; } public abstract AttachEventType[] supportedEventTypes { get; } [SerializeField] public List<Entry> entries = new List<Entry>(); public AttachEvent GetOrCreateEvent(AttachEventType eventType, bool hideInInspector = true) { foreach (Entry e in entries) { if (e.eventType == eventType) { if (!hideInInspector) e.hideInInspector = false; return e.callback; } } Entry entry = new Entry(); entry.eventType = eventType; if (!hideInInspector) entry.hideInInspector = false; entries.Add(entry); return entry.callback; } public bool HasVisibleEntryForEventType(AttachEventType eventType) { foreach (Entry e in entries) if (e.eventType == eventType) return !e.hideInInspector; return false; } } }
using StardewValley.Buildings; using System.Collections.Generic; using System.Linq; namespace BitwiseJonMods { class BuildingContentsInfo { public int NumberOfContainers { get; set; } public int NumberReadyToHarvest { get; set; } public int NumberReadyToLoad { get; set; } public IEnumerable<StardewValley.Object> Containers { get; set; } public IEnumerable<StardewValley.Object> ReadyToHarvestContainers { get; set; } public IEnumerable<StardewValley.Object> ReadyToLoadContainers { get; set; } public BuildingContentsInfo(Building building, List<string> supportedContainerTypes) { if (building == null || building.indoors.Value == null) { Containers = null; NumberOfContainers = 0; NumberReadyToHarvest = 0; NumberReadyToLoad = 0; } else { var indoors = building.indoors.Value; var objects = indoors.objects.Values; Containers = objects.Where(o => supportedContainerTypes.Any(c => o.Name == c)).Select(o => o); ReadyToHarvestContainers = Containers.Where(c => c.heldObject.Value != null && c.readyForHarvest.Value == true); ReadyToLoadContainers = Containers.Where(c => c.heldObject.Value == null && c.readyForHarvest.Value == false); NumberOfContainers = Containers.Count(); NumberReadyToHarvest = ReadyToHarvestContainers.Count(); NumberReadyToLoad = NumberReadyToHarvest + ReadyToLoadContainers.Count(); } } } }
using System; using UnityEngine.Events; namespace UnityAtoms.BaseAtoms { /// <summary> /// None generic Unity Event of type `FloatPair`. Inherits from `UnityEvent&lt;FloatPair&gt;`. /// </summary> [Serializable] public sealed class FloatPairUnityEvent : UnityEvent<FloatPair> { } }
 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading.Tasks; using Newtonsoft.Json; using PFRCenterGlobal.ViewModels.Maps; using Xamarin.Forms; using Xamarin.Forms.Maps; namespace PFRCenterGlobal.Views.AuthZone { public partial class MapPage : ContentPage { public MapPage() { InitializeComponent(); Task.Delay(2000); UpdateMap(); } List<Place> placesList = new List<Place>(); private async void UpdateMap() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(AppShell)).Assembly; Stream stream = assembly.GetManifestResourceStream("PFRCenterGlobal.Places.json"); string text = string.Empty; using (var reader = new StreamReader(stream)) { text = reader.ReadToEnd(); } var resultObject = JsonConvert.DeserializeObject<Places>(text); foreach (var place in resultObject.results) { placesList.Add(new Place { PlaceName = place.name, Address = place.vicinity, Location = place.geometry.location, Position = new Position(place.geometry.location.lat, place.geometry.location.lng), //Icon = place.icon, //Distance = $"{GetDistance(lat1, lon1, place.geometry.location.lat, place.geometry.location.lng, DistanceUnit.Kiliometers).ToString("N2")}km", //OpenNow = GetOpenHours(place?.opening_hours?.open_now) }); } MyMap.ItemsSource = placesList; //PlacesListView.ItemsSource = placesList; //var loc = await Xamarin.Essentials.Geolocation.GetLocationAsync(); MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(55.811871, 37.6529762), Distance.FromKilometers(100))); } catch (Exception ex) { Debug.WriteLine(ex); } } } }
using AGD.DataAccess; using ADP.BusinessLogic.Entity; using System.Collections.Generic; using System.Linq; using System; namespace ADP.BusinessLogic { public class UserBusinessLogic { public static bool CreateEmployee(string nama, string tempLahir, DateTime tglLahir, string noTlp, string email, string jabatan) { return new UserDataAccess().CreateEmployee(nama, tempLahir, tglLahir, noTlp, email, jabatan); } public static bool CreateUser(string Username, string Password, string IdRole) { return new UserDataAccess().CreateUser(Username, Password, IdRole); } } }
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Docller.Core.Common { public interface ILocalStorage { string CreateTempFolder(); string EnsureCacheFolder(string folderName); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Real : Scenario { void Start() { this.gameObject.transform.localScale = new Vector3 (0.01f, 0.01f); } public IEnumerator Anim(float finalSize, string text) { if (this.gameObject != null) { while (Mathf.Abs(this.gameObject.transform.localScale.y) <= Mathf.Abs(finalSize)) { this.gameObject.transform.localScale += new Vector3 (0.32f, 0.4f, 0f); yield return null; } GameObject dialog = GameObject.Find("TextReal"); dialog.gameObject.GetComponent<Text>().text = text; } } public override void Put () { base.Put (); sc.sortingLayerName = "Game"; sc.sortingOrder = 30; this.tag = "Dog"; this.gameObject.transform.localScale = new Vector3 (4f, 3f); this.imageSize = sc.bounds.size; GameObject dialog = GameObject.Find ("TextReal"); Instantiate (this, new Vector3 (Camera.main.transform.position.x, Camera.main.transform.position.y), Quaternion.identity); } }
using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; using Microsoft.Xna.Framework; namespace DuckingAround.NPCs.Towns.EnemySpawnerNPC { [AutoloadHead] public class EnemySpawnerNPC : ModNPC { private int center { get => (int)npc.ai[0]; set => npc.ai[0] = value; } private int captiveType { get => (int)npc.ai[1]; set => npc.ai[1] = value; } public static int enemyCount = 0; public static int spawnerActive; public static int playerClosest; public override string Texture => "DuckingAround/NPCs/Towns/EnemySpawnerNPC/EnemySpawnerNPC"; public override string[] AltTextures => new[] { "DuckingAround/NPCs/Towns/EnemySpawnerNPC/EnemySpawnerNPC_Alt_1" }; public override bool Autoload(ref string name) { name = "Enemy Spawner"; return mod.Properties.Autoload; } public override void SetStaticDefaults() { Main.npcFrameCount[npc.type] = 16; } public override void SetDefaults() { npc.townNPC = true; npc.friendly = true; npc.width = 32; npc.height = 55; npc.aiStyle = -1; npc.lifeMax = 250; npc.scale = 1.5f; npc.knockBackResist = 0f; npc.lifeRegenCount = 100; npc.noGravity = true; npc.immortal = true; npc.netAlways = true; npc.dontTakeDamageFromHostiles = true; } public override void FindFrame(int frameHeight) { this.npc.frameCounter += .20; this.npc.frameCounter %= (double)Main.npcFrameCount[this.npc.type]; this.npc.frame.Y = (int)this.npc.frameCounter * frameHeight; } public override string TownNPCName() { return "EnemySpawner"; } public override void SetChatButtons(ref string button, ref string button2) { button = "Enable spawner"; button2 = "Disable spawner"; } public override void OnChatButtonClicked(bool firstButton, ref bool shop) { if (firstButton) { Player player = Main.player[this.npc.FindClosestPlayer()]; DuckingWorld.spawnerX = (int)player.position.X; DuckingWorld.spawnerY = (int)player.position.Y - 64; DuckingWorld.spawnerActive = 1; NetMessage.SendData(MessageID.WorldData); } else { DuckingWorld.spawnerActive = 0; NetMessage.SendData(MessageID.WorldData); } } public override string GetChat() { if (DuckingWorld.spawnerActive == 1) { return "I am currently spawning " + DuckingWorld.EggNameMethod() + "."; } else { return "I am not currently active."; } } public override void AI() { if (Main.slimeRain) { Main.StopSlimeRain(); NetMessage.SendData(MessageID.WorldData); } else if (DuckingWorld.spawnerActive == 1 && Main.rand.Next(0, DuckingWorld.spawnRate) == 60 && enemyCount <= 50) { DuckingAround.HandleNPC(DuckingWorld.EggSpawnMethod()); enemyCount += 1; } } public static void SetPosition(NPC npc) { EnemySpawnerNPC modNPC = npc.modNPC as EnemySpawnerNPC; if (modNPC != null) { Vector2 center = Main.npc[modNPC.center].Center; double angle = Main.npc[modNPC.center].ai[3] + 2.0 * Math.PI * modNPC.captiveType / 5.0; npc.position = center + 300f * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) - npc.Size / 2f; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adventure_Game { class AdventureGame { //member variables public Player1 player1; public Player2 player2; public Destination destination; public Course course; //constructor public AdventureGame() { player1 = new Player1(); player2 = new Player2(); destination = new Destination(); course = new Course(); } //member methods } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; // TODO: replace these with the processor input and output types. using TInput = System.String; using TOutput = System.String; namespace ModelWithNormalMap { [ContentProcessor] public class ModelWithNormalmapProcessor : ModelProcessor { public override ModelContent Process(NodeContent input, ContentProcessorContext context) { ModelContent model = base.Process(input, context); foreach (ModelMeshContent modelMesh in model.Meshes) { foreach (ModelMeshPartContent meshPart in modelMesh.MeshParts) { MaterialContent materialContent = meshPart.Material; foreach (var texture in materialContent.Textures) { if (texture.Value != null) meshPart.Tag = texture.Value.Filename; } } } return model; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; using System.Web; namespace Juicy.DirtCheapDaemons.Http { public class HttpServer { public const int DefaultPortNumber = 8081; private TcpListener _listener; private Thread _serverThread; private readonly MountPointResolver _resolver = new MountPointResolver(); public HttpServer() : this(DefaultPortNumber) { } public HttpServer(int portNumber) { MountPoints = new List<MountPoint>(); PortNumber = portNumber; } private bool IsRunning { get { return _serverThread != null; } } private int _portNumber; public int PortNumber { get { return _portNumber; } set { if (IsRunning) { throw new InvalidOperationException("Cannot change the port number after the server has been started."); } _portNumber = value; } } public IList<MountPoint> MountPoints { get; private set; } public string RootUrl { get { return string.Format("http://localhost:{0}/", PortNumber); } } public void Mount(string virtualDir, string physicalDirectory) { Mount(virtualDir, new StaticFileHandler(physicalDirectory)); } public void Mount(string virtualDir, Action<IRequest, IResponse> handler) { Mount(virtualDir, new InlineHandler(handler)); } public void Mount(string virtualDir, IMountPointHandler handler) { MountPoints.Add(new MountPoint { VirtualPath = virtualDir, Handler = handler }); } public void Unmount(string virtualDir) { var mount = MountPoints.FirstOrDefault(m => m.VirtualPath.Equals(virtualDir, StringComparison.OrdinalIgnoreCase)); if (mount != null) { MountPoints.Remove(mount); } } public void UnmountAll() { MountPoints.Clear(); } public void Start() { Shutdown(); var host = Dns.GetHostEntry("localhost"); var localIP = host.AddressList[0]; _listener = new TcpListener(localIP, PortNumber); _listener.Start(); _serverThread = new Thread(WaitForConnection); _serverThread.Start(); Console.WriteLine("Juicy Web Server ready at http://localhost:" + PortNumber + "/"); } public void Shutdown() { if (_listener != null) { _listener.Stop(); _listener = null; } if (_serverThread != null) { _serverThread.Abort(); _serverThread = null; } } public void WaitForConnection() { try { while (true) { //Accept a new connection using (var socket = _listener.AcceptSocket()) { if(socket.Connected) { Console.WriteLine("\nRequest from IP {0}\n", socket.RemoteEndPoint); string reqText = GetRequestText(socket); if (string.IsNullOrEmpty(reqText)) { Console.WriteLine("Empty request, canceling."); socket.Close(); continue; } string[] lines = reqText.Split(new[] {"\r\n"}, StringSplitOptions.None); string firstLine = lines[0]; //(starting n the next line is what a GET request looks like, line break = \r\n //GET /some/path/in/the/server.html HTTP/1.1 //Host: localhost:8081 //User-Agent: Mozilla/5.0 (blah blah blah) //Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 //Accept-Language: en-us,en;q=0.5 //Accept-Encoding: gzip,deflate //Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 //Keep-Alive: 300 //Connection: keep-alive //Cookie: cookie1=val1; cookie2=val2; string vpath = "/"; //IMountPointHandler handler; MountPoint mount = null; if (CheckIfHttpRequest(firstLine)) { string[] httpCommand = firstLine.Split(' '); //so this must be an HTTP request var httpVerb = httpCommand[0]; //a vpath must have been given in the command vpath = httpCommand[1]; Console.WriteLine("Requested path:" + vpath); if(ValidateHttpVerb(httpVerb)) { mount = FindMount(vpath); } } if(mount == null) { mount = CreateUnacceptableMountPoint(vpath); } Console.WriteLine("Request being handled at vpath: {0}, by handler: {1}", mount.VirtualPath, mount.Handler); var request = new RequestFactory().Create(lines, mount, vpath); var response = CreateResponse(HttpStatusCode.OK, "OK"); mount.Handler.Respond(request, response); SendResponse(response, socket); socket.Close(); } } Thread.Sleep(50); } } catch (SocketException) { } } private MountPoint CreateUnacceptableMountPoint(string vpath) { var handler = new EmptyHttpResponseHandler(HttpStatusCode.NotAcceptable, "Not acceptable"); return new MountPoint { Handler = handler, VirtualPath = vpath }; } private bool CheckIfHttpRequest(string line) { var cmd = line.Split(' '); return cmd.Length == 3 && cmd[2].StartsWith("HTTP", StringComparison.OrdinalIgnoreCase); } private static Response CreateResponse(HttpStatusCode statusCode, string statusMessage) { var response = new Response { StatusCode = statusCode, StatusMessage = statusMessage }; //add some standard headers that can be replaced by // the handler if needed response["Cache-Control"] = "private"; response["Content-Type"] = "text/html; charset=utf-8"; response["Server"] = "Juicy/1.0"; response["Date"] = DateTime.UtcNow.ToString("ddd, d MMM yyyy HH:mm:ss 'GMT'"); return response; } private static string GetRequestText(Socket socket) { byte[] bytes = new byte[1024]; socket.Receive(bytes, bytes.Length, 0); string data = Encoding.ASCII.GetString(bytes); return data.TrimEnd('\0'); } private static bool ValidateHttpVerb(string httpVerb) { //At present we will only deal with GET type if ( !httpVerb.Equals("GET", StringComparison.OrdinalIgnoreCase) && !httpVerb.Equals("POST", StringComparison.OrdinalIgnoreCase) ) { Console.WriteLine("Requested HTTP verb '{0}' not supported.", httpVerb); return false; } return true; } private MountPoint FindMount(string requestedVirtualDir) { return _resolver.Resolve(MountPoints, requestedVirtualDir) ?? new MountPoint { VirtualPath = "/", Handler = new ResourceNotFoundHandler() }; } private void SendResponse(Response response, Socket socket) { socket.Send(Encoding.UTF8.GetBytes( string.Format("HTTP/1.1 {0} {1}\r\n", (int)response.StatusCode, response.StatusMessage) )); string body = response.GetResponseBodyText(); var buffer = Encoding.UTF8.GetBytes(body); response["Content-Length"] = buffer.Length.ToString(); SendAllHeaders(response, socket); socket.Send(Encoding.UTF8.GetBytes("\r\n")); //end of headers socket.Send(buffer); } private static void SendAllHeaders(IResponse response, Socket socket) { foreach (var h in response.Headers) { SendHeader(h.Key, h.Value, socket); } } private static void SendHeader(string name, string value, Socket socket) { socket.Send(Encoding.UTF8.GetBytes(string.Format("{0}: {1}\r\n", name, value))); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace Library.Migrations { public partial class updateTransaction : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CheckoutId", table: "Patrons"); migrationBuilder.DropColumn( name: "CheckoutId", table: "Copies"); migrationBuilder.AddColumn<bool>( name: "ToBeCheckedOut", table: "Copies", nullable: false, defaultValue: false); migrationBuilder.CreateIndex( name: "IX_Copies_BookId", table: "Copies", column: "BookId"); migrationBuilder.CreateIndex( name: "IX_Checkouts_CopyId", table: "Checkouts", column: "CopyId"); migrationBuilder.AddForeignKey( name: "FK_Checkouts_Copies_CopyId", table: "Checkouts", column: "CopyId", principalTable: "Copies", principalColumn: "CopyId", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Copies_Books_BookId", table: "Copies", column: "BookId", principalTable: "Books", principalColumn: "BookId", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Checkouts_Copies_CopyId", table: "Checkouts"); migrationBuilder.DropForeignKey( name: "FK_Copies_Books_BookId", table: "Copies"); migrationBuilder.DropIndex( name: "IX_Copies_BookId", table: "Copies"); migrationBuilder.DropIndex( name: "IX_Checkouts_CopyId", table: "Checkouts"); migrationBuilder.DropColumn( name: "ToBeCheckedOut", table: "Copies"); migrationBuilder.AddColumn<int>( name: "CheckoutId", table: "Patrons", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "CheckoutId", table: "Copies", nullable: false, defaultValue: 0); } } }
using System.Collections.Generic; using UnityEngine; using Object = System.Object; public class GameDataFromOverlook : MonoBehaviour { //public GameDataToOverlook gameDataToOverlook; [HideInInspector] public List<SettingsConfigObject> settingsConfigObjects; //Create references to all the GameObjects that have settings functions on them. private List<GameObject> allGameObjects; private void Start() { //settingsConfigObjects = gameDataToOverlook.allSettingsConfigObjects; allGameObjects = new List<GameObject>(); //Set those object's values using the list of Settings Config Objects. for (int i = 0; i < settingsConfigObjects.Count; i++) { //allGameObjects.Add(settingsConfigObjects[i].GetGameObject()); } } class SettingBreakdown { public string key; public string value; public SettingBreakdown(string _key, string _value) { key = _key; value = _value; } } class SettingsContainer { public static List<object> items; } public void ParseSettings(string settingsJson) { var settingsObject = JsonUtility.FromJson<SettingsContainer>("{\"items\":" + settingsJson + "}"); foreach (SettingBreakdown setting in SettingsContainer.items) { CallMethodOnGameObject(setting.key, setting.value); } } //Add all methods to change game settings here. void CallMethodOnGameObject(string method, object parameter) { /* string _gameObject = ""; string _method = ""; foreach (var settingsConfigObject in settingsConfigObjects) { if (settingsConfigObject.settingName == method) { _gameObject = settingsConfigObject.gameObjectName; _method = settingsConfigObject.methodName; } } GameObject.Find(_gameObject).SendMessage(_method, parameter); */ } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StartElevator : MonoBehaviour { public Animator leftDoorAnimator; public Animator rightDoorAnimator; // Start is called before the first frame update void Start() { leftDoorAnimator.SetTrigger("finishTrigger"); rightDoorAnimator.SetTrigger("finishTrigger"); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; namespace HospitalSystem.Models { public partial class appointment_record { public long AppointmentID { get; set; } public Nullable<long> DoctorID { get; set; } public Nullable<long> PatientID { get; set; } public Nullable<System.DateTime> AppointmentTime { get; set; } public virtual doctor doctor { get; set; } public virtual patient patient { get; set; } } }
using AlgorithmProblems.Arrays.ArraysHelper; using AlgorithmProblems.Heaps.HeapHelper; using AlgorithmProblems.matrix_problems; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Distributed_Algorithms { /// <summary> /// You are given k sorted arrays and you need to merge them into one sorted array. /// Usually the k sorted arrays are in different computers and they gets merged in one computer and are written back to a cluster. /// </summary> class KWayMerge { /// <summary> /// Algo: use a priority queue and save the cell location as the object and the cell value as the priority. /// 2. Initialize the priority queue and add the 0th column values for all rows. /// 3. extract min and add it to the output array. /// 4. insert the next element to the extracted element /// 5. Do 3,4 till the priority queue is empty /// </summary> /// <param name="mat"></param> /// <returns></returns> public int[] DoKWayMerge(int[,] mat) { int[] sortedArr = new int[mat.GetLength(0) * mat.GetLength(1)]; int sortedArrIndex = 0; int k = mat.GetLength(0); // initialization of the priority queue PriorityQueue<Cell> pq = new PriorityQueue<Cell>(k); for(int i=0;i< k; i++) { pq.Insert(new Cell(i, 0), mat[i, 0]); } while(pq.Count>0) { Cell minCell = pq.ExtractMin(); sortedArr[sortedArrIndex++] = mat[minCell.Row, minCell.Col]; if(minCell.Col +1 < mat.GetLength(1)) { pq.Insert(new Cell(minCell.Row, minCell.Col + 1), mat[minCell.Row, minCell.Col + 1]); } } return sortedArr; } /// <summary> /// Represents a cell location in the matrix /// In a distributed system, row represents computerId /// and column represents the index of the element in the file present in computerId /// </summary> public class Cell { public int Row { get; set; } public int Col { get; set; } public Cell(int row, int col) { Row = row; Col = col; } public override string ToString() { return string.Format("({0}, {1})", Row, Col); } } public static void TestKWayMerge() { KWayMerge merge = new KWayMerge(); int[,] mat = new int[,] { {2,4,6,7,90 }, {3,4,66,77,88 }, {55,65,88,90,101 }, {1,2,3,4,5 } }; Console.WriteLine("the input matrix is as shown below"); MatrixProblemHelper.PrintMatrix(mat); Console.WriteLine("The sorted array is as shown below"); ArrayHelper.PrintArray(merge.DoKWayMerge(mat)); } } }
using SalaryCalculator.Interfaces; namespace SalaryCalculator.TaxPlans { /// <summary> /// Defines a tax deduction in sections. /// There's a threshold section, a tax rate to apply to the first section /// and a tax rate to apply to the rest of the money /// </summary> public class SectionDeduction : ISectionDeduction { private decimal _firstTaxSectionDeductionPct; private decimal _secondtaxSectionDeductionPct; private decimal _taxSectionThreshold; private string _name; public decimal FirstTaxSectionDeductionPercentage { get { return _firstTaxSectionDeductionPct; } } public decimal SecondTaxSectionDeductionPercentage { get { return _secondtaxSectionDeductionPct; } } public decimal TaxSectionThreshold { get { return _taxSectionThreshold; } } public string Name { get { return _name; } } public SectionDeduction(decimal FirstTaxSectionDeductionPct, decimal SecondTaxSectionDeductionPct, decimal TaxSectionthreshold, string name) { _firstTaxSectionDeductionPct = FirstTaxSectionDeductionPct; _secondtaxSectionDeductionPct = SecondTaxSectionDeductionPct; _taxSectionThreshold = TaxSectionthreshold; _name = name; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Security.Principal; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using ContestsPortal.WebSite.App_Start; using ContestsPortal.WebSite.Infrastructure; using ContestsPortal.WebSite.Infrastructure.ActionAttributes; using ContestsPortal.WebSite.ViewModels.Account; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Newtonsoft.Json.Linq; using ContestsPortal.WebSite.ViewModels.Administrator; using System.Diagnostics; using ContestsPortal.Domain.Models; using ContestsPortal.Domain.DataAccess; using ContestsPortal.Domain.DataAccess.Providers.Interfaces; namespace ContestsPortal.WebSite.Controllers { [Authorize(Roles = Roles.SuperAdministrator + "," + Roles.Administrator)] public class AdministratorController : Controller { private readonly IContestsProvider _contestsProvider; private readonly IUsersProvider _usersProvider; private readonly IProgrammingLanguageProvider _programmingLanguageProvider; private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } #region Constructors public AdministratorController() { } public AdministratorController(IContestsProvider provider, IUsersProvider usersProvider, IProgrammingLanguageProvider programmingLanguageProvider) { if (provider == null) throw new ArgumentNullException("provider"); if (usersProvider == null) throw new ArgumentNullException("usersProvider"); if (programmingLanguageProvider == null) throw new ArgumentNullException("programmingLanguageProvider"); _contestsProvider = provider; _usersProvider = usersProvider; _programmingLanguageProvider = programmingLanguageProvider; } #endregion [HttpGet, AjaxOnly] public async Task<ActionResult> AddLanguage() { Debug.WriteLine("AdministratorController.AddLanguage"); return View("_ProgrammingLanguageEdit"); } [HttpPost, AjaxOnly] public async Task<ActionResult> EditLanguage(ProgrammingLanguageViewModel viewmodel) { Debug.WriteLine("AdministratorController.EditLanguage(ProgrammingLanguageViewModel viewmodel)"); ProgrammingLanguage newLanguage = new ProgrammingLanguage() { LanguageId = viewmodel.LanguageId, LanguageName = viewmodel.LanguageName }; IdentityResult result = await _programmingLanguageProvider.AddProgrammingLanguageAsync(newLanguage); if (result.Succeeded) return Json(new { Succeeded = result.Succeeded }, JsonRequestBehavior.DenyGet); return RedirectToAction("ProgrammingLanguages"); } [HttpGet] public async Task<ActionResult> DeleteLanguage(int languageId) { Debug.WriteLine("AdministratorController.EditLanguage(int languageId)"); IdentityResult result = await _programmingLanguageProvider.DeleteContestAsync(languageId); if (result.Succeeded) return Json(new { Succeeded = result.Succeeded }, JsonRequestBehavior.DenyGet); return RedirectToAction("ProgrammingLanguages"); } [HttpGet] public async Task<ActionResult> EditLanguage(int languageId) { Debug.WriteLine("AdministratorController.EditLanguage(int languageId)"); ProgrammingLanguage language = await _programmingLanguageProvider.GetProgrammingLanguageAsync(languageId); ProgrammingLanguageViewModel languageViewModel = new ProgrammingLanguageViewModel(language); return View("_ProgrammingLanguageEdit", languageViewModel); } [HttpGet, AjaxOnly] public async Task<ActionResult> ProgrammingLanguages() { IList<ProgrammingLanguage> languages = await _programmingLanguageProvider.GetAllProgrammingLanguagesAsync(); IList<ProgrammingLanguageViewModel> languagesViewModel = languages.Select(x => new ProgrammingLanguageViewModel(x)).ToList(); return View("_ProgrammingLanguages", languagesViewModel); } private UserViewModel ConvertUserProfileToUserViewModel(UserProfile user) { return new UserViewModel { Id = user.Id, UserName = user.UserName, Email = user.Email, NickName = user.NickName }; } [HttpPost, AjaxOnly] public async Task<ActionResult> EditUser(UserViewModel viewmodel) { var user = await _usersProvider.GetUser(Convert.ToInt32(viewmodel.Id)); user.NickName = viewmodel.NickName; user.PasswordHash = viewmodel.Password; IdentityResult res = await UserManager.UpdateAsync(user); if (!res.Succeeded) { return View("_UserEdit", viewmodel); } return RedirectToAction("Users"); } [HttpGet] public async Task<ActionResult> EditUser(int userId) { UserProfile user = await _usersProvider.GetUser(userId); UserViewModel userViewModel = ConvertUserProfileToUserViewModel(user); return View("_UserEdit", userViewModel); } [HttpGet, AjaxOnly] public async Task<ActionResult> Users() { if (!HttpContext.Request.IsAjaxRequest()) return null; IList<UserProfile> users = (await _usersProvider.GetAllUsers()); IList<UserViewModel> usersViewModel = new List<UserViewModel>(users.Count); foreach (UserProfile user in users) { UserViewModel userViewModel = ConvertUserProfileToUserViewModel(user); usersViewModel.Add(userViewModel); } return View("_Users", usersViewModel); } // GET: Administrator [HttpGet] public ActionResult Index() { return View("IndexView"); } [HttpGet, AjaxOnly] public async Task<ActionResult> ActiveContests() { IList<Contest> contests = await _contestsProvider.GetContestsByStateAsync(ContestStates.Active); return View("_ActiveContests", contests); } [HttpGet, AjaxOnly] public async Task<ActionResult> AwaitingContests() { IList<Contest> contests = await _contestsProvider.GetContestsByStateAsync(ContestStates.Awaiting); return View("_AwaitingContests", contests); } [HttpGet, AjaxOnly] public async Task<ActionResult> ActiveContestTasks(int contestId) { if (!HttpContext.Request.IsAjaxRequest()) return null; return View(); } [HttpPost, AjaxOnly] public async Task<JsonResult> DeleteContest(int contestId) { if (!HttpContext.Request.IsAjaxRequest()) return null; IdentityResult result = await _contestsProvider.DeleteContestAsync(contestId); return Json(new { Result = result.Succeeded }, JsonRequestBehavior.DenyGet); } [HttpGet, AjaxOnly] public async Task<ActionResult> OpenForRegistrationContests() { IList<Contest> contests = await _contestsProvider.GetContestsByStateAsync(ContestStates.Registration); return View(contests); } [HttpPost, AjaxOnly] public async Task<JsonResult> PassToRegisrationStage(int contestId = 0) { IdentityResult result = await _contestsProvider.SetStateForContestAsync(contestId, ContestStates.Registration); return Json(new { Result = result.Succeeded }, JsonRequestBehavior.DenyGet); } [HttpGet, AjaxOnly] public async Task<ActionResult> AddNewContest() { var contest = new ContestEditorViewModel(); IList<ContestPriority> list; // gonna use ninject later using (var context = new PortalContext()) list = context.Set<ContestPriority>().OrderBy(x => x.ContestPriorityId).ToList(); ViewBag.ContestPriorities = new SelectList(list, "ContestPriorityId", "ContestPriorityName"); Session["ContestPriorityId"] = ViewBag.ContestPriorities; return View("_AddNewContest", contest); } [HttpPost, AjaxOnly] public async Task<ActionResult> ContesEdit(int contestId) { Contest contest = await _contestsProvider.GetContest(contestId); return null; } [HttpPost, AjaxOnly] public async Task<ActionResult> AddNewContest(ContestEditorViewModel viewmodel) { ViewData["ContestPriorityId"] = Session["ContestPriorityId"]; Session["ContestPriorityId"] = null; if (!ModelState.IsValid) return View(viewmodel); TimeSpan? duration = TimeSpan.Zero; var tasks = new List<ContestTask>(); foreach (TaskEditorViewModel editor in viewmodel.TaskEditors) { var task = new ContestTask { TaskComplexity = editor.TaskComplexity, TaskDuration = editor.TaskDuration, TaskAward = editor.TaskAward, TaskTitle = editor.TaskTitle, TaskComment = editor.TaskComment, TaskContent = editor.TaskContent }; duration = duration.Value.Add(editor.TaskDuration.Value); // adding only via id should be checked task.Languages = editor.Languages.Select( x => new ProgrammingLanguage { LanguageId = x.LanguageId, LanguageName = x.LanguageName }) .ToList(); tasks.Add(task); } DateTime contestEnd = viewmodel.ContestBeginning.Value.Add(duration.Value); var contest = new Contest { Tasks = tasks, ContestBeginning = viewmodel.ContestBeginning, ContestTitle = viewmodel.ContestTitle, ContestComment = viewmodel.ContestComment, TasksCount = viewmodel.TaskEditors.Count, ContestEnd = contestEnd, IdContestPriority = viewmodel.ContestPriorityId }; IdentityResult result = await _contestsProvider.CreateContestAsync(contest); if (result.Succeeded) return Json(new { Succeeded = result.Succeeded }, JsonRequestBehavior.DenyGet); return View("_AddNewContest", viewmodel); } // this is used in addnewcontest tab [HttpGet] public async Task<ActionResult> OpenTaskEditor() { if (HttpContext.Session["Languages"] == null) { // use Resolver.GetService<> later using (var context = new PortalContext()) HttpContext.Session["Languages"] = context.Languages.ToList(); } List<ProgrammingLanguageViewModel> langvms = (HttpContext.Session["Languages"] as IList<ProgrammingLanguage>) .Select(x => new ProgrammingLanguageViewModel(x)) .ToList(); var model = new TaskEditorViewModel { Languages = langvms }; return View("_TaskEditor", model); } // task editing [HttpGet, AjaxOnly] public async Task<ActionResult> EditArchivedTask(int taskId) { return View(); } [HttpPost, AjaxOnly] public async Task<ActionResult> EditArchivedTask(TaskEditorViewModel viewmodel) { return View(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Restart : MonoBehaviour { void Awake() { gameObject.SetActive(false); } public void GameRestart() { SceneManager.LoadScene(0); } }
using System.Collections.Generic; using System.Linq; using Profiling2.Domain.Contracts.Queries; using Profiling2.Domain.Contracts.Queries.Search; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Domain.Prf; using SharpArch.NHibernate.Contracts.Repositories; namespace Profiling2.Tasks { public class LocationTasks : ILocationTasks { protected readonly INHibernateRepository<Location> locationRepo; protected readonly INHibernateRepository<Region> regionRepo; protected readonly INHibernateRepository<Province> provinceRepo; protected readonly ILocationSearchQuery locationSearchQuery; protected readonly ILuceneTasks luceneTasks; protected readonly ILocationMergeQuery mergeQuery; public LocationTasks(INHibernateRepository<Location> locationRepo, INHibernateRepository<Region> regionRepo, INHibernateRepository<Province> provinceRepo, ILocationSearchQuery locationSearchQuery, ILuceneTasks luceneTasks, ILocationMergeQuery mergeQuery) { this.locationRepo = locationRepo; this.regionRepo = regionRepo; this.provinceRepo = provinceRepo; this.locationSearchQuery = locationSearchQuery; this.luceneTasks = luceneTasks; this.mergeQuery = mergeQuery; } public Location GetLocation(int id) { return this.locationRepo.Get(id); } public IList<Location> GetLocations(string name) { IDictionary<string, object> criteria = new Dictionary<string, object>(); criteria.Add("LocationName", name); return this.locationRepo.FindAll(criteria); } protected IList<Location> GetLocations(string town, string territory, Province province) { IDictionary<string, object> criteria = new Dictionary<string, object>(); criteria.Add("Town", town); criteria.Add("Territory", territory); criteria.Add("Province", province); return this.locationRepo.FindAll(criteria); } protected IList<Location> GetLocations(string town, string territory, Region region) { IDictionary<string, object> criteria = new Dictionary<string, object>(); criteria.Add("Town", town); criteria.Add("Territory", territory); criteria.Add("Region", region); return this.locationRepo.FindAll(criteria); } public IList<Location> GetAllLocations() { return this.locationRepo.GetAll().OrderBy(x => x.LocationName).ToList<Location>(); } public IList<Location> GetLocationsWithCoords() { return this.locationSearchQuery.GetLocationsWithCoords(); } public Location GetOrCreateLocation(string address, string town, string territory, string province, float? latitude, float? longitude) { Location l = null; Province p = this.GetProvince(province); Region r = this.GetRegion(province); // check for existing Location using Location.Province IList<Location> candidates = this.GetLocations(town, territory, p); if (candidates == null || (candidates != null && !candidates.Any())) candidates = this.GetLocations(town, territory, r); // check for existing Location using Location.Region if (candidates != null && candidates.Any()) l = candidates[0]; // create new Location if necessary if (l == null) { l = new Location(); l.LocationName = !string.IsNullOrEmpty(address) ? address : (!string.IsNullOrEmpty(town) ? town : (!string.IsNullOrEmpty(territory) ? territory : (!string.IsNullOrEmpty(province) ? province : "(no name)"))); l.Town = town; l.Territory = territory; l.Region = r; l.Province = p; if (latitude.HasValue) l.Latitude = latitude.Value; if (longitude.HasValue) l.Longitude = longitude.Value; l = this.SaveLocation(l); } return l; } public Location SaveLocation(Location loc) { this.luceneTasks.UpdatePersons(loc); return this.locationRepo.SaveOrUpdate(loc); } public IList<Location> SearchLocations(string term) { return this.locationSearchQuery.GetResults(term); } public bool DeleteLocation(Location loc) { if (loc != null && loc.Careers.Count == 0 && loc.Events.Count == 0 && loc.UnitLocations.Count == 0) { this.locationRepo.Delete(loc); return true; } return false; } public Region GetRegion(int id) { return this.regionRepo.Get(id); } public Region GetRegion(string name) { IDictionary<string, object> criteria = new Dictionary<string, object>(); criteria.Add("RegionName", name); return this.regionRepo.FindOne(criteria); } public IList<Region> GetAllRegions() { return this.regionRepo.GetAll().OrderBy(x => x.RegionName).ToList<Region>(); } public IList<object> GetRegionsJson(string term) { IList<Region> regions = (from region in this.regionRepo.GetAll() where region.RegionName.ToUpper().Contains(term.ToUpper()) orderby region.ToString() select region).ToList<Region>(); IList<object> objList = new List<object>(); foreach (Region r in regions) objList.Add(new { id = r.Id, text = r.ToString() }); return objList; } public Region SaveRegion(Region reg) { return this.regionRepo.SaveOrUpdate(reg); } public void DeleteRegion(Region reg) { if (reg != null && !reg.Locations.Any() && !reg.Persons.Any()) this.regionRepo.Delete(reg); } public void MergeLocations(int toKeepId, int toDeleteId) { this.mergeQuery.MergeLocations(toKeepId, toDeleteId); } public IList<Province> GetAllProvinces() { return this.provinceRepo.GetAll().OrderBy(x => x.ProvinceName).ToList<Province>(); } public Province GetProvince(int id) { return this.provinceRepo.Get(id); } public Province GetProvince(string name) { IDictionary<string, object> criteria = new Dictionary<string, object>(); criteria.Add("ProvinceName", name); return this.provinceRepo.FindOne(criteria); } } }
using System.Web; using System.Web.Mvc; using System.Web.Http.Filters; using LuckyMasale.WebApi.Filters; namespace LuckyMasale.WebApi { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } /// <summary> /// Registers the http filters. /// </summary> /// <param name="filters">The filters.</param> public static void RegisterHttpFilters(HttpFilterCollection filters) { filters.Add(new TokenValidationAttribute()); } } }
using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class SkinColorer : MonoBehaviour { private void Start() { EntityWorker worker = this.GetComponentInParent<EntityWorker>(); int skinTone = worker.info.skinTone; this.GetComponent<SpriteRenderer>().color = Main.instance.workerFactory.getSkinColorFromTone(skinTone); } }
using System.Collections.Generic; using System.Linq; namespace Tools { public class Constants { public static readonly List<char> LatinAlphabetLower = "abcdefghijklmnopqrstuvwxyz".ToList(); public static readonly List<char> LatinAlphabetUpper = "abcdefghijklmnopqrstuvwxyz".ToUpper().ToList(); public static readonly List<char> LatinAlphabet; public static readonly List<char> CyrillicAlphabetLower = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя".ToList(); public static readonly List<char> CyrillicAlphabetUpper = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя".ToUpper().ToList(); public static readonly List<char> CyrillicAlphabet; public static readonly List<char> Alphabet; public static readonly List<char> Numbers = "0123456789".ToList(); public static readonly List<char> SpecialSymbols = new List<char>() {';', '=', '(',')'}; public static readonly List<char> Symbols; public static readonly List<char> ArifmeticalOperators = new List<char>(){'+','-','*','/','^','(',')'}; static Constants() { LatinAlphabet = new List<char>(); LatinAlphabet.AddRange(LatinAlphabetLower); LatinAlphabet.AddRange(LatinAlphabetUpper); CyrillicAlphabet = new List<char>(); CyrillicAlphabet.AddRange(CyrillicAlphabetLower); CyrillicAlphabet.AddRange(CyrillicAlphabetUpper); Alphabet = new List<char>(); //Alphabet.AddRange(CyrillicAlphabet); Alphabet.AddRange(LatinAlphabet); Symbols = new List<char>(); Symbols.AddRange(Alphabet); Symbols.AddRange(Numbers); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraGo : MonoBehaviour { private Transform myTransform; private float speed; private int record; private int circle = 0; private float curr_time; void Start () { curr_time = PlayerPrefs.GetFloat("time_in_game"); myTransform = transform; speed = 5; } void Update () { curr_time += Time.fixedDeltaTime; myTransform.position += myTransform.forward * Time.deltaTime * speed; //рух у напрямку погляду record = (int)myTransform.position.z; if (myTransform.position.z > 100) // прискорення { myTransform.position -= new Vector3(0, 0, 100); speed += speed/3; circle++; } if ((Mathf.Abs(myTransform.position.x) * Mathf.Abs(myTransform.position.x) + Mathf.Abs(myTransform.position.y) * Mathf.Abs(myTransform.position.y)) > Mathf.Abs(0.81f)) // смерть при виході із зони гри { myTransform.GetChild(0).GetComponent<Player>().die(); } } public int getRecord() { return circle * 100 + record; } public void died() { PlayerPrefs.SetFloat("time_in_game", curr_time); gameObject.SetActive(false); } }
using ManageProducts.Domain.Entities; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ManageProducts.Data { public class MyContext :DbContext { //ctor+double tab //public MyContext():base("mabase_4sim4")// le nom de la base de données //{ //} public MyContext():base("name=MaChaine")//le nom de la chaine : app.config du projet de démarrage { } public DbSet<Product> Products { get; set; } // TPH : 1 seule table pour 3 classes(product+chemical+biological) public DbSet<Provider> Providers { get; set; } public DbSet<Category> Categories { get; set; } } }
using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts; using Newtonsoft.Json.Linq; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Parts { public interface ITaxonomyPartGraphSyncer : IContentPartGraphSyncer { Task AddSyncComponentsForNonLeafEmbeddedTerm(JObject content, IGraphMergeContext context); Task DeleteComponentsForNonLeafEmbeddedTerm(JObject content, IGraphDeleteContext context); Task<(bool validated, string failureReason)> ValidateSyncComponentForNonLeafEmbeddedTerm( JObject content, IValidateAndRepairContext context); } }
using UnityEngine; using System.Collections; using UnityEngine.Networking; public class PlayerStateController : MonoBehaviour { public enum playerStates { idle = 0, left, right, jump, landing, falling, kill, resurrect, firingWeapon, _stateCount } public static float[] stateDelayTimer = new float[(int)playerStates._stateCount]; public delegate void playerStateHandler(PlayerStateController.playerStates newState); public static event playerStateHandler onStateChange; void LateUpdate() { // Detect the current input of Horizontal axis, then // broadcast a state update for the player as needed. // Do this on each frame to make sure the state is always // set properly based on the current user input. float horizontal = Input.GetAxis("Horizontal"); if (horizontal != 0f) { if (horizontal < 0f) { if (onStateChange != null) onStateChange(PlayerStateController.playerStates.left); } else { if (onStateChange != null) onStateChange(PlayerStateController.playerStates.right); } } else { if (onStateChange != null) onStateChange(PlayerStateController.playerStates.idle); } float jump = Input.GetAxis("Jump"); if (jump > 0.0f) { if (onStateChange != null) onStateChange(PlayerStateController.playerStates.jump); } float firing = Input.GetAxis("Fire1"); if (firing > 0.0f) { if (onStateChange != null) { onStateChange(PlayerStateController.playerStates.firingWeapon); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TutorialTrigger : MonoBehaviour { public string tutorialText; public PlayerMovement requiredVehicle; private bool activated = false; private void OnTriggerEnter(Collider other) { PlayerMovement pm = other.transform.GetComponent<PlayerMovement>(); if(pm != null) { if(requiredVehicle == null || pm == requiredVehicle) { ActivateTutorial(); } } } public void ActivateTutorial() { if (activated == false) { activated = true; TutorialManager.instance.ShowTutorial(tutorialText); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; public class UISlider : UIBase { [System.Serializable] public class UIEventFloat:UnityEvent<float> { } public UIEventFloat OnHoverFloat; public UIEventFloat OnUnhoverFloat; public UIEventFloat OnPressFloat; public UIEventFloat OnUnpressFloat; Slider slider; public virtual float floatElement { get { return slider.value; } set { slider.value = value; } } protected override void Awake () { base.Awake (); for (int i = 0; i < transform.childCount; i++) { Transform child = transform.GetChild (i); Slider slider = child.GetComponent<Slider> (); if (slider) { if (this.slider) { Debug.LogWarning ("Don't put multiple Sliders on a single UISlider"); } this.slider = slider; } } } public void SetValue (float f) { floatElement = f; } public override void OnPointerHover (GameObject source) { base.OnPointerHover (source); if (!hidden) { OnHoverFloat.Invoke (floatElement); } } public override void OnPointerUnhover (GameObject source) { base.OnPointerUnhover (source); if (!hidden) { OnUnhoverFloat.Invoke (floatElement); } } public override void OnPointerPress (GameObject source) { base.OnPointerPress (source); if (!hidden) { OnPressFloat.Invoke (floatElement); } } public override void OnPointerUnpress (GameObject source) { base.OnPointerUnpress (source); if (!hidden) { OnUnpressFloat.Invoke (floatElement); } } }
using System; using System.Collections.Generic; using System.Text; namespace SAAS.Mq.Socket.Channel { enum EMsgType : byte { /// <summary> /// request /// </summary> request = 1, /// <summary> /// reply /// </summary> reply = 2, /// <summary> /// 单向数据 /// </summary> message=3 } }
using gView.Framework.Globalisation; using gView.Framework.Web; using System; using System.Drawing; using System.Windows.Forms; namespace gView.Framework.UI.Dialogs { [gView.Framework.system.RegisterPlugIn("399FD7B5-915C-4035-84E6-FA4C5DFE1A95")] public partial class OptionPageProxy : Form, IMapOptionPage, IExplorerOptionPage { public OptionPageProxy() { InitializeComponent(); //ProxySettings.Load(); //gView.Framework.Web.ProxySettings settings = new gView.Framework.Web.ProxySettings(); cmbUseType.SelectedIndex = (int)ProxySettings.UseProxy; txtServer.Text = ProxySettings.Server; numPort.Value = Math.Max(ProxySettings.Port, 1); txtExceptions.Text = ProxySettings.Exceptions; txtDomain.Text = ProxySettings.Domain; txtUser.Text = ProxySettings.User; txtPassword.Text = " "; cmbUseType_SelectedIndexChanged(cmbUseType, new EventArgs()); } #region IMapOptionPage Member public Panel OptionPage(IMapDocument document) { return this.PagePanel; } public string Title { get { return LocalizedResources.GetResString("String.ProxySettings", "Proxy Settings"); } } public Image Image { get { return null; } } public void Commit() { //gView.Framework.Web.ProxySettings settings = new gView.Framework.Web.ProxySettings(); ProxySettings.UseProxy = (ProxySettings.UseProxyType)cmbUseType.SelectedIndex; ProxySettings.Server = txtServer.Text; ProxySettings.Port = (int)numPort.Value; ProxySettings.Exceptions = txtExceptions.Text; ProxySettings.Domain = txtDomain.Text; ProxySettings.User = txtUser.Text; if (txtPassword.Text != " ") { ProxySettings.Password = txtPassword.Text; } if (!ProxySettings.Commit()) { MessageBox.Show("ERROR: Can't write config..."); } } public bool IsAvailable(IMapDocument document) { return true; } #endregion #region IExplorerOptionPage Member public Panel OptionPage() { return this.PagePanel; } #endregion private void cmbUseType_SelectedIndexChanged(object sender, EventArgs e) { groupBox1.Visible = groupBox2.Visible = groupBox3.Visible = (ProxySettings.UseProxyType)cmbUseType.SelectedIndex == ProxySettings.UseProxyType.use; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Person { class Person { public string name; public int age; public Person() { name = "No name"; age = 1; } public Person(int a) { name = "No name"; age = a; } public Person(string n, int a) { name = n; age = a; } } }
/////////////////////////////////////////////////////////////////////////////// /// This code is provided for demonstration purposes only. /// There's only minimal error checking and the code does not /// meet production quality standards. Use it at your own risk. /////////////////////////////////////////////////////////////////////////////// using Meeting; using Sardf.Logging; using System; using System.Drawing; using System.Windows.Forms; namespace Page.ShareWindow.Comment { /// <summary> /// Summary description for MainForm. /// </summary> public class ShareMediaForm : System.Windows.Forms.Form { private ILogger _log = LoggerFactory.GetLogger(typeof(ShareMediaForm)); private System.ComponentModel.IContainer components; private System.Windows.Forms.Timer m_GCTimer; private int m_XExtent; private AxUMediaControlLib.AxUMediaPlayer m_Player; public ClientVersion Version { get; set; } private Button btnClose; private int m_YExtent; public ShareMediaForm() { InitializeComponent(); m_GCTimer.Start(); m_XExtent = this.Size.Width - m_Player.Width; m_YExtent = this.Size.Height - m_Player.Height; this.Visible = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShareMediaForm)); this.m_GCTimer = new System.Windows.Forms.Timer(this.components); this.m_Player = new AxUMediaControlLib.AxUMediaPlayer(); this.btnClose = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.m_Player)).BeginInit(); this.SuspendLayout(); // // m_GCTimer // this.m_GCTimer.Enabled = true; this.m_GCTimer.Interval = 10000; this.m_GCTimer.Tick += new System.EventHandler(this.m_GCTimer_Tick); // // m_Player // this.m_Player.Dock = System.Windows.Forms.DockStyle.Fill; this.m_Player.Enabled = true; this.m_Player.Location = new System.Drawing.Point(0, 0); this.m_Player.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.m_Player.Name = "m_Player"; this.m_Player.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("m_Player.OcxState"))); this.m_Player.Size = new System.Drawing.Size(1708, 960); this.m_Player.TabIndex = 0; // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.BackColor = System.Drawing.Color.Transparent; this.btnClose.BackgroundImage = global::Page.ShareWindow.Comment.Properties.Resources.meeting_base_closed; this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnClose.Location = new System.Drawing.Point(1657, 14); this.btnClose.Margin = new System.Windows.Forms.Padding(4); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(35, 35); this.btnClose.TabIndex = 1; this.btnClose.UseVisualStyleBackColor = false; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // ShareMediaForm // this.AutoScaleDimensions = new System.Drawing.SizeF(120F, 120F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(1708, 960); this.Controls.Add(this.btnClose); this.Controls.Add(this.m_Player); this.DoubleBuffered = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximizeBox = false; this.Name = "ShareMediaForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "·ÖÏí"; this.TopMost = true; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); this.Load += new System.EventHandler(this.OnFormLoad); ((System.ComponentModel.ISupportInitialize)(this.m_Player)).EndInit(); this.ResumeLayout(false); } private void M_Player_OnError(object sender, AxUMediaControlLib._IUMediaPlayerEvents_OnErrorEvent e) { this.Hide(); } #endregion private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Disconnect(); m_GCTimer.Stop(); } private void m_GCTimer_Tick(object sender, System.EventArgs e) { GC.Collect(); } public void Connect(string ClientId, string ServerIp) { try { ShareMediaHelper.Play(m_Player, new MeetingShareParam { ClientId = ClientId, ServerIp = ServerIp, Version = Version }, s => { this.Text = "Á´½ÓÖÐ..."; this.Visible = true; this.Show(); }, e => { m_Player.Stop(); this.Hide(); }); } catch (Exception se) { _log.Error(se.Message); } } public void Disconnect() { try { this.Visible = false; this.Hide(); m_Player.Stop(); } catch (Exception) { this.Hide(); } } private void OnFormLoad(object sender, System.EventArgs e) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.btnClose.Location = new Point(this.Width - 30, 0); } private void OnViewFullScreen(object sender, System.EventArgs e) { m_Player.ViewFullScreenSize(); } private void OnViewProperties(object sender, System.EventArgs e) { m_Player.ViewProperties(); } private void OnVideoSettings(object sender, System.EventArgs e) { m_Player.ViewVideoSettings(); } private void btnClose_Click(object sender, EventArgs e) { Disconnect(); } } }
using Grillisoft.FastCgi.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Grillisoft.FastCgi.Repositories { public class SyncronizedRequestsRepository : IRequestsRepository { private readonly Dictionary<ushort, Request> _requests = new Dictionary<ushort, Request>(); public void AddRequest(Protocol.Request request) { lock(_requests) { _requests.Add(request.Id, request); } } public void RemoveRequest(Protocol.Request request) { lock(_requests) { _requests.Remove(request.Id); } } public Protocol.Request GetRequest(ushort requestId) { lock(_requests) { return _requests[requestId]; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Docller.Core.Models { public class TransmittalUser:User { public long TransmittalId { get; set; } public bool IsCced { get; set; } } }
using Microsoft.AspNetCore.Mvc; using ProjectCompany.Services; using ProjectCompany.Models; using System.Collections.Generic; namespace ProjectCompany.Controllers { [Route("api/[controller]")] public class SkillController : Controller { private SkillService skillService; public SkillController(SkillService skillService) { this.skillService = skillService; } [HttpGet] public IActionResult Index(int id) { return Ok(this.skillService.GetAllSkills()); } [HttpPost] public IActionResult Create([FromBody] Skill skill) { if (this.skillService.isUniqueSkillTitle(skill)) { ModelState.AddModelError("Title", "This skill is already exist"); } if (ModelState.IsValid && !this.skillService.isUniqueSkillTitle(skill)) { this.skillService.AddSkill(skill); return Ok(skill); } return UnprocessableEntity(ModelState); } [HttpDelete("{id:int:min(1)}")] public IActionResult Delete(int id) { Skill skill = this.skillService.GetSkillById(id); if (skill == null) { return NotFound(); } this.skillService.DeleteSkill(skill); return Ok(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _07.Selection_Sort { class SortArray { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] arrNums = new int[n]; for (int i = 0; i < n; i++) { arrNums[i] = int.Parse(Console.ReadLine()); } Array.Sort(arrNums); foreach (var item in arrNums) { Console.WriteLine(item); } } } }
using System.Collections.Generic; using System.Linq; namespace Dependencies { /// <summary> /// A Dependency Node belongs to a Dependency Graph. /// A node an abstraction that contains the links to its dependees and dependents. /// </summary> public class DependencyNode { private string _key; private Dictionary<string, DependencyNode> _linkedDependency = new Dictionary<string, DependencyNode>(); private Dictionary<string, DependencyNode> _linkedDependees = new Dictionary<string, DependencyNode>(); /// <summary> /// Constructor for a DependencyNode. /// </summary> /// <param name="key">A string to associate the node by.</param> public DependencyNode(string key) { _key = key; } /// <summary> /// Returns the count of dependents for the node. /// </summary> public int CountDependents() { return _linkedDependency.Count; } /// <summary> /// Returns the count of dependees for the node. /// </summary> public int CountDependees() { return _linkedDependees.Count; } /// <summary> /// Remove the link between all dependents and the node. /// </summary> public void ClearDependents() { foreach (var dependent in _linkedDependency.Values) { dependent.RemoveDependee(this); } _linkedDependency.Clear(); } /// <summary> /// Removes the link between all dependees and the node. /// </summary> public void ClearDependees() { foreach (var dependee in _linkedDependees.Values) { dependee.RemoveDependency(this); } _linkedDependees.Clear(); } /// <summary> /// Returns true if the node has the dependency of tNode. /// </summary> public bool HasDependency(DependencyNode tNode) { return _linkedDependency.ContainsKey(tNode.ToString()); } /// <summary> /// Returns true if the node has the dependee of sNode. /// </summary> public bool HasDependee(DependencyNode sNode) { return _linkedDependees.ContainsKey(sNode.ToString()); } /// <summary> /// Returns the Dependents of the node. /// </summary> public IEnumerable<string> GetDependents() { return _linkedDependency.Values.Select(node => node.ToString()); } /// <summary> /// Returns the Dependees of the node. /// </summary> public IEnumerable<string> GetDependees() { return _linkedDependees.Values.Select(node => node.ToString()); } /// <summary> /// Adds the linkedNode as a dependency of the node. /// </summary> public void AddDependency(DependencyNode linkedNode) { if (HasDependency(linkedNode)) return; //Return if the link already exists. _linkedDependency.Add(linkedNode.ToString(), linkedNode); } /// <summary> /// Removes the linkedNode as a dependency of the node. /// </summary> public void RemoveDependency(DependencyNode linkedNode) { if (_linkedDependency.ContainsKey(linkedNode.ToString())) { _linkedDependency.Remove(linkedNode.ToString()); } } /// <summary> /// Adds the linkedNode as a dependee of the node. /// </summary> public void AddDependee(DependencyNode linkedNode) { if (HasDependee(linkedNode)) return; //Return if the link already exists. _linkedDependees.Add(linkedNode.ToString(), linkedNode); } /// <summary> /// Removes the linkedNode as a dependee of the node. /// </summary> public void RemoveDependee(DependencyNode linkedNode) { if (_linkedDependees.ContainsKey(linkedNode.ToString())) { _linkedDependees.Remove(linkedNode.ToString()); } } /// <summary> /// Returns the key of the node. /// </summary> public override string ToString() { return _key; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Profile; using System.Collections; using DLib.DAL; namespace BLL.DLib { public class Library { #region vars private static DlibEntities Db { get { if (HttpContext.Current.Session["DB"] == null) { var entities = new DlibEntities(); HttpContext.Current.Session["DB"] = entities; return entities; } else return HttpContext.Current.Session["DB"] as DlibEntities; } } public int ID; public string Title; public string Domain; public bool Active; #endregion public static Library GetLibrary(int LibID) { var q = Db.tblLibrary.FirstOrDefault(c => c.ID == LibID); return new Library { ID = q.ID, Title = q.Title, Domain=q.Domain, Active = q.Active.Value }; } public static int GetLibIDWithDomain(string Domain) { var q = Db.tblLibrary.FirstOrDefault(c => c.Domain == Domain); return q == null ? 0 : q.ID; } public string Delete() { var q = Db.tblLibRecords.Where(c => c.LibID == this.ID); int RecCount = q == null ? 0 : q.Count(); var q1 = Db.tblLibRecTree.Where(c => c.LibID == this.ID); int TreeCount = q1 == null ? 0 : q1.Count(); if (TreeCount == 1) { var tree = q1.FirstOrDefault(); while (tree.tblLibRecTreeLang.Count>0) { tree.tblLibRecTreeLang.Remove(tree.tblLibRecTreeLang.FirstOrDefault()); } Db.tblLibRecTree.Remove(tree); TreeCount = 0; } var q2 = Db.tblLibRecType.Where(c => c.LibID == this.ID); int LibRecTypeCount = q2 == null ? 0 : q2.Count(); var q3 = Db.tblLibKeyword.Where(c => c.LibID == this.ID); int LibKeyCount = q3 == null ? 0 : q3.Count(); var q4 = Db.tblCmsPage.Where(c => c.LibID == this.ID); int LibPageCount = q4 == null ? 0 : q4.Count(); if (LibPageCount == 1) { int PageID=q4.FirstOrDefault().ID; foreach (var opVal in Db.tblCmsPageOptionValue.Where(cc => cc.PageID == PageID)) { q4.FirstOrDefault().tblCmsPageOptionValue.Remove(opVal); Db.tblCmsPageOptionValue.Remove(opVal); } Db.tblCmsPage.Remove(q4.FirstOrDefault()); LibPageCount = 0; } var q6 = Db.tblLibKeywordTree.Where(c => c.LibID == this.ID); int LibKeywordTreeCount = q6 == null ? 0 : q6.Count(); if (LibKeywordTreeCount == 1) { Db.tblLibKeywordTree.Remove(q6.FirstOrDefault()); LibKeywordTreeCount = 0; } var q7 = Db.tblCmsTheme.Where(c => c.LibID == this.ID); int LibThemeCount = q7 == null ? 0 : q7.Count(); var q8 = Db.tblCmsModule.Where(c => c.LibID == this.ID); int LibModuleCount = q8 == null ? 0 : q8.Count(); string msg = ""; if (RecCount == 0 && TreeCount == 0 && LibRecTypeCount == 0 && LibKeyCount == 0 && LibPageCount == 0 && LibThemeCount == 0 && LibModuleCount == 0) { var qq = Db.tblLibrary.FirstOrDefault(c => c.ID == this.ID); Db.tblLibrary.Remove(qq); Db.SaveChanges(); msg = "حذف شد"; } else { msg = "شامل محتوا می باشد"; } return msg; } public static void Save(int LibID, string Title,string Domain, bool Active, Guid Creator, DateTime Createdate) { var q = (LibID > 0) ? Db.tblLibrary.FirstOrDefault(c => c.ID == LibID) : new tblLibrary(); q.Title = Title; q.Domain = Domain; q.Active = Active; if (LibID == 0) { q.Creator = Creator; q.Createdate = Createdate; Db.tblLibrary.Add(q); } Db.SaveChanges(); var tree = new tblLibRecTree { LibID = q.ID, Title = Title, Creator = Creator, ParentID = 1 }; foreach (var lang in Db.tblLang) { tree.tblLibRecTreeLang.Add(new tblLibRecTreeLang { LangID = lang.ID, Title = Title }); } Db.tblLibRecTree.Add(tree); Db.tblLibKeywordTree.Add(new tblLibKeywordTree { LibID = q.ID, Title = Title, Creator = Creator, Order = 0 }); Db.tblCmsPage.Add(new tblCmsPage { LibID = q.ID, IsMasterPage = true, Title = "صفحه اصلی" }); Db.SaveChanges(); } public void ActiveLibrary() { var qq = Db.tblLibrary.FirstOrDefault(c => c.ID == this.ID); qq.Active = (qq.Active == true) ? false : true; Db.SaveChanges(); } public void SelectLibrary() { ProfileBase prof = ProfileCommon.Create(Access.GetCurrentUserName()); prof.SetPropertyValue("LibID", this.ID); prof.Save(); } public void CreateIndex() { LuceneSearch ls = new LuceneSearch { LibID = this.ID }; ls.CreateAllDocuments(this.ID); } public static int GetActiveLibrary() { ProfileBase prof = ProfileCommon.Create(Access.GetCurrentUserName()); return Convert.ToInt32(prof.GetPropertyValue("LibID")); } public static int GetCurrentActiveLibrary() { var l = Db.tblLibrary.FirstOrDefault(c => c.Active == true); return l.ID; } public static IList GetList() { ProfileBase prof = ProfileCommon.Create(Access.GetCurrentUserName()); int LibID = Convert.ToInt32(prof.GetPropertyValue("LibID")); bool IsPowerUser = Access.IsPowerUser(); var q = Db.tblLibrary.Where(c => c.ID > 0).AsEnumerable().Where(c => Access.IsAdmin() ? true : (Access.UserShowLib(c.ID) == true)).Select(c => new { LibID = c.ID, c.Title, c.Domain, RecordCount = c.tblLibRecords.Count, AttachCount = c.tblLibRecords.Where(cc => cc.LibID == c.ID && cc.IsAttach == true).Count(), AttachSize = c.tblLibRecords.Where(cc => cc.LibID == c.ID && cc.IsAttach == true).Sum(cc => cc.tblLibRecFileData.FileSizeKB), TypeCount = c.tblLibRecType.Count, KeywordCount = c.tblLibKeyword.Count, Active = c.Active == true ? "فعال" : "غیر فعال", Select = LibID == c.ID ? "انتخاب" : "-", c.Createdate, DataSize =0, /* c.tblLibRecords.Sum(cc => cc.body.Length) / 1024 + c.tblLibRecords.Sum(cc => (cc.tblLibRecFileData == null || cc.tblLibRecFileData.ID == 0) ? 0 : cc.tblLibRecFileData.FileSizeKB),*/ FieldCount = c.tblLibRecFields == null ? 0 : c.tblLibRecFields.Count, FontBold = LibID == c.ID ? "bold" : "" }).OrderBy(c => c.Createdate); return q.AsQueryable().ToList(); } } }
using DAL; using DAL.Basics; using Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CateringWeb.Controllers { public class DishDevController : BaseController { D_OperationArea dOperationArea = new D_OperationArea();//作业区 D_DishDev dDishDev = new D_DishDev(); D_ClassInfo dClassInfo = new D_ClassInfo();//班组 /// <summary> /// 菜槽管理列表 /// </summary> public ActionResult DishDevlist(E_DishDev model) { List<E_OperationArea> OperationAreaList = dOperationArea.GetList(new E_OperationArea() { }); List<E_ClassInfo> ClassInfoList = dClassInfo.GetList(new E_ClassInfo() { }); List<E_DishDev> DishDevList = new List<E_DishDev>(); if (model.Date != null && model.classid > 0) { DishDevList = dDishDev.GetRecipeDishList(model); } //判断是否存在当天的菜槽设置,若不存在直接进行初始化 if (DishDevList != null && DishDevList.Count > 0) { var addList = DishDevList.Where(p=>p.devno<=0).ToList(); var devnoStrartIndex = 1; if(DishDevList.Count(p => p.status.Equals(1))>0) { devnoStrartIndex = DishDevList.Where(p => p.status.Equals(1)).Max(p => p.devno) + 1; } foreach (var item in addList) { item.devno = devnoStrartIndex; item.suggest_takeqty = item.TotalNumber.ToString(); item.status = 1; dDishDev.Add(item); dDishDev.Enable(item); devnoStrartIndex += 1; } } ViewBag.OperationAreaList = OperationAreaList; ViewBag.ClassInfoList = ClassInfoList; ViewBag.DishDevList = DishDevList; ViewBag.SearchParam = model; return View(); } /// <summary> /// 保存菜槽设置 /// </summary> public JsonResult SaveDishDev(E_DishDev model) { Save(model); return Json(new { result = model, msg = "OK" }, JsonRequestBehavior.AllowGet); } private void Save(E_DishDev model) { var DishDevList = dDishDev.GetList(new E_DishDev() { RecipeInformationId = model.RecipeInformationId }); if (DishDevList != null && DishDevList.Count > 0) { var eDishDev = DishDevList.FirstOrDefault(); eDishDev.suggest_takeqty = model.suggest_takeqty; eDishDev.devno = model.devno; dDishDev.Update(eDishDev); } else //新增 { var eDishDev = dDishDev.GetRecipeDishList(new E_DishDev() { RecipeInformationId = model.RecipeInformationId }).First(); eDishDev.suggest_takeqty = model.suggest_takeqty; eDishDev.devno = model.devno; dDishDev.Add(eDishDev); } } /// <summary> /// 启用菜槽 /// </summary> public JsonResult Enable(E_DishDev model) { Save(model); var eDishDev = dDishDev.GetList(new E_DishDev() { RecipeInformationId = model.RecipeInformationId }).First(); bool result = dDishDev.Enable(eDishDev); return Json(new { result = model, msg = result ? "OK" : "NO" }, JsonRequestBehavior.AllowGet); } } }
using UnityEngine; using System.Collections; public class GameLayer { public const int UI = 5; }
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 Автошкола { public partial class ServiceMastersForm : Form { public ServiceMastersForm() { InitializeComponent(); } BusinessLogic BusinessLogic = new BusinessLogic(); AutoschoolDataSet dataSet; string LastSearchingText = ""; int LastFoundRow = -1; bool FirstLoad = true; void ReloadServiceMasters() { dataSet = BusinessLogic.ReadServiceMasters(); ServiceMasters_dataGridView.DataSource = dataSet; ServiceMasters_dataGridView.DataMember = "ServiceMasters"; ServiceMasters_dataGridView.Columns["ID"].Visible = false; ServiceMasters_dataGridView.Columns["Surname"].Visible = false; ServiceMasters_dataGridView.Columns["FirstName"].Visible = false; ServiceMasters_dataGridView.Columns["PatronymicName"].Visible = false;; ServiceMasters_dataGridView.Columns["WorkStatus"].Visible = false; ServiceMasters_dataGridView.Columns["FIO"].Visible = false; ServiceMasters_dataGridView.Columns["WorkStatusName"].Visible = false; IDColumn.DataPropertyName = "ID"; SurnameColumn.DataPropertyName = "Surname"; FirstNameColumn.DataPropertyName = "FirstName"; PatronymicNameColumn.DataPropertyName = "PatronymicName"; WorkStatusColumn.DataPropertyName = "WorkStatusName"; } private void ServiceMastersForm_Load(object sender, EventArgs e) { ReloadServiceMasters(); ServiceMasters_dataGridView_SelectionChanged(sender, e); } private void Search_button_Click(object sender, EventArgs e) { SearchingInDataGridViewClass.Search(Search_textBox, ref ServiceMasters_dataGridView, Direction_checkBox, ref LastSearchingText, ref LastFoundRow, "SurnameColumn", "FirstNameColumn", "PatronymicNameColumn", "WorkStatusColumn"); } private void Search_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((char)e.KeyChar == (Char)Keys.Enter) { Search_button_Click(sender, e); } if ((char)e.KeyChar == (Char)Keys.Back) { LastSearchingText = ""; } } private void ServiceMasters_dataGridView_SelectionChanged(object sender, EventArgs e) { if (ServiceMasters_dataGridView.SelectedRows.Count == 1) { RepairsOfMaster_button.Enabled = true; } else { RepairsOfMaster_button.Enabled = false; } } private void Reload_button_Click(object sender, EventArgs e) { ReloadServiceMasters(); ServiceMasters_dataGridView_SelectionChanged(sender, e); } private void ServiceMastersForm_FormClosing(object sender, FormClosingEventArgs e) { MainForm.Perem(MainForm.FormsNames[5], false); } private void Close_button_Click(object sender, EventArgs e) { Close(); } private void ServiceMastersForm_VisibleChanged(object sender, EventArgs e) { if (Visible) { if (!FirstLoad) Reload_button_Click(sender, e); else FirstLoad = false; } } private void RepairsOfMaster_button_Click(object sender, EventArgs e) { ServiceMastersRepairsForm ServiceMastersForm = new ServiceMastersRepairsForm(Convert.ToInt32(ServiceMasters_dataGridView.SelectedRows[0].Cells["ID"].Value)); ServiceMastersForm.Text = "Отремонтированные и ремонтируемые ТС мастером сервиса: " + ServiceMasters_dataGridView.SelectedRows[0].Cells["FIO"].Value.ToString(); ServiceMastersForm.Show(); } } }
using EddiDataDefinitions; using Newtonsoft.Json; using System; using System.Collections.ObjectModel; namespace EddiConfigService.Configurations { /// <summary>Storage for configuration of cargo details</summary> [JsonObject(MemberSerialization.OptOut), RelativePath(@"\cargomonitor.json")] public class CargoMonitorConfiguration : Config { public ObservableCollection<Cargo> cargo { get; set; } = new ObservableCollection<Cargo>(); public int cargocarried { get; set; } public DateTime updatedat { get; set; } } }
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public void ReorderList(ListNode head) { if (head == null) return; ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode mid = slow.next; slow.next = null; ListNode pre = null, curr = mid; while (curr != null) { ListNode tmp = curr.next; curr.next = pre; pre = curr; curr = tmp; } ListNode p1 = head, p2 = pre; while (p1 != null && p2 != null) { //Console.WriteLine($"{p1.val} {p2.val}"); ListNode tmp2 = p1.next, tmp3 = p2.next; p1.next = p2; p2.next = tmp2; p1 = tmp2; p2 = tmp3; } } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using Alabo.Extensions; using Alabo.Framework.Tasks.Schedules.Domain.Entities; using Alabo.Reflections; using Alabo.Runtime; using Alabo.Schedules.Job; using Alabo.Web.Mvc.Attributes; using Microsoft.Extensions.Logging; using MongoDB.Bson; using System; using System.Collections.Generic; using System.Linq; namespace Alabo.Framework.Tasks.Schedules.Domain.Services { public class ScheduleService : ServiceBase<Schedule, ObjectId>, IScheduleService { public ScheduleService(IUnitOfWork unitOfWork, IRepository<Schedule, ObjectId> repository) : base(unitOfWork, repository) { } public IEnumerable<Type> GetAllTypes() { var cacheKey = "Schedule_alltypes"; return ObjectCache.GetOrSetPublic(() => { var types = RuntimeContext.Current.GetPlatformRuntimeAssemblies().SelectMany(a => a.GetTypes() .Where(t => !t.IsAbstract && t.BaseType == typeof(JobBase) || t.BaseType?.BaseType == typeof(JobBase))).ToList(); return types; }, cacheKey).Value; } public void Init() { ILoggerFactory loggerFactory = new LoggerFactory(); var list = GetList(); var addList = new List<Schedule>(); foreach (var type in GetAllTypes()) { try { long delay = 0; var config = Activator.CreateInstance(type, loggerFactory); var dynamicConfig = (dynamic)config; var timeSpan = (TimeSpan)dynamicConfig.DelayInterval; delay = timeSpan.TotalSeconds.ConvertToLong(); var find = list.FirstOrDefault(r => r.Type == type.FullName); if (find == null) { find = new Schedule { Type = type.FullName, Name = type.Name }; var classPropertyAttribute = type.GetAttribute<ClassPropertyAttribute>(); if (classPropertyAttribute != null) { find.Name = classPropertyAttribute.Name; } addList.Add(find); } else { var isUpdate = false; if (find.Delay != delay) { find.Delay = delay; isUpdate = true; } if (find.Name == type.Name) { find.Delay = delay; var classPropertyAttribute = type.GetAttribute<ClassPropertyAttribute>(); if (classPropertyAttribute != null) { find.Name = classPropertyAttribute.Name; isUpdate = true; } } if (isUpdate) { Update(find); } } } catch { } } AddMany(addList); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Pobs.Domain; using Pobs.Domain.Entities; using Pobs.Web.Models.Tags; namespace Pobs.Web.Models.Activity { public class ActivityListItemModel { public ActivityListItemModel() { } public ActivityListItemModel(Question x) { this.Type = "Question"; this.QuestionId = x.Id; this.QuestionSlug = x.Slug; this.QuestionText = x.Text; this.PostedAt = x.PostedAt.UtcDateTime; this.ChildCount = x.Answers.Count; this.Tags = x.Tags?.Select(y => new TagValueModel(y)).ToArray(); } public ActivityListItemModel(Answer x) : this(x.Question) { this.Type = "Answer"; this.QuestionId = x.Question.Id; this.QuestionSlug = x.Question.Slug; this.AnswerId = x.Id; this.AnswerSlug = x.Slug; this.AnswerText = x.Text; this.PostedAt = x.PostedAt.UtcDateTime; this.ChildCount = x.Comments.Count; } public ActivityListItemModel(Comment x) : this(x.Answer) { this.Type = "Comment"; this.QuestionId = x.Answer.Question.Id; this.QuestionSlug = x.Answer.Question.Slug; this.AnswerId = x.Answer.Id; this.AnswerSlug = x.Answer.Slug; this.CommentId = x.Id; this.CommentText = x.Text; this.PostedAt = x.PostedAt.UtcDateTime; this.IsAgree = x.AgreementRating == AgreementRating.Agree; this.ChildCount = null; } [Required] public string Type { get; set; } public int QuestionId { get; set; } [Required] public string QuestionSlug { get; set; } [Required] public string QuestionText { get; set; } public int? AnswerId { get; set; } public string AnswerSlug { get; set; } public string AnswerText { get; set; } public long? CommentId { get; set; } public string CommentText { get; set; } public DateTime PostedAt { get; set; } public int? ChildCount { get; set; } public bool? IsAgree { get; set; } public TagValueModel[] Tags { get; set; } } }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using AnimationOrTween; [Serializable] public class Appclass : MonoBehaviour { public LIST_CONTENT_FDLIVE _list_conent_fdlist; public LIST_SCRIPT_LIST _list_script_list; public LIST_COMMANDER _list_commander; public LIST_VIDEO_EXTRA_INFO _list_video_extra_info; } ///////////////////////////////////// /// Default class ///////////////////////////////////// /// [Serializable] public class APP_INFO { public string version0; public string version1; public string version2; public string appVersion; public string phoneNumber; public string market_url; public string market_url_short; public string facebook_url; public string facebook_link_icon; public string bundle_id; public APP_INFO() { phoneNumber = "UNKNOW"; version0 = "0"; version1 = "4"; version2 = "3"; appVersion = "V." + version0 + "." + version1 + "." + version2; appVersion += "1.ALPHA"; #if _DIRECT_URL_ appVersion += ".D"; #endif } } [Serializable] public class TEMP_TEXTURE { public string url; public Texture texture; public TEMP_TEXTURE() { url = string.Empty; } } ///////////////////////////////////// /// Custom class ///////////////////////////////////// /// [Serializable] public class LIST_VIDEO_EXTRA_INFO { public List<VIDEO_EXTRA_INFOMATION> result; } [Serializable] public class LIST_COMMANDER { public List<LIST_COMMANDER_ITEM> result; } [Serializable] public class LIST_COMMANDER_ITEM { public int id; public int video_id; public string data; public long timestamp; } [Serializable] public class LIST_CONTENT_FDLIVE { public List<LIST_CONTENT_FDLIVE_ITEM> result; ~LIST_CONTENT_FDLIVE() { } } [Serializable] public class LIST_SCRIPT_LIST { public List<LIST_SCRIPT_LIST_ITEM> result; } [Serializable] public class LIST_CONTENT_FDLIVE_ITEM { const string _4DREPLAY_TYPE_ = ".4ds"; public int id; public string title; public string url; public string type; public VIDEO_CONTENT_TYPE _type; public int default_channel; public int max_channel; public sub_category category; public sub_thumbnail thumbnail; public MediaPlayerCtrl controler; public LIST_CONTENT_FDLIVE_ITEM() { //_prefab = new GameObject(); bool isResult = Enum.TryParse<VIDEO_CONTENT_TYPE>(type, out _type); } internal string GETURL() { if(url.Contains(_4DREPLAY_TYPE_) == true) { return string.Format("{0}?type={1}&quality=fhd&target={2}", url, type, default_channel); }else { return url; } throw new NotImplementedException(); } public void SET_CATEGOTY_KET() { bool result = Enum.TryParse<CATEGORY_KEY>(category.key, out category._key); } [Serializable] public class sub_category { public int id; public string name; public string key; public CATEGORY_KEY _key; } [Serializable] public class sub_thumbnail { public string url; } } [Serializable] public class LIST_SCRIPT_LIST_ITEM_SUB { public RECV_TYPE type; public int id; public string name; public string content; public string filename; public void SET_TYPE() { if(!string.IsNullOrEmpty(filename)) { string[] _tmp = filename.Split("_"[0]); if(_tmp[0].Equals("cs")) { type = RECV_TYPE.CAMERA_SCRIPT; }else if(_tmp[0].Equals("tb")) { type = RECV_TYPE.TABLE; }else if(_tmp[0].Equals("l")) { type = RECV_TYPE.LIST; } } } } [Serializable] public class LIST_SCRIPT_LIST_ITEM { public RECV_TYPE type; public int id; public string name; public string filename; public string cs_commands_data; public LIST_SCRIPT_LIST_ITEM() { } public void SET_TYPE() { if(!string.IsNullOrEmpty(filename)) { string[] _tmp = filename.Split("_"[0]); if(_tmp[0].Equals("cs")) { type = RECV_TYPE.CAMERA_SCRIPT; }else if(_tmp[0].Equals("tb")) { type = RECV_TYPE.TABLE; }else if(_tmp[0].Equals("l")) { type = RECV_TYPE.LIST; } } } } [Serializable] public class DEFAULT_EFFECT_LIST { public int index; public string resources_path; public string pfb_name; public string etc; public DEFAULT_EFFECT_LIST(string[] tableData) { int j = 0; this.index = Convert.ToInt32(tableData[j ++]); this.resources_path = tableData[j ++]; this.pfb_name = tableData[j ++]; this.etc = tableData[j ++]; resources_path = resources_path.TrimStart(); resources_path = resources_path.TrimEnd(); resources_path = resources_path.Trim(); pfb_name = pfb_name.TrimStart(); pfb_name = pfb_name.TrimEnd(); pfb_name = pfb_name.Trim(); } public string GET_PATH() { return string.Format("{0}{1}", resources_path, pfb_name); } } [Serializable] public class DEFAULT_EFFECT_TABLE { public int index; public int power_min; public int power_max; public int effect_index; public DEFAULT_EFFECT_LIST _effect_index; public float scaleX; public float scaleY; public float scaleZ; public string etc; public DEFAULT_EFFECT_TABLE(string[] tableData) { int j = 0; this.index = Convert.ToInt32(tableData[j ++]); this.power_min = Convert.ToInt32(tableData[j ++]); this.power_max = Convert.ToInt32(tableData[j ++]); this.effect_index = Convert.ToInt32(tableData[j ++]); this.scaleX = Convert.ToSingle(tableData[j ++]); this.scaleY = Convert.ToSingle(tableData[j ++]); this.scaleZ = Convert.ToSingle(tableData[j ++]); this.etc = tableData[j ++]; } } [Serializable] public class DEFAULT_PLAYER_LIST { public int index; public string country; public string teamName; public string playerName; public int age; public int tall; public int weight; public string s_skill; public string spcial_info; public string thumnail_url; public bool isPenalty; public float nowPenaltyTime; public int yellowCardCnt; public DEFAULT_PLAYER_LIST(string[] tableData) { int j = 0; this.index = Convert.ToInt32(tableData[j ++]); this.country = tableData[j ++]; this.teamName = tableData[j ++]; this.playerName = tableData[j ++]; this.age = Convert.ToInt32(tableData[j ++]); this.tall = Convert.ToInt32(tableData[j ++]); this.weight = Convert.ToInt32(tableData[j ++]); this.s_skill = tableData[j ++]; this.s_skill = this.s_skill.Replace("|", "\n"); this.spcial_info = tableData[j ++]; this.spcial_info = this.spcial_info.Replace("|", "\n"); this.thumnail_url = tableData[j ++]; } } [Serializable] public class GAME_INFO_TAE { public GAME_TYPE_TAE gameType; //득점제 실점제 /////////////////////////// public int index; public string gameName; public string stadiumName; public long gameStartTime; //기간 : 경기 시작 public long gameEndTime; //기간 : 경기 종료 public string gameWeight; /////////////////////////// public int maxStageCnt; //총 경기수 public int nowStageCnt; //경기차수 public int maxRoundCnt_normal; //총 라운드수 3판 2선승이면 3 public int maxRoudnCnt_final; public int roundTime; public bool isPlaying; public int nowRoundCnt; public float nowRoundTime; public ROUND_INFO_TAE[] roundInfo; //어디서 생성하지...? public GAME_INFO_TAE(string[] tableData) { int j = 0; this.index = Convert.ToInt32(tableData[j ++]); bool result = Enum.TryParse<GAME_TYPE_TAE>(tableData[j ++], out this.gameType); if(result == false) { Debug.Log("need check GAME_TYPE_TAE"); } this.gameName = tableData[j ++]; this.stadiumName = tableData[j ++]; this.gameStartTime = Convert.ToInt64(tableData[j ++]); this.gameEndTime = Convert.ToInt64(tableData[j ++]); this.gameWeight = tableData[j ++]; this.maxStageCnt = Convert.ToInt32(tableData[j ++]); this.maxRoundCnt_normal = Convert.ToInt32(tableData[j ++]); this.maxRoudnCnt_final = Convert.ToInt32(tableData[j ++]); this.roundTime = Convert.ToInt32(tableData[j ++]); } } [Serializable] public class ROUND_INFO_TAE { public int nowRoundCnt; //진행중인 라운드 수 public float prevBlueScore; public float prevRedScore; public float blueScore; public float redScore; public int blueWinCnt; public int redWinCnt; public DEFAULT_PLAYER_LIST blue; public DEFAULT_PLAYER_LIST red; public ROUND_INFO_TAE() { } public ROUND_INFO_TAE(DEFAULT_PLAYER_LIST blue, DEFAULT_PLAYER_LIST red) { this.blue = blue; this.red = red; this.blue.isPenalty = false; this.red.isPenalty = false; this.blue.yellowCardCnt = 0; this.red.yellowCardCnt = 0; } } [Serializable] public class COUNTRY_CODE { public int index; public string name; public string alpha2Code; public string alpha3Code; public int numbericCode; public string isoCode; public COUNTRY_CODE(string[] tableData) { int i = 0; this.index = Convert.ToInt32(tableData[i++]); this.name = tableData[i++]; this.alpha2Code = tableData[i++]; this.alpha3Code = tableData[i++]; this.numbericCode = Convert.ToInt32(tableData[i++]); this.isoCode = tableData[i++]; } } public enum GAME_TYPE_TAE { NONE = -1, PLUS, //득점제 MINUS //실점제 } public class SEND_FDLIVE_SWIPE { public string sessionId; public string actionType; public string direction; public int speed; public int moveFrame; }
using System; namespace qbq.EPCIS.Repository.Custom.Entities { class EventData { //----------------------------------------------------------------- //-- Tabelle zum Zwischenspeichern der Wurzel-Event Daten //----------------------------------------------------------------- // //create table #EventData //( //EPCISEventID bigint not null PRIMARY KEY IDENTITY(1,1), //[ClientID] BIGINT NOT NULL, //[EventTime] DATETIME2 (0) NOT NULL, //[RecordTime] DATETIME2 (0) NOT NULL, //[EventTimeZoneOffset] DATETIMEOFFSET (7) NOT NULL, //[EPCISRepresentation] XML NOT NULL //); public long EpcisEventId { get; set; } public long ClientId { get; set; } public DateTime EventTime { get; set; } public DateTime RecordTime { get; set; } public DateTimeOffset EventTimeZoneOffset { get; set; } public string EpcisRepresentation { get; set; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Consensus; using FiiiChain.Entities; using FiiiChain.Framework; using FiiiChain.Messages; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FiiiChain.Business.Extensions { public struct InputExtensionParams { public string BlockHash; public string InputAccountId; public long InputAmount; public string TransactionHash; } public struct TransExtensionParams { public string BlockHash; public long Height; public List<Input> Inputs; public List<Output> Outputs; public long TotalInput; public long TotalOutput; } public static class BlockMsgExtension { public static Block ConvertToEntity(this BlockMsg blockMsg, List<Transaction> transactions) { var block = new Block(); block.Hash = blockMsg.Header.Hash; block.Version = blockMsg.Header.Version; block.Height = blockMsg.Header.Height; block.PreviousBlockHash = blockMsg.Header.PreviousBlockHash; block.Bits = blockMsg.Header.Bits; block.Nonce = blockMsg.Header.Nonce; block.GeneratorId = blockMsg.Header.GeneratorId; block.Timestamp = blockMsg.Header.Timestamp; block.BlockSignature = blockMsg.Header.BlockSignature; block.PayloadHash = blockMsg.Header.PayloadHash; block.IsDiscarded = false; block.IsVerified = false; //交易信息 block.Transactions = transactions; block.TotalAmount += transactions.Sum(x => x.TotalOutput); block.TotalFee += transactions.Sum(x => x.Fee); return block; } public static Output ConvertToEntiry(this OutputMsg outputMsg, TransactionMsg transaction, BlockMsg blockMsg) { Output output = new Output(); output.Amount = outputMsg.Amount; output.BlockHash = blockMsg.Header.Hash; output.Index = outputMsg.Index; output.LockScript = outputMsg.LockScript; output.Size = outputMsg.Size; output.Index = transaction.Outputs.IndexOf(outputMsg); output.TransactionHash = transaction.Hash; output.Spent = false; output.IsDiscarded = false; var receiverId = AccountIdHelper.CreateAccountAddressByPublicKeyHash( Base16.Decode( Script.GetPublicKeyHashFromLockScript(outputMsg.LockScript) )); output.ReceiverId = receiverId; return output; } public static Input ConvertToEntiry(this InputMsg inputMsg, InputExtensionParams inputExtension) { Input input = new Input(); input.AccountId = inputExtension.InputAccountId; input.Amount = inputExtension.InputAmount; input.BlockHash = inputExtension.BlockHash; input.IsDiscarded = false; input.OutputIndex = inputMsg.OutputIndex; input.OutputTransactionHash = inputMsg.OutputTransactionHash; input.Size = inputMsg.Size; input.TransactionHash = inputExtension.TransactionHash; input.UnlockScript = inputMsg.UnlockScript; return input; } public static Transaction ConvertToEntity(this TransactionMsg transactionMsg, TransExtensionParams transExtension, bool isCoinbase = false) { Transaction transaction = new Transaction(); transaction.BlockHash = transExtension.BlockHash; transaction.ExpiredTime = transactionMsg.ExpiredTime; transaction.Hash = transactionMsg.Hash; transaction.Inputs = transExtension.Inputs; transaction.IsDiscarded = false; transaction.LockTime = transactionMsg.Locktime; transaction.Outputs = transExtension.Outputs; transaction.Size = transactionMsg.Size; transaction.Timestamp = transactionMsg.Timestamp; transaction.TotalInput = transExtension.TotalInput; transaction.TotalOutput = transExtension.TotalOutput; transaction.Version = transactionMsg.Version; if (isCoinbase) transaction.Fee = 0; else transaction.Fee = transExtension.TotalInput - transExtension.TotalOutput; return transaction; } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Net.Mail; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace WebApp.Services { public class EmailNotificationService { private FileSystemService _fileSystemService { get; } public EmailNotificationService(FileSystemService fileSystemService) { _fileSystemService = fileSystemService; } public async Task SendNotificationAsync(MailAddress to, string subject, string htmlBody) { MailAddress from = new MailAddress("inspiredapp00@gmail.com", "Inspired-app"); MailMessage msg = new MailMessage(from, to) { Subject = subject, Body = htmlBody, IsBodyHtml = true }; SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("inspiredapp00@gmail.com", "Qwerty//Qaz"), EnableSsl = true }; await smtpClient.SendMailAsync(msg); } public void SendRecoveryPasswordNotification(string email, string content) { } } }
using STLFoodTruckFavorites2.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace STLFoodTruckFavorites2.ViewModels { public class FoodTruckListViewModel { public static List<FoodTruckListViewModel> GetFoodTruckListViewModels(ApplicationDbContext context) { List<Models.FoodTruck> foodTrucks = context.FoodTrucks.ToList(); List<FoodTruckListViewModel> foodTruckListViewModels = new List<FoodTruckListViewModel>(); foreach (Models.FoodTruck foodTruck in foodTrucks) { FoodTruckListViewModel viewModel = new FoodTruckListViewModel(); viewModel.ID = foodTruck.ID; viewModel.Name = foodTruck.Name; viewModel.Description = foodTruck.Description; foodTruckListViewModels.Add(viewModel); } return foodTruckListViewModels; } public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core.Interops { public sealed partial class VlcManager { public bool GetVideoMarqueeEnabled(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Enable) == 1; } public string GetVideoMarqueeText(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return Utf8InteropStringConverter.Utf8InteropToString(myLibraryLoader.GetInteropDelegate<GetVideoMarqueeString>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Text)); } public int GetVideoMarqueeColor(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Color); } public int GetVideoMarqueeOpacity(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Opacity); } public int GetVideoMarqueePosition(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Position); } public int GetVideoMarqueeRefresh(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Refresh); } public int GetVideoMarqueeSize(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Size); } public int GetVideoMarqueeTimeout(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Timeout); } public int GetVideoMarqueeX(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.X); } public int GetVideoMarqueeY(VlcMediaPlayerInstance mediaPlayerInstance) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); return myLibraryLoader.GetInteropDelegate<GetVideoMarqueeInteger>().Invoke(mediaPlayerInstance, VideoMarqueeOptions.Y); } } }
using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class Kernel32 { /// <summary> /// An application-defined function registered with the RegisterBadMemoryNotification function that is called when one or more bad memory pages are detected. /// </summary> [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void PBAD_MEMORY_CALLBACK_ROUTINE(); /// <summary>Flags that indicate which of the file cache limits are enabled.</summary> [PInvokeData("MemoryApi.h")] [Flags] public enum FILE_CACHE_LIMITS : uint { /// <summary> /// Enable the maximum size limit. /// <para>The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive.</para> /// </summary> FILE_CACHE_MAX_HARD_ENABLE = 0x00000001, /// <summary> /// Disable the maximum size limit. /// <para>The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive.</para> /// </summary> FILE_CACHE_MAX_HARD_DISABLE = 0x00000002, /// <summary> /// Enable the minimum size limit. /// <para>The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive.</para> /// </summary> FILE_CACHE_MIN_HARD_ENABLE = 0x00000004, /// <summary> /// Disable the minimum size limit. /// <para>The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive.</para> /// </summary> FILE_CACHE_MIN_HARD_DISABLE = 0x00000008, } /// <summary>The type of access to a file mapping object, which determines the page protection of the pages.</summary> [PInvokeData("MemoryApi.h")] [Flags] public enum FILE_MAP : uint { /// <summary> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection. /// <para>When used with MapViewOfFileEx, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE.</para> /// </summary> FILE_MAP_WRITE = SECTION_MAP.SECTION_MAP_WRITE, /// <summary> /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation. /// <para>The file mapping object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection.</para> /// </summary> FILE_MAP_READ = SECTION_MAP.SECTION_MAP_READ, /// <summary> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection. /// <para>When used with the MapViewOfFileEx function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE.</para> /// </summary> FILE_MAP_ALL_ACCESS = SECTION_MAP.SECTION_ALL_ACCESS, /// <summary> /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created with /// PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection. /// <para>Windows Server 2003 and Windows XP: This value is available starting with Windows XP with SP2 and Windows Server 2003 with SP1.</para> /// </summary> FILE_MAP_EXECUTE = SECTION_MAP.SECTION_MAP_EXECUTE_EXPLICIT, /// <summary> /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, PAGE_WRITECOPY, /// PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection. /// <para> /// When a process writes to a copy-on-write page, the system copies the original page to a new page that is private to the process.The new page is /// backed by the paging file.The protection of the new page changes from copy-on-write to read/write. /// </para> /// <para> /// When copy-on-write access is specified, the system and process commit charge taken is for the entire view because the calling process can /// potentially write to every page in the view, making all pages private. The contents of the new page are never written back to the original file /// and are lost when the view is unmapped. /// </para> /// </summary> FILE_MAP_COPY = 0x00000001, /// <summary></summary> FILE_MAP_RESERVE = 0x80000000, /// <summary> /// Sets all the locations in the mapped file as invalid targets for CFG. This flag is similar to PAGE_TARGETS_INVALID. It is used along with the /// execute access right FILE_MAP_EXECUTE. Any indirect call to locations in those pages will fail CFG checks and the process will be terminated. The /// default behavior for executable pages allocated is to be marked valid call targets for CFG. /// </summary> FILE_MAP_TARGETS_INVALID = 0x40000000, /// <summary></summary> FILE_MAP_LARGE_PAGES = 0x20000000, } /// <summary>The type of memory allocation.</summary> [PInvokeData("WinNT.h")] [Flags] public enum MEM_ALLOCATION_TYPE : uint { /// <summary> /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function /// also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated /// unless/until the virtual addresses are actually accessed.To reserve and commit pages in one step, call VirtualAlloc with .Attempting to commit a /// specific address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL lpAddress fails unless the entire range has already been /// reserved. The resulting error code is ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to /// fail. This means that you can commit pages without first determining the current commitment state of each page.If lpAddress specifies an address /// within an enclave, flAllocationType must be MEM_COMMIT. /// </summary> MEM_COMMIT = 0x00001000, /// <summary> /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on /// disk.You can commit reserved pages in subsequent calls to the VirtualAlloc function. To reserve and commit pages in one step, call VirtualAlloc /// with MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and LocalAlloc, cannot use a reserved range of memory until it is released. /// </summary> MEM_RESERVE = 0x00002000, /// <summary> /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function does not fail if you /// attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first determining the current commitment /// state.Do not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when the lpAddress parameter provides the base address for /// an enclave. /// </summary> MEM_DECOMMIT = 0x00004000, /// <summary> /// Releases the specified region of pages. After this operation, the pages are in the free state. If you specify this value, dwSize must be 0 /// (zero), and lpAddress must point to the base address returned by the VirtualAlloc function when the region is reserved. The function fails if /// either of these conditions is not met. If any pages in the region are committed currently, the function first decommits, and then releases /// them.The function does not fail if you attempt to release pages that are in different states, some reserved and some committed. This means that /// you can release a range of pages without first determining the current commitment state.Do not use this value with MEM_DECOMMIT. /// </summary> MEM_RELEASE = 0x00008000, /// <summary> /// Indicates free pages not accessible to the calling process and available to be allocated. For free pages, the information in the AllocationBase, /// AllocationProtect, Protect, and Type members is undefined. /// </summary> MEM_FREE = 0x00010000, /// <summary>Indicates that the memory pages within the region are private (that is, not shared by other processes).</summary> MEM_PRIVATE = 0x00020000, /// <summary>Indicates that the memory pages within the region are mapped into the view of a section.</summary> MEM_MAPPED = 0x00040000, /// <summary> /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read from or written /// to the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other /// value.Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, /// decommit the memory and then recommit it.When you specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must /// still set flProtect to a valid protection value, such as PAGE_NOACCESS.VirtualAlloc returns an error if you use MEM_RESET and the range of memory /// is mapped to a file. A shared view is only acceptable if it is mapped to a paging file. /// </summary> MEM_RESET = 0x00080000, /// <summary>Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations.</summary> MEM_TOP_DOWN = 0x00100000, /// <summary> /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify MEM_RESERVE.To /// retrieve the addresses of the pages that have been written to since the region was allocated or the write-tracking state was reset, call the /// GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or ResetWriteWatch. The write-tracking feature remains enabled for /// the memory region until the region is freed. /// </summary> MEM_WRITE_WATCH = 0x00200000, /// <summary> /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with MEM_RESERVE and no other values. /// </summary> MEM_PHYSICAL = 0x00400000, /// <summary></summary> MEM_ROTATE = 0x00800000, /// <summary></summary> MEM_DIFFERENT_IMAGE_BASE_OK = 0x00800000, /// <summary> /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that the data in the /// specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the effects of MEM_RESET. If the /// function succeeds, that means all data in the specified address range is intact. If the function fails, at least some of the data in the address /// range has been replaced with zeroes.This value cannot be used with any other value. If MEM_RESET_UNDO is called on an address range which was not /// MEM_RESET earlier, the behavior is undefined. When you specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you /// must still set flProtect to a valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows /// Vista, Windows Server 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// </summary> MEM_RESET_UNDO = 0x01000000, /// <summary> /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this value, use the /// GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// </summary> MEM_LARGE_PAGES = 0x20000000, /// <summary></summary> MEM_4MB_PAGES = 0x80000000, /// <summary></summary> MEM_64K_PAGES = MEM_LARGE_PAGES | MEM_PHYSICAL } /// <summary> /// The following are the memory-protection options; you must specify one of the following values when allocating or protecting a page in memory. /// Protection attributes cannot be assigned to a portion of a page; they can only be assigned to a whole page. /// </summary> [PInvokeData("WinNT.h")] [Flags] public enum MEM_PROTECTION : uint { /// <summary> /// Disables all access to the committed region of pages. An attempt to read from, write to, or execute the committed region results in an access violation. /// <para>This flag is not supported by the CreateFileMapping function.</para> /// </summary> PAGE_NOACCESS = 0x01, /// <summary> /// Enables read-only access to the committed region of pages. An attempt to write to the committed region results in an access violation. If Data /// Execution Prevention is enabled, an attempt to execute code in the committed region results in an access violation. /// </summary> PAGE_READONLY = 0x02, /// <summary> /// Enables read-only or read/write access to the committed region of pages. If Data Execution Prevention is enabled, attempting to execute code in /// the committed region results in an access violation. /// </summary> PAGE_READWRITE = 0x04, /// <summary> /// Enables read-only or copy-on-write access to a mapped view of a file mapping object. An attempt to write to a committed copy-on-write page /// results in a private copy of the page being made for the process. The private page is marked as PAGE_READWRITE, and the change is written to the /// new page. If Data Execution Prevention is enabled, attempting to execute code in the committed region results in an access violation. /// <para>This flag is not supported by the VirtualAlloc or VirtualAllocEx functions.</para> /// </summary> PAGE_WRITECOPY = 0x08, /// <summary> /// Enables execute access to the committed region of pages. An attempt to write to the committed region results in an access violation. /// <para>This flag is not supported by the CreateFileMapping function.</para> /// </summary> PAGE_EXECUTE = 0x10, /// <summary> /// Enables execute or read-only access to the committed region of pages. An attempt to write to the committed region results in an access violation. /// <para> /// Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until Windows XP with SP2 and Windows /// Server 2003 with SP1. /// </para> /// </summary> PAGE_EXECUTE_READ = 0x20, /// <summary> /// Enables execute, read-only, or read/write access to the committed region of pages. /// <para> /// Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until Windows XP with SP2 and Windows /// Server 2003 with SP1. /// </para> /// </summary> PAGE_EXECUTE_READWRITE = 0x40, /// <summary> /// Enables execute, read-only, or copy-on-write access to a mapped view of a file mapping object. An attempt to write to a committed copy-on-write /// page results in a private copy of the page being made for the process. The private page is marked as PAGE_EXECUTE_READWRITE, and the change is /// written to the new page. /// <para>This flag is not supported by the VirtualAlloc or VirtualAllocEx functions.</para> /// <para> /// Windows Vista, Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until Windows Vista with SP1 /// and Windows Server 2008. /// </para> /// </summary> PAGE_EXECUTE_WRITECOPY = 0x80, /// <summary> /// Pages in the region become guard pages. Any attempt to access a guard page causes the system to raise a STATUS_GUARD_PAGE_VIOLATION exception and /// turn off the guard page status. Guard pages thus act as a one-time access alarm. For more information, see Creating Guard Pages. /// <para>When an access attempt leads the system to turn off guard page status, the underlying page protection takes over.</para> /// <para>If a guard page exception occurs during a system service, the service typically returns a failure status indicator.</para> /// <para>This value cannot be used with PAGE_NOACCESS.</para> /// <para>This flag is not supported by the CreateFileMapping function.</para> /// </summary> PAGE_GUARD = 0x100, /// <summary> /// Sets all pages to be non-cachable. Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception. /// <para>The PAGE_NOCACHE flag cannot be used with the PAGE_GUARD, PAGE_NOACCESS, or PAGE_WRITECOMBINE flags.</para> /// <para> /// The PAGE_NOCACHE flag can be used only when allocating private memory with the VirtualAlloc, VirtualAllocEx, or VirtualAllocExNuma functions. To /// enable non-cached memory access for shared memory, specify the SEC_NOCACHE flag when calling the CreateFileMapping function. /// </para> /// </summary> PAGE_NOCACHE = 0x200, /// <summary> /// Sets all pages to be write-combined. /// <para> /// Applications should not use this attribute except when explicitly required for a device. Using the interlocked functions with memory that is /// mapped as write-combined can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception. /// </para> /// <para>The PAGE_WRITECOMBINE flag cannot be specified with the PAGE_NOACCESS, PAGE_GUARD, and PAGE_NOCACHE flags.</para> /// <para> /// The PAGE_WRITECOMBINE flag can be used only when allocating private memory with the VirtualAlloc, VirtualAllocEx, or VirtualAllocExNuma /// functions. To enable write-combined memory access for shared memory, specify the SEC_WRITECOMBINE flag when calling the CreateFileMapping function. /// </para> /// <para>Windows Server 2003 and Windows XP: This flag is not supported until Windows Server 2003 with SP1.</para> /// </summary> PAGE_WRITECOMBINE = 0x400, /// <summary>The page contents that you supply are excluded from measurement with the EEXTEND instruction of the Intel SGX programming model.</summary> PAGE_ENCLAVE_UNVALIDATED = 0x20000000, /// <summary> /// Sets all locations in the pages as invalid targets for CFG. Used along with any execute page protection like PAGE_EXECUTE, PAGE_EXECUTE_READ, /// PAGE_EXECUTE_READWRITE and PAGE_EXECUTE_WRITECOPY. Any indirect call to locations in those pages will fail CFG checks and the process will be /// terminated. The default behavior for executable pages allocated is to be marked valid call targets for CFG. /// <para>This flag is not supported by the VirtualProtect or CreateFileMapping functions.</para> /// </summary> PAGE_TARGETS_INVALID = 0x40000000, /// <summary> /// Pages in the region will not have their CFG information updated while the protection changes for VirtualProtect. For example, if the pages in the /// region was allocated using PAGE_TARGETS_INVALID, then the invalid information will be maintained while the page protection changes. This flag is /// only valid when the protection changes to an executable type like PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE and /// PAGE_EXECUTE_WRITECOPY. The default behavior for VirtualProtect protection change to executable is to mark all locations as valid call targets /// for CFG. /// <para>The following are modifiers that can be used in addition to the options provided in the previous table, except as noted.</para> /// </summary> PAGE_TARGETS_NO_UPDATE = 0x40000000, /// <summary>The page contains a thread control structure (TCS).</summary> PAGE_ENCLAVE_THREAD_CONTROL = 0x80000000, /// <summary></summary> PAGE_REVERT_TO_FILE_MAP = 0x80000000, } /// <summary>The memory condition under which the object is to be signaled.</summary> [PInvokeData("MemoryApi.h")] public enum MEMORY_RESOURCE_NOTIFICATION_TYPE { /// <summary>Available physical memory is running low.</summary> LowMemoryResourceNotification, /// <summary>Available physical memory is high.</summary> HighMemoryResourceNotification, } /// <summary> /// Indicates how important the offered memory is to the application. A higher priority increases the probability that the offered memory can be /// reclaimed intact when calling ReclaimVirtualMemory. /// </summary> public enum OFFER_PRIORITY { /// <summary>The offered memory is very low priority, and should be the first discarded.</summary> VmOfferPriorityVeryLow = 1, /// <summary>The offered memory is low priority.</summary> VmOfferPriorityLow, /// <summary>The offered memory is below normal priority.</summary> VmOfferPriorityBelowNormal, /// <summary>The offered memory is of normal priority to the application, and should be the last discarded.</summary> VmOfferPriorityNormal } /// <summary>Flags that determines the allocation attributes of the section, file, page, etc.</summary> [PInvokeData("winbase.h", MSDNShortId = "d3302183-76a0-47ec-874f-1173db353dfe")] public enum SEC_ALLOC : uint { /// <summary> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is committed rather than reserved. The system must have enough committable /// pages to hold the entire mapping. Otherwise, CreateFileMapping fails.This attribute has no effect for file mapping objects that are backed by /// executable image files or data files (the hfile parameter is a handle to a file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is /// specified, SEC_COMMIT is assumed. /// </summary> SEC_COMMIT = 0x8000000, /// <summary> /// Specifies that the file that the hFile parameter specifies is an executable image file.The SEC_IMAGE attribute must be combined with a page /// protection value such as PAGE_READONLY. However, this page protection value has no effect on views of the executable image file. Page protection for /// views of an executable image file is determined by the executable file itself.No other attributes are valid with SEC_IMAGE. /// </summary> SEC_IMAGE = 0x1000000, /// <summary> /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded image file will have /// no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the SEC_IMAGE_NO_EXECUTE attribute will not invoke /// driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The SEC_IMAGE_NO_EXECUTE attribute must be combined with the /// PAGE_READONLY page protection value. No other attributes are valid with SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008, /// Windows Vista, Windows Server 2003 and Windows XP: This value is not supported before Windows Server 2012 and Windows 8. /// </summary> SEC_IMAGE_NO_EXECUTE = 0x11000000, /// <summary> /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile parameter is /// INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable image files or data files (the hFile /// parameter is a handle to an executable image or data file).The maximum size of the file mapping object must be a multiple of the minimum size of a /// large page returned by the GetLargePageMinimum function. If it is not, CreateFileMapping fails. When mapping a view of a file mapping object created /// with SEC_LARGE_PAGES, the base address and view size must also be multiples of the minimum large page size.SEC_LARGE_PAGES requires the /// SeLockMemoryPrivilege privilege to be enabled in the caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be /// specified.Windows Server 2003: This value is not supported until Windows Server 2003 with SP1.Windows XP: This value is not supported. /// </summary> SEC_LARGE_PAGES = 0x80000000, /// <summary> /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_NOCACHE requires either the /// SEC_RESERVE or SEC_COMMIT attribute to be set. /// </summary> SEC_NOCACHE = 0x10000000, /// <summary> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is reserved for later use by the process rather than committed.Reserved /// pages can be committed in subsequent calls to the VirtualAlloc function. After the pages are committed, they cannot be freed or decommitted with the /// VirtualFree function.This attribute has no effect for file mapping objects that are backed by executable image files or data files (the hfile /// parameter is a handle to a file).SEC_RESERVE cannot be combined with SEC_COMMIT. /// </summary> SEC_RESERVE = 0x4000000, /// <summary> /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_WRITECOMBINE requires either /// the SEC_RESERVE or SEC_COMMIT attribute to be set.Windows Server 2003 and Windows XP: This flag is not supported until Windows Vista. /// </summary> SEC_WRITECOMBINE = 0x40000000, } /// <summary>Used by <see cref="QueryVirtualMemoryInformation"/>.</summary> public enum WIN32_MEMORY_INFORMATION_CLASS { /// <summary>This parameter must point to a <c>WIN32_MEMORY_REGION_INFORMATION</c> structure.</summary> MemoryRegionInfo } /// <summary>Flags used in <see cref="GetWriteWatch"/>.</summary> public enum WRITE_WATCH { /// <summary>Do not reset the write-tracking state.</summary> WRITE_WATCH_UNSPECIFIED = 0, /// <summary>Reset the write-tracking state.</summary> WRITE_WATCH_FLAG_RESET = 1 } /// <summary> /// <para>Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified process.</para> /// <para> /// <c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>AllocateUserPhysicalPages</c> is not supported for 32-bit applications. /// </para> /// </summary> /// <param name="hProcess"> /// <para>A handle to a process.</para> /// <para> /// The function allocates memory that can later be mapped within the virtual address space of this process. The handle must have the /// <c>PROCESS_VM_OPERATION</c> access right. For more information, see Process Security and Access Rights. /// </para> /// </param> /// <param name="NumberOfPages"> /// <para>The size of the physical memory to allocate, in pages.</para> /// <para> /// To determine the page size of the computer, use the <c>GetSystemInfo</c> function. On output, this parameter receives the number of pages that are /// actually allocated, which might be less than the number requested. /// </para> /// </param> /// <param name="UserPfnArray"> /// <para>A pointer to an array to store the page frame numbers of the allocated memory.</para> /// <para>The size of the array that is allocated should be at least the NumberOfPages times the size of the <c>ULONG_PTR</c> data type.</para> /// <para> /// Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in the buffer is not /// useful to an application. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is <c>TRUE</c>.</para> /// <para> /// Fewer pages than requested can be allocated. The caller must check the value of the NumberOfPages parameter on return to see how many pages are /// allocated. All allocated page frame numbers are sequentially placed in the memory pointed to by the UserPfnArray parameter. /// </para> /// <para>If the function fails, the return value is <c>FALSE</c>, and no frames are allocated. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI AllocateUserPhysicalPages( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _Out_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366528")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocateUserPhysicalPages([In] HPROCESS hProcess, ref SizeT NumberOfPages, out IntPtr UserPfnArray); /// <summary> /// Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified process and specifies /// the NUMA node for the physical memory. /// </summary> /// <param name="hProcess"> /// <para>A handle to a process.</para> /// <para> /// The function allocates memory that can later be mapped within the virtual address space of this process. The handle must have the /// <c>PROCESS_VM_OPERATION</c> access right. For more information, see Process Security and Access Rights. /// </para> /// </param> /// <param name="NumberOfPages"> /// <para>The size of the physical memory to allocate, in pages.</para> /// <para> /// To determine the page size of the computer, use the <c>GetSystemInfo</c> function. On output, this parameter receives the number of pages that are /// actually allocated, which might be less than the number requested. /// </para> /// </param> /// <param name="PageArray"> /// <para>A pointer to an array to store the page frame numbers of the allocated memory.</para> /// <para>The size of the array that is allocated should be at least the NumberOfPages times the size of the <c>ULONG_PTR</c> data type.</para> /// </param> /// <param name="nndPreferred">The NUMA node where the physical memory should reside.</param> /// <returns> /// <para>If the function succeeds, the return value is <c>TRUE</c>.</para> /// <para> /// Fewer pages than requested can be allocated. The caller must check the value of the NumberOfPages parameter on return to see how many pages are /// allocated. All allocated page frame numbers are sequentially placed in the memory pointed to by the PageArray parameter. /// </para> /// <para> /// If the function fails, the return value is <c>FALSE</c> and no frames are allocated. To get extended error information, call the <c>GetLastError</c> function. /// </para> /// </returns> // BOOL WINAPI AllocateUserPhysicalPagesNuma( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _Out_ PULONG_PTR PageArray, _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366529")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocateUserPhysicalPagesNuma([In] HPROCESS hProcess, ref SizeT NumberOfPages, out IntPtr PageArray, uint nndPreferred); /// <summary> /// <para>Creates or opens a named or unnamed file mapping object for a specified file.</para> /// <para>To specify the NUMA node for the physical memory, see <c>CreateFileMappingNuma</c>.</para> /// </summary> /// <param name="hFile"> /// <para>A handle to the file from which to create a file mapping object.</para> /// <para> /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. It is not required, /// but it is recommended that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights. /// </para> /// <para> /// If hFile is <c>INVALID_HANDLE_VALUE</c>, the calling process must also specify a size for the file mapping object in the dwMaximumSizeHigh and /// dwMaximumSizeLow parameters. In this scenario, <c>CreateFileMapping</c> creates a file mapping object of a specified size that is backed by the /// system paging file instead of by a file in the file system. /// </para> /// </param> /// <param name="lpAttributes"> /// <para> /// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that determines whether a returned handle can be inherited by child processes. The /// <c>lpSecurityDescriptor</c> member of the <c>SECURITY_ATTRIBUTES</c> structure specifies a security descriptor for a new file mapping object. /// </para> /// <para> /// If lpAttributes is <c>NULL</c>, the handle cannot be inherited and the file mapping object gets a default security descriptor. The access control /// lists (ACL) in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. For more /// information, see File Mapping Security and Access Rights. /// </para> /// </param> /// <param name="flProtect"> /// <para>Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection.</para> /// <para>This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>PAGE_EXECUTE_READ0x20</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or execute access.The file handle specified by the hFile parameter must be created with the /// GENERIC_READ and GENERIC_EXECUTE access rights.Windows Server 2003 and Windows XP: This value is not available until Windows XP with SP2 and Windows /// Server 2003 with SP1. /// </term> /// </item> /// <item> /// <term>PAGE_EXECUTE_READWRITE0x40</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, read/write, or execute access.The file handle that the hFile parameter specifies must be /// created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights.Windows Server 2003 and Windows XP: This value is not available until /// Windows XP with SP2 and Windows Server 2003 with SP1. /// </term> /// </item> /// <item> /// <term>PAGE_EXECUTE_WRITECOPY0x80</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or execute access. This value is equivalent to PAGE_EXECUTE_READ.The file handle that the /// hFile parameter specifies must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.Windows Vista: This value is not available until /// Windows Vista with SP1.Windows Server 2003 and Windows XP: This value is not supported. /// </term> /// </item> /// <item> /// <term>PAGE_READONLY0x02</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access violation.The file /// handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// <item> /// <term>PAGE_READWRITE0x04</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies must be created with /// the GENERIC_READ and GENERIC_WRITE access rights. /// </term> /// </item> /// <item> /// <term>PAGE_WRITECOPY0x08</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that the hFile parameter /// specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// </list> /// </para> /// <para> /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the preceding page /// protection values. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>SEC_COMMIT0x8000000</term> /// <term> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is committed rather than reserved. The system must have enough committable /// pages to hold the entire mapping. Otherwise, CreateFileMapping fails.This attribute has no effect for file mapping objects that are backed by /// executable image files or data files (the hfile parameter is a handle to a file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is /// specified, SEC_COMMIT is assumed. /// </term> /// </item> /// <item> /// <term>SEC_IMAGE0x1000000</term> /// <term> /// Specifies that the file that the hFile parameter specifies is an executable image file.The SEC_IMAGE attribute must be combined with a page /// protection value such as PAGE_READONLY. However, this page protection value has no effect on views of the executable image file. Page protection for /// views of an executable image file is determined by the executable file itself.No other attributes are valid with SEC_IMAGE. /// </term> /// </item> /// <item> /// <term>SEC_IMAGE_NO_EXECUTE0x11000000</term> /// <term> /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded image file will have /// no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the SEC_IMAGE_NO_EXECUTE attribute will not invoke /// driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The SEC_IMAGE_NO_EXECUTE attribute must be combined with the /// PAGE_READONLY page protection value. No other attributes are valid with SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008, /// Windows Vista, Windows Server 2003 and Windows XP: This value is not supported before Windows Server 2012 and Windows 8. /// </term> /// </item> /// <item> /// <term>SEC_LARGE_PAGES0x80000000</term> /// <term> /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile parameter is /// INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable image files or data files (the hFile /// parameter is a handle to an executable image or data file).The maximum size of the file mapping object must be a multiple of the minimum size of a /// large page returned by the GetLargePageMinimum function. If it is not, CreateFileMapping fails. When mapping a view of a file mapping object created /// with SEC_LARGE_PAGES, the base address and view size must also be multiples of the minimum large page size.SEC_LARGE_PAGES requires the /// SeLockMemoryPrivilege privilege to be enabled in the caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be /// specified.Windows Server 2003: This value is not supported until Windows Server 2003 with SP1.Windows XP: This value is not supported. /// </term> /// </item> /// <item> /// <term>SEC_NOCACHE0x10000000</term> /// <term> /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_NOCACHE requires either the /// SEC_RESERVE or SEC_COMMIT attribute to be set. /// </term> /// </item> /// <item> /// <term>SEC_RESERVE0x4000000</term> /// <term> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is reserved for later use by the process rather than committed.Reserved /// pages can be committed in subsequent calls to the VirtualAlloc function. After the pages are committed, they cannot be freed or decommitted with the /// VirtualFree function.This attribute has no effect for file mapping objects that are backed by executable image files or data files (the hfile /// parameter is a handle to a file).SEC_RESERVE cannot be combined with SEC_COMMIT. /// </term> /// </item> /// <item> /// <term>SEC_WRITECOMBINE0x40000000</term> /// <term> /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_WRITECOMBINE requires either /// the SEC_RESERVE or SEC_COMMIT attribute to be set.Windows Server 2003 and Windows XP: This flag is not supported until Windows Vista. /// </term> /// </item> /// </list> /// </para> /// </param> /// <param name="dwMaximumSizeHigh">The high-order <c>DWORD</c> of the maximum size of the file mapping object.</param> /// <param name="dwMaximumSizeLow"> /// <para>The low-order <c>DWORD</c> of the maximum size of the file mapping object.</para> /// <para> /// If this parameter and dwMaximumSizeHigh are 0 (zero), the maximum size of the file mapping object is equal to the current size of the file that hFile identifies. /// </para> /// <para> /// An attempt to map a file with a length of 0 (zero) fails with an error code of <c>ERROR_FILE_INVALID</c>. Applications should test for files with a /// length of 0 (zero) and reject those files. /// </para> /// </param> /// <param name="lpName"> /// <para>The name of the file mapping object.</para> /// <para> /// If this parameter matches the name of an existing mapping object, the function requests access to the object with the protection that flProtect specifies. /// </para> /// <para>If this parameter is <c>NULL</c>, the file mapping object is created without a name.</para> /// <para> /// If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the <c>GetLastError</c> /// function returns <c>ERROR_INVALID_HANDLE</c>. This occurs because these objects share the same namespace. /// </para> /// <para> /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can /// contain any character except the backslash character (\). Creating a file mapping object in the global namespace from a session other than session /// zero requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel Object Namespaces. /// </para> /// <para> /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next user to log on uses /// session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal Services so that applications can support /// multiple users. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the newly created file mapping object.</para> /// <para> /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), /// and <c>GetLastError</c> returns <c>ERROR_ALREADY_EXISTS</c>. /// </para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HANDLE WINAPI CreateFileMapping( _In_ HANDLE hFile, _In_opt_ LPSECURITY_ATTRIBUTES lpAttributes, _In_ DWORD flProtect, _In_ DWORD dwMaximumSizeHigh, // _In_ DWORD dwMaximumSizeLow, _In_opt_ LPCTSTR lpName); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366537")] public static extern IntPtr CreateFileMapping([In] HFILE hFile, [In] SECURITY_ATTRIBUTES lpAttributes, MEM_PROTECTION flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName); /// <summary>Creates or opens a named or unnamed file mapping object for a specified file from a Windows Store app.</summary> /// <param name="hFile"> /// <para>A handle to the file from which to create a file mapping object.</para> /// <para> /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. It is not required, /// but it is recommended that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights. /// </para> /// <para> /// If hFile is <c>INVALID_HANDLE_VALUE</c>, the calling process must also specify a size for the file mapping object in the dwMaximumSizeHigh and /// dwMaximumSizeLow parameters. In this scenario, <c>CreateFileMappingFromApp</c> creates a file mapping object of a specified size that is backed by /// the system paging file instead of by a file in the file system. /// </para> /// </param> /// <param name="SecurityAttributes"> /// <para> /// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that determines whether a returned handle can be inherited by child processes. The /// <c>lpSecurityDescriptor</c> member of the <c>SECURITY_ATTRIBUTES</c> structure specifies a security descriptor for a new file mapping object. /// </para> /// <para> /// If SecurityAttributes is <c>NULL</c>, the handle cannot be inherited and the file mapping object gets a default security descriptor. The access /// control lists (ACL) in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. For /// more information, see File Mapping Security and Access Rights. /// </para> /// </param> /// <param name="PageProtection"> /// <para>Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection.</para> /// <para>This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>PAGE_READONLY0x02</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access violation.The file /// handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// <item> /// <term>PAGE_READWRITE0x04</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies must be created with /// the GENERIC_READ and GENERIC_WRITE access rights. /// </term> /// </item> /// <item> /// <term>PAGE_WRITECOPY0x08</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that the hFile parameter /// specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// </list> /// </para> /// <para> /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the preceding page /// protection values. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>SEC_COMMIT0x8000000</term> /// <term> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is committed rather than reserved. The system must have enough committable /// pages to hold the entire mapping. Otherwise, CreateFileMappingFromApp fails.This attribute has no effect for file mapping objects that are backed by /// executable image files or data files (the hfile parameter is a handle to a file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is /// specified, SEC_COMMIT is assumed. /// </term> /// </item> /// <item> /// <term>SEC_IMAGE_NO_EXECUTE0x11000000</term> /// <term> /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded image file will have /// no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the SEC_IMAGE_NO_EXECUTE attribute will not invoke /// driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The SEC_IMAGE_NO_EXECUTE attribute must be combined with the /// PAGE_READONLY page protection value. No other attributes are valid with SEC_IMAGE_NO_EXECUTE. /// </term> /// </item> /// <item> /// <term>SEC_LARGE_PAGES0x80000000</term> /// <term> /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile parameter is /// INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable image files or data files (the hFile /// parameter is a handle to an executable image or data file).The maximum size of the file mapping object must be a multiple of the minimum size of a /// large page returned by the GetLargePageMinimum function. If it is not, CreateFileMappingFromApp fails. When mapping a view of a file mapping object /// created with SEC_LARGE_PAGES, the base address and view size must also be multiples of the minimum large page size.SEC_LARGE_PAGES requires the /// SeLockMemoryPrivilege privilege to be enabled in the caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be specified. /// </term> /// </item> /// <item> /// <term>SEC_NOCACHE0x10000000</term> /// <term> /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_NOCACHE requires either the /// SEC_RESERVE or SEC_COMMIT attribute to be set. /// </term> /// </item> /// <item> /// <term>SEC_RESERVE0x4000000</term> /// <term> /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies that when a view of /// the file is mapped into a process address space, the entire range of pages is reserved for later use by the process rather than committed.Reserved /// pages can be committed in subsequent calls to the VirtualAlloc function. After the pages are committed, they cannot be freed or decommitted with the /// VirtualFree function.This attribute has no effect for file mapping objects that are backed by executable image files or data files (the hfile /// parameter is a handle to a file).SEC_RESERVE cannot be combined with SEC_COMMIT. /// </term> /// </item> /// <item> /// <term>SEC_WRITECOMBINE0x40000000</term> /// <term> /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_WRITECOMBINE requires either /// the SEC_RESERVE or SEC_COMMIT attribute to be set. /// </term> /// </item> /// </list> /// </para> /// </param> /// <param name="MaximumSize"> /// <para>The maximum size of the file mapping object.</para> /// <para> /// An attempt to map a file with a length of 0 (zero) fails with an error code of <c>ERROR_FILE_INVALID</c>. Applications should test for files with a /// length of 0 (zero) and reject those files. /// </para> /// </param> /// <param name="Name"> /// <para>The name of the file mapping object.</para> /// <para> /// If this parameter matches the name of an existing mapping object, the function requests access to the object with the protection that flProtect specifies. /// </para> /// <para>If this parameter is <c>NULL</c>, the file mapping object is created without a name.</para> /// <para> /// If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the <c>GetLastError</c> /// function returns <c>ERROR_INVALID_HANDLE</c>. This occurs because these objects share the same namespace. /// </para> /// <para> /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can /// contain any character except the backslash character (\). Creating a file mapping object in the global namespace from a session other than session /// zero requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel Object Namespaces. /// </para> /// <para> /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next user to log on uses /// session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal Services so that applications can support /// multiple users. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the newly created file mapping object.</para> /// <para> /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), /// and <c>GetLastError</c> returns <c>ERROR_ALREADY_EXISTS</c>. /// </para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HANDLE WINAPI CreateFileMappingFromApp( _In_ HANDLE hFile, _In_opt_ PSECURITY_ATTRIBUTES SecurityAttributes, _In_ ULONG PageProtection, _In_ ULONG64 // MaximumSize, _In_opt_ PCWSTR Name); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("MemoryApi.h", MSDNShortId = "hh994453")] public static extern IntPtr CreateFileMappingFromApp([In] HFILE hFile, [In] SECURITY_ATTRIBUTES SecurityAttributes, MEM_PROTECTION PageProtection, ulong MaximumSize, string Name); /// <summary>Creates or opens a named or unnamed file mapping object for a specified file and specifies the NUMA node for the physical memory.</summary> /// <param name="hFile"> /// <para>A handle to the file from which to create a file mapping object.</para> /// <para> /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. It is not required, /// but it is recommended that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights. /// </para> /// <para> /// If hFile is <c>INVALID_HANDLE_VALUE</c>, the calling process must also specify a size for the file mapping object in the dwMaximumSizeHigh and /// dwMaximumSizeLow parameters. In this scenario, <c>CreateFileMappingNuma</c> creates a file mapping object of a specified size that is backed by the /// system paging file instead of by a file in the file system. /// </para> /// </param> /// <param name="lpFileMappingAttributes"> /// <para> /// A pointer to a <c>SECURITY_ATTRIBUTES</c> structure that determines whether a returned handle can be inherited by child processes. The /// <c>lpSecurityDescriptor</c> member of the <c>SECURITY_ATTRIBUTES</c> structure specifies a security descriptor for a new file mapping object. /// </para> /// <para> /// If lpFileMappingAttributes is <c>NULL</c>, the handle cannot be inherited and the file mapping object gets a default security descriptor. The access /// control lists (ACL) in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. For /// more information, see File Mapping Security and Access Rights. /// </para> /// </param> /// <param name="flProtect"> /// <para>Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection.</para> /// <para>This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>PAGE_EXECUTE_READ0x20</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or execute access.The file handle that the hFile parameter specifies must be created with the /// GENERIC_READ and GENERIC_EXECUTE access rights. /// </term> /// </item> /// <item> /// <term>PAGE_EXECUTE_READWRITE0x40</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, read/write or execute access.The file handle that the hFile parameter specifies must be /// created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights. /// </term> /// </item> /// <item> /// <term>PAGE_EXECUTE_WRITECOPY0x80</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or execute access. This value is equivalent to PAGE_EXECUTE_READ.The file handle that the /// hFile parameter specifies must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.Windows Vista: This value is not available until /// Windows Vista with SP1. /// </term> /// </item> /// <item> /// <term>PAGE_READONLY0x02</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access violation.The file /// handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// <item> /// <term>PAGE_READWRITE0x04</term> /// <term> /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies must be created with /// the GENERIC_READ and GENERIC_WRITE access rights. /// </term> /// </item> /// <item> /// <term>PAGE_WRITECOPY0x08</term> /// <term> /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that the hFile parameter /// specifies must be created with the GENERIC_READ access right. /// </term> /// </item> /// </list> /// </para> /// <para> /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the preceding page /// protection values. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>SEC_COMMIT0x8000000</term> /// <term>Allocates physical storage in memory or the paging file for all pages. This is the default setting.</term> /// </item> /// <item> /// <term>SEC_IMAGE0x1000000</term> /// <term> /// Sets the file that is specified to be an executable image file.The SEC_IMAGE attribute must be combined with a page protection value such as /// PAGE_READONLY. However, this page protection value has no effect on views of the executable image file. Page protection for views of an executable /// image file is determined by the executable file itself.No other attributes are valid with SEC_IMAGE. /// </term> /// </item> /// <item> /// <term>SEC_IMAGE_NO_EXECUTE0x11000000</term> /// <term> /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded image file will have /// no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the SEC_IMAGE_NO_EXECUTE attribute will not invoke /// driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The SEC_IMAGE_NO_EXECUTE attribute must be combined with the /// PAGE_READONLY page protection value. No other attributes are valid with SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008 /// and Windows Vista: This value is not supported before Windows Server 2012 and Windows 8. /// </term> /// </item> /// <item> /// <term>SEC_LARGE_PAGES0x80000000</term> /// <term> /// Enables large pages to be used when mapping images or backing from the pagefile, but not when mapping data for regular files. Be sure to specify the /// maximum size of the file mapping object as the minimum size of a large page reported by the GetLargePageMinimum function and to enable the /// SeLockMemoryPrivilege privilege. /// </term> /// </item> /// <item> /// <term>SEC_NOCACHE0x10000000</term> /// <term> /// Sets all pages to noncachable.Applications should not use this flag except when explicitly required for a device. Using the interlocked functions /// with memory mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_NOCACHE requires either SEC_RESERVE or SEC_COMMIT to /// be set. /// </term> /// </item> /// <item> /// <term>SEC_RESERVE0x4000000</term> /// <term> /// Reserves all pages without allocating physical storage.The reserved range of pages cannot be used by any other allocation operations until the range /// of pages is released.Reserved pages can be identified in subsequent calls to the VirtualAllocExNuma function. This attribute is valid only if the /// hFile parameter is INVALID_HANDLE_VALUE (that is, a file mapping object that is backed by the system paging file). /// </term> /// </item> /// <item> /// <term>SEC_WRITECOMBINE0x40000000</term> /// <term> /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. Using the interlocked /// functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_WRITECOMBINE requires either /// the SEC_RESERVE or SEC_COMMIT attribute to be set. /// </term> /// </item> /// </list> /// </para> /// </param> /// <param name="dwMaximumSizeHigh">The high-order <c>DWORD</c> of the maximum size of the file mapping object.</param> /// <param name="dwMaximumSizeLow"> /// <para>The low-order <c>DWORD</c> of the maximum size of the file mapping object.</para> /// <para> /// If this parameter and the dwMaximumSizeHigh parameter are 0 (zero), the maximum size of the file mapping object is equal to the current size of the /// file that the hFile parameter identifies. /// </para> /// <para> /// An attempt to map a file with a length of 0 (zero) fails with an error code of <c>ERROR_FILE_INVALID</c>. Applications should test for files with a /// length of 0 (zero) and reject those files. /// </para> /// </param> /// <param name="lpName"> /// <para>The name of the file mapping object.</para> /// <para> /// If this parameter matches the name of an existing file mapping object, the function requests access to the object with the protection that the /// flProtect parameter specifies. /// </para> /// <para>If this parameter is <c>NULL</c>, the file mapping object is created without a name.</para> /// <para> /// If the lpName parameter matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails and the /// <c>GetLastError</c> function returns <c>ERROR_INVALID_HANDLE</c>. This occurs because these objects share the same namespace. /// </para> /// <para> /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can /// contain any character except the backslash character (\). Creating a file mapping object in the global namespace requires the SeCreateGlobalPrivilege /// privilege. For more information, see Kernel Object Namespaces. /// </para> /// <para> /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next user to log on uses /// session 1 (one), and so on. Kernel object names must follow the guidelines so that applications can support multiple users. /// </para> /// </param> /// <param name="nndPreferred"> /// <para>The NUMA node where the physical memory should reside.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>NUMA_NO_PREFERRED_NODE = 0xffffffff</term> /// <term>No NUMA node is preferred. This is the same as calling the CreateFileMapping function.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to the file mapping object.</para> /// <para> /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size) /// and the <c>GetLastError</c> function returns <c>ERROR_ALREADY_EXISTS</c>. /// </para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call the <c>GetLastError</c> function.</para> /// </returns> // HANDLE WINAPI CreateFileMappingNuma( _In_ HANDLE hFile, _In_opt_ LPSECURITY_ATTRIBUTES lpFileMappingAttributes, _In_ DWORD flProtect, _In_ DWORD // dwMaximumSizeHigh, _In_ DWORD dwMaximumSizeLow, _In_opt_ LPCTSTR lpName, _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366539")] public static extern SafeHFILE CreateFileMappingNuma([In] HFILE hFile, [In] SECURITY_ATTRIBUTES lpFileMappingAttributes, MEM_PROTECTION flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName, uint nndPreferred); /// <summary> /// <para>Creates a memory resource notification object.</para> /// </summary> /// <param name="NotificationType"> /// <para> /// The memory condition under which the object is to be signaled. This parameter can be one of the following values from the /// <c>MEMORY_RESOURCE_NOTIFICATION_TYPE</c> enumeration. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>LowMemoryResourceNotification0</term> /// <term>Available physical memory is running low.</term> /// </item> /// <item> /// <term>HighMemoryResourceNotification1</term> /// <term>Available physical memory is high.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a handle to a memory resource notification object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended information, call <c>GetLastError</c>.</para> /// </returns> // HANDLE WINAPI CreateMemoryResourceNotification( _In_ MEMORY_RESOURCE_NOTIFICATION_TYPE NotificationType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366541")] public static extern SafeMemoryResourceNotification CreateMemoryResourceNotification(MEMORY_RESOURCE_NOTIFICATION_TYPE NotificationType); /// <summary> /// Discards the memory contents of a range of memory pages, without decommitting the memory. The contents of discarded memory is undefined and must be /// rewritten by the application. /// </summary> /// <param name="VirtualAddress">Page-aligned starting address of the memory to discard.</param> /// <param name="Size">Size, in bytes, of the memory region to discard. Size must be an integer multiple of the system page size.</param> /// <returns>ERROR_SUCCESS if successful; a System Error Code otherwise.</returns> // DWORD WINAPI DiscardVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781432")] public static extern uint DiscardVirtualMemory(IntPtr VirtualAddress, SizeT Size); /// <summary>Fills a block of memory with a specified value.</summary> /// <param name="Destination">A pointer to the starting address of the block of memory to fill.</param> /// <param name="Length"> /// The size of the block of memory to fill, in bytes. This value must be less than the size of the Destination buffer. /// </param> /// <param name="Fill">The byte value with which to fill the memory block.</param> // void FillMemory( [out] PVOID Destination, [in] SIZE_T Length, [in] BYTE Fill); // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366561(v=vs.85).aspx [PInvokeData("WinBase.h", MSDNShortId = "aa366561")] [DllImport(Lib.Kernel32, EntryPoint = "RtlFillMemory", SetLastError = false)] public static extern void FillMemory(IntPtr Destination, SizeT Length, byte Fill); /// <summary>Writes to the disk a byte range within a mapped view of a file.</summary> /// <param name="lpBaseAddress">A pointer to the base address of the byte range to be flushed to the disk representation of the mapped file.</param> /// <param name="dwNumberOfBytesToFlush"> /// The number of bytes to be flushed. If dwNumberOfBytesToFlush is zero, the file is flushed from the base address to the end of the mapping. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI FlushViewOfFile( _In_ LPCVOID lpBaseAddress, _In_ SIZE_T dwNumberOfBytesToFlush); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366563")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FlushViewOfFile([In] IntPtr lpBaseAddress, SizeT dwNumberOfBytesToFlush); /// <summary> /// <para> /// Frees physical memory pages that are allocated previously by using <c>AllocateUserPhysicalPages</c> or <c>AllocateUserPhysicalPagesNuma</c>. If any /// of these pages are currently mapped in the Address Windowing Extensions (AWE) region, they are automatically unmapped by this call. This does not /// affect the virtual address space that is occupied by a specified Address Windowing Extensions (AWE) region. /// </para> /// <para> /// <c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>FreeUserPhysicalPages</c> is not supported for 32-bit applications. /// </para> /// </summary> /// <param name="hProcess"> /// <para>The handle to a process.</para> /// <para>The function frees memory within the virtual address space of this process.</para> /// </param> /// <param name="NumberOfPages"> /// <para>The size of the physical memory to free, in pages.</para> /// <para>On return, if the function fails, this parameter indicates the number of pages that are freed.</para> /// </param> /// <param name="UserPfnArray">A pointer to an array of page frame numbers of the allocated memory to be freed.</param> /// <returns> /// <para>If the function succeeds, the return value is <c>TRUE</c>.</para> /// <para> /// If the function fails, the return value is <c>FALSE</c>. In this case, the NumberOfPages parameter reflect how many pages have actually been /// released. To get extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // BOOL WINAPI FreeUserPhysicalPages( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366566")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeUserPhysicalPages([In] HPROCESS hProcess, ref SizeT NumberOfPages, [In] IntPtr UserPfnArray); /// <summary>Retrieves the minimum size of a large page.</summary> /// <returns> /// <para>If the processor supports large pages, the return value is the minimum size of a large page.</para> /// <para>If the processor does not support large pages, the return value is zero.</para> /// </returns> // SIZE_T WINAPI GetLargePageMinimum(void); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366568")] public static extern SizeT GetLargePageMinimum(); /// <summary>Gets the memory error handling capabilities of the system.</summary> /// <param name="Capabilities"> /// <para>A <c>PULONG</c> that receives one or more of the following flags.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEHC_PATROL_SCRUBBER_PRESENT = 1</term> /// <term>The hardware can detect and report failed memory.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI GetMemoryErrorHandlingCapabilities( _Out_ PULONG Capabilities); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691012")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetMemoryErrorHandlingCapabilities(out uint Capabilities); /// <summary>Retrieves the minimum and maximum working set sizes of the specified process.</summary> /// <param name="hProcess"> /// <para> /// A handle to the process whose working set sizes will be obtained. The handle must have the <c>PROCESS_QUERY_INFORMATION</c> or /// <c>PROCESS_QUERY_LIMITED_INFORMATION</c> access right. For more information, see Process Security and Access Rights. /// </para> /// <para><c>Windows Server 2003 and Windows XP:</c> The handle must have the <c>PROCESS_QUERY_INFORMATION</c> access right.</para> /// </param> /// <param name="lpMinimumWorkingSetSize"> /// A pointer to a variable that receives the minimum working set size of the specified process, in bytes. The virtual memory manager attempts to keep at /// least this much memory resident in the process whenever the process is active. /// </param> /// <param name="lpMaximumWorkingSetSize"> /// A pointer to a variable that receives the maximum working set size of the specified process, in bytes. The virtual memory manager attempts to keep no /// more than this much memory resident in the process whenever the process is active when memory is in short supply. /// </param> /// <param name="Flags">The flags that control the enforcement of the minimum and maximum working set sizes.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI GetProcessWorkingSetSize( _In_ HANDLE hProcess, _Out_ PSIZE_T lpMinimumWorkingSetSize, _Out_ PSIZE_T lpMaximumWorkingSetSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms683226")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetProcessWorkingSetSizeEx([In] HPROCESS hProcess, [Out] out SizeT lpMinimumWorkingSetSize, [Out] out SizeT lpMaximumWorkingSetSize, out QUOTA_LIMITS_HARDWS Flags); /// <summary>Retrieves the current size limits for the working set of the system cache.</summary> /// <param name="lpMinimumFileCacheSize"> /// A pointer to a variable that receives the minimum size of the file cache, in bytes. The virtual memory manager attempts to keep at least this much /// memory resident in the system file cache, if there is a previous call to the <c>SetSystemFileCacheSize</c> function with the /// <c>FILE_CACHE_MIN_HARD_ENABLE</c> flag. /// </param> /// <param name="lpMaximumFileCacheSize"> /// A pointer to a variable that receives the maximum size of the file cache, in bytes. The virtual memory manager enforces this limit only if there is a /// previous call to <c>SetSystemFileCacheSize</c> with the <c>FILE_CACHE_MAX_HARD_ENABLE</c> flag. /// </param> /// <param name="lpFlags"> /// <para>The flags that indicate which of the file cache limits are enabled.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_CACHE_MAX_HARD_ENABLE = 0x1</term> /// <term>The maximum size limit is enabled. If this flag is not present, this limit is disabled.</term> /// </item> /// <item> /// <term>FILE_CACHE_MIN_HARD_ENABLE = 0x4</term> /// <term>The minimum size limit is enabled. If this flag is not present, this limit is disabled.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a nonzero value.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI GetSystemFileCacheSize( _Out_ PSIZE_T lpMinimumFileCacheSize, _Out_ PSIZE_T lpMaximumFileCacheSize, _Out_ PDWORD lpFlags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa965224")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetSystemFileCacheSize(out SizeT lpMinimumFileCacheSize, out SizeT lpMaximumFileCacheSize, out FILE_CACHE_LIMITS lpFlags); /// <summary> /// <para>Retrieves the addresses of the pages that are written to in a region of virtual memory.</para> /// <para><c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>GetWriteWatch</c> is not supported for 32-bit applications.</para> /// </summary> /// <param name="dwFlags"> /// <para>Indicates whether the function resets the write-tracking state.</para> /// <para> /// To reset the write-tracking state, set this parameter to <c>WRITE_WATCH_FLAG_RESET</c>. If this parameter is 0 (zero), <c>GetWriteWatch</c> does not /// reset the write-tracking state. For more information, see the Remarks section of this topic. /// </para> /// </param> /// <param name="lpBaseAddress"> /// <para>The base address of the memory region for which to retrieve write-tracking information.</para> /// <para>This address must be in a memory region that is allocated by the <c>VirtualAlloc</c> function using <c>MEM_WRITE_WATCH</c>.</para> /// </param> /// <param name="dwRegionSize">The size of the memory region for which to retrieve write-tracking information, in bytes.</param> /// <param name="lpAddresses"> /// <para>A pointer to a buffer that receives an array of page addresses in the memory region.</para> /// <para>The addresses indicate the pages that have been written to since the region has been allocated or the write-tracking state has been reset.</para> /// </param> /// <param name="lpdwCount"> /// <para>On input, this variable indicates the size of the lpAddresses array, in array elements.</para> /// <para>On output, the variable receives the number of page addresses that are returned in the array.</para> /// </param> /// <param name="lpdwGranularity">A pointer to a variable that receives the page size, in bytes.</param> /// <returns> /// <para>If the function succeeds, the return value is 0 (zero).</para> /// <para>If the function fails, the return value is a nonzero value.</para> /// </returns> // UINT WINAPI GetWriteWatch( _In_ DWORD dwFlags, _In_ PVOID lpBaseAddress, _In_ SIZE_T dwRegionSize, _Out_ PVOID *lpAddresses, _Inout_ PULONG_PTR // lpdwCount, _Out_ PULONG lpdwGranularity); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366573")] public static extern uint GetWriteWatch(WRITE_WATCH dwFlags, [In] IntPtr lpBaseAddress, SizeT dwRegionSize, out IntPtr lpAddresses, ref UIntPtr lpdwCount, [Out] out uint lpdwGranularity); /// <summary> /// <para>Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region.</para> /// <para>To perform batch mapping and unmapping of multiple regions, use the <c>MapUserPhysicalPagesScatter</c> function.</para> /// <para> /// <c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>MapUserPhysicalPages</c> is not supported for 32-bit applications. /// </para> /// </summary> /// <param name="lpAddress"> /// <para>A pointer to the starting address of the region of memory to remap.</para> /// <para> /// The value of lpAddress must be within the address range that the <c>VirtualAlloc</c> function returns when the Address Windowing Extensions (AWE) /// region is allocated. /// </para> /// </param> /// <param name="NumberOfPages"> /// <para>The size of the physical memory and virtual address space for which to establish translations, in pages.</para> /// <para>The virtual address range is contiguous starting at lpAddress. The physical frames are specified by the UserPfnArray.</para> /// <para>The total number of pages cannot extend from the starting address beyond the end of the range that is specified in <c>AllocateUserPhysicalPages</c>.</para> /// </param> /// <param name="UserPfnArray"> /// <para>A pointer to an array of physical page frame numbers.</para> /// <para> /// These frames are mapped by the argument lpAddress on return from this function. The size of the memory that is allocated should be at least the /// NumberOfPages times the size of the data type <c>ULONG_PTR</c>. /// </para> /// <para> /// Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in the buffer is not /// useful to an application. /// </para> /// <para> /// If this parameter is <c>NULL</c>, the specified address range is unmapped. Also, the specified physical pages are not freed, and you must call /// <c>FreeUserPhysicalPages</c> to free them. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is <c>TRUE</c>.</para> /// <para> /// If the function fails, the return value is <c>FALSE</c> and no mapping is done—partial or otherwise. To get extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // BOOL WINAPI MapUserPhysicalPages( _In_ PVOID lpAddress, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366753")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool MapUserPhysicalPages([In] IntPtr lpAddress, ref SizeT NumberOfPages, [In] IntPtr UserPfnArray); /// <summary> /// <para>Maps a view of a file mapping into the address space of a calling process.</para> /// <para>To specify a suggested base address for the view, use the <c>MapViewOfFileEx</c> function. However, this practice is not recommended.</para> /// </summary> /// <param name="hFileMappingObject"> /// A handle to a file mapping object. The <c>CreateFileMapping</c> and <c>OpenFileMapping</c> functions return this handle. /// </param> /// <param name="dwDesiredAccess"> /// <para>The type of access to a file mapping object, which determines the protection of the pages. This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_MAP_ALL_ACCESS</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection.When /// used with the MapViewOfFile function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// <item> /// <term>FILE_MAP_COPY</term> /// <term> /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, PAGE_WRITECOPY, /// PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection.When a process writes to a copy-on-write page, the system copies the /// original page to a new page that is private to the process. The new page is backed by the paging file. The protection of the new page changes from /// copy-on-write to read/write.When copy-on-write access is specified, the system and process commit charge taken is for the entire view because the /// calling process can potentially write to every page in the view, making all pages private. The contents of the new page are never written back to the /// original file and are lost when the view is unmapped. /// </term> /// </item> /// <item> /// <term>FILE_MAP_READ</term> /// <term> /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping object must have been /// created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// </term> /// </item> /// <item> /// <term>FILE_MAP_WRITE</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection.When /// used with MapViewOfFile, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// </list> /// </para> /// <para>Each of the preceding values can be combined with the following value.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_MAP_EXECUTE</term> /// <term> /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created with PAGE_EXECUTE_READ, /// PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection.Windows Server 2003 and Windows XP: This value is available starting with Windows XP /// with SP2 and Windows Server 2003 with SP1. /// </term> /// </item> /// </list> /// </para> /// <para> /// For file mapping objects created with the <c>SEC_IMAGE</c> attribute, the dwDesiredAccess parameter has no effect and should be set to any valid /// value such as <c>FILE_MAP_READ</c>. /// </para> /// <para>For more information about access to file mapping objects, see File Mapping Security and Access Rights.</para> /// </param> /// <param name="dwFileOffsetHigh">A high-order <c>DWORD</c> of the file offset where the view begins.</param> /// <param name="dwFileOffsetLow"> /// A low-order <c>DWORD</c> of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within the /// file mapping. They must also match the memory allocation granularity of the system. That is, the offset must be a multiple of the allocation /// granularity. To obtain the memory allocation granularity of the system, use the <c>GetSystemInfo</c> function, which fills in the members of a /// <c>SYSTEM_INFO</c> structure. /// </param> /// <param name="dwNumberOfBytesToMap"> /// The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by <c>CreateFileMapping</c>. If this /// parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. /// </param> /// <returns> /// <para>If the function succeeds, the return value is the starting address of the mapped view.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI MapViewOfFile( _In_ HANDLE hFileMappingObject, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFileOffsetHigh, _In_ DWORD dwFileOffsetLow, _In_ // SIZE_T dwNumberOfBytesToMap); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366761")] public static extern IntPtr MapViewOfFile([In] HFILE hFileMappingObject, FILE_MAP dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap); /// <summary> /// <para> /// Maps a view of a file mapping into the address space of a calling process. A caller can optionally specify a suggested base memory address for the view. /// </para> /// <para>To specify the NUMA node for the physical memory, see <c>MapViewOfFileExNuma</c>.</para> /// </summary> /// <param name="hFileMappingObject"> /// A handle to a file mapping object. The <c>CreateFileMapping</c> and <c>OpenFileMapping</c> functions return this handle. /// </param> /// <param name="dwDesiredAccess"> /// <para> /// The type of access to a file mapping object, which determines the page protection of the pages. This parameter can be one of the following values. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_MAP_ALL_ACCESS</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection.When /// used with the MapViewOfFileEx function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// <item> /// <term>FILE_MAP_COPY</term> /// <term> /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, PAGE_WRITECOPY, /// PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection.When a process writes to a copy-on-write page, the system copies the /// original page to a new page that is private to the process. The new page is backed by the paging file. The protection of the new page changes from /// copy-on-write to read/write.When copy-on-write access is specified, the system and process commit charge taken is for the entire view because the /// calling process can potentially write to every page in the view, making all pages private. The contents of the new page are never written back to the /// original file and are lost when the view is unmapped. /// </term> /// </item> /// <item> /// <term>FILE_MAP_READ</term> /// <term> /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping object must have been /// created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// </term> /// </item> /// <item> /// <term>FILE_MAP_WRITE</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection.When /// used with MapViewOfFileEx, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// </list> /// </para> /// <para>Each of the preceding values can be combined with the following value.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_MAP_EXECUTE</term> /// <term> /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created with PAGE_EXECUTE_READ, /// PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection.Windows Server 2003 and Windows XP: This value is available starting with Windows XP /// with SP2 and Windows Server 2003 with SP1. /// </term> /// </item> /// </list> /// </para> /// <para> /// For file mapping objects created with the <c>SEC_IMAGE</c> attribute, the dwDesiredAccess parameter has no effect and should be set to any valid /// value such as <c>FILE_MAP_READ</c>. /// </para> /// <para>For more information about access to file mapping objects, see File Mapping Security and Access Rights.</para> /// </param> /// <param name="dwFileOffsetHigh">The high-order <c>DWORD</c> of the file offset where the view is to begin.</param> /// <param name="dwFileOffsetLow"> /// The low-order <c>DWORD</c> of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within /// the file mapping. They must also match the memory allocation granularity of the system. That is, the offset must be a multiple of the allocation /// granularity. To obtain the memory allocation granularity of the system, use the <c>GetSystemInfo</c> function, which fills in the members of a /// <c>SYSTEM_INFO</c> structure. /// </param> /// <param name="dwNumberOfBytesToMap"> /// The number of bytes of a file mapping to map to a view. All bytes must be within the maximum size specified by <c>CreateFileMapping</c>. If this /// parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. /// </param> /// <param name="lpBaseAddress"> /// <para> /// A pointer to the memory address in the calling process address space where mapping begins. This must be a multiple of the system's memory allocation /// granularity, or the function fails. To determine the memory allocation granularity of the system, use the <c>GetSystemInfo</c> function. If there is /// not enough address space at the specified address, the function fails. /// </para> /// <para> /// If lpBaseAddress is <c>NULL</c>, the operating system chooses the mapping address. In this scenario, the function is equivalent to the /// <c>MapViewOfFile</c> function. /// </para> /// <para> /// While it is possible to specify an address that is safe now (not used by the operating system), there is no guarantee that the address will remain /// safe over time. Therefore, it is better to let the operating system choose the address. In this case, you would not store pointers in the memory /// mapped file, you would store offsets from the base of the file mapping so that the mapping can be used at any address. /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is the starting address of the mapped view.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI MapViewOfFileEx( _In_ HANDLE hFileMappingObject, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFileOffsetHigh, _In_ DWORD dwFileOffsetLow, // _In_ SIZE_T dwNumberOfBytesToMap, _In_opt_ LPVOID lpBaseAddress); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366763")] public static extern IntPtr MapViewOfFileEx([In] HFILE hFileMappingObject, FILE_MAP dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap, [In] IntPtr lpBaseAddress); /// <summary>Maps a view of a file mapping into the address space of a calling Windows Store app.</summary> /// <param name="hFileMappingObject">A handle to a file mapping object. The <c>CreateFileMappingFromApp</c> function returns this handle.</param> /// <param name="DesiredAccess"> /// <para>The type of access to a file mapping object, which determines the protection of the pages. This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_MAP_ALL_ACCESS</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE protection.When used with the /// MapViewOfFileFromApp function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// <item> /// <term>FILE_MAP_COPY</term> /// <term> /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, PAGE_WRITECOPY, or /// PAGE_READWRITE protection.When a process writes to a copy-on-write page, the system copies the original page to a new page that is private to the /// process. The new page is backed by the paging file. The protection of the new page changes from copy-on-write to read/write.When copy-on-write access /// is specified, the system and process commit charge taken is for the entire view because the calling process can potentially write to every page in /// the view, making all pages private. The contents of the new page are never written back to the original file and are lost when the view is unmapped. /// </term> /// </item> /// <item> /// <term>FILE_MAP_READ</term> /// <term> /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping object must have been /// created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// </term> /// </item> /// <item> /// <term>FILE_MAP_WRITE</term> /// <term> /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE protection.When used with /// MapViewOfFileFromApp, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. /// </term> /// </item> /// </list> /// </para> /// <para>For more information about access to file mapping objects, see File Mapping Security and Access Rights.</para> /// </param> /// <param name="FileOffset"> /// The file offset where the view is to begin. The offset must specify an offset within the file mapping. They must also match the memory allocation /// granularity of the system. That is, the offset must be a multiple of the allocation granularity. To obtain the memory allocation granularity of the /// system, use the <c>GetSystemInfo</c> function, which fills in the members of a <c>SYSTEM_INFO</c> structure. /// </param> /// <param name="NumberOfBytesToMap"> /// The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by <c>CreateFileMappingFromApp</c>. If /// this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. /// </param> /// <returns> /// <para>If the function succeeds, the return value is the starting address of the mapped view.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // PVOID WINAPI MapViewOfFileFromApp( _In_ HANDLE hFileMappingObject, _In_ ULONG DesiredAccess, _In_ ULONG64 FileOffset, _In_ SIZE_T NumberOfBytesToMap); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "hh994454")] public static extern IntPtr MapViewOfFileFromApp([In] HFILE hFileMappingObject, FILE_MAP DesiredAccess, ulong FileOffset, SizeT NumberOfBytesToMap); /// <summary>Maps a view of a file or a pagefile-backed section into the address space of the specified process.</summary> /// <param name="FileMappingHandle">A <c>HANDLE</c> to a section that is to be mapped into the address space of the specified process.</param> /// <param name="ProcessHandle">A <c>HANDLE</c> to a process into which the section will be mapped.</param> /// <param name="Offset">The offset from the beginning of the section. This must be 64k aligned.</param> /// <param name="BaseAddress"> /// The desired base address of the view. The address is rounded down to the nearest 64k boundary. If this parameter is <c>NULL</c>, the system picks the /// base address. /// </param> /// <param name="ViewSize">The number of bytes to map. A value of zero (0) specifies that the entire section is to be mapped.</param> /// <param name="AllocationType">The type of allocation. This parameter can be zero (0) or one of the following constant values:</param> /// <param name="PageProtection">The desired page protection.</param> /// <param name="PreferredNode">The preferred NUMA node for this memory.</param> /// <returns> /// Returns the base address of the mapped view, if successful. Otherwise, returns <c>NULL</c> and extended error status is available using <c>GetLastError</c>. /// </returns> // PVOID WINAPI MapViewOfFileNuma2( _In_ HANDLE FileMappingHandle, _In_ HANDLE ProcessHandle, _In_ ULONG64 Offset, _In_opt_ PVOID BaseAddress, _In_ // SIZE_T ViewSize, _In_ ULONG AllocationType, _In_ ULONG PageProtection, _In_ ULONG PreferredNode); [DllImport("Api-ms-win-core-memory-l1-1-5.dll", SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "mt492558")] public static extern IntPtr MapViewOfFileNuma2([In] HFILE FileMappingHandle, [In] HPROCESS ProcessHandle, ulong Offset, IntPtr BaseAddress, SizeT ViewSize, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, uint PreferredNode); /// <summary> /// <para> /// Indicates that the data contained in a range of memory pages is no longer needed by the application and can be discarded by the system if necessary. /// </para> /// <para>The specified pages will be marked as inaccessible, removed from the process working set, and will not be written to the paging file.</para> /// <para>To later reclaim offered pages, call <c>ReclaimVirtualMemory</c>.</para> /// </summary> /// <param name="VirtualAddress">Page-aligned starting address of the memory to offer.</param> /// <param name="Size">Size, in bytes, of the memory region to offer. Size must be an integer multiple of the system page size.</param> /// <param name="Priority"> /// <para> /// Priority indicates how important the offered memory is to the application. A higher priority increases the probability that the offered memory can be /// reclaimed intact when calling <c>ReclaimVirtualMemory</c>. The system typically discards lower priority memory before discarding higher priority /// memory. Priority must be one of the following values. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>VMOfferPriorityVeryLow0x00001000</term> /// <term>The offered memory is very low priority, and should be the first discarded.</term> /// </item> /// <item> /// <term>VMOfferPriorityLow0x00002000</term> /// <term>The offered memory is low priority.</term> /// </item> /// <item> /// <term>VMOfferPriorityBelowNormal0x00002000</term> /// <term>The offered memory is below normal priority.</term> /// </item> /// <item> /// <term>VMOfferPriorityNormal0x00002000</term> /// <term>The offered memory is of normal priority to the application, and should be the last discarded.</term> /// </item> /// </list> /// </para> /// </param> /// <returns>ERROR_SUCCESS if successful; a System Error Code otherwise.</returns> // DWORD WINAPI OfferVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size, _In_ OFFER_PRIORITY Priority); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781436")] public static extern uint OfferVirtualMemory(IntPtr VirtualAddress, SizeT Size, OFFER_PRIORITY Priority); /// <summary>Opens a named file mapping object.</summary> /// <param name="dwDesiredAccess"> /// The access to the file mapping object. This access is checked against any security descriptor on the target file mapping object. For a list of /// values, see File Mapping Security and Access Rights. /// </param> /// <param name="bInheritHandle"> /// If this parameter is <c>TRUE</c>, a process created by the <c>CreateProcess</c> function can inherit the handle; otherwise, the handle cannot be inherited. /// </param> /// <param name="lpName"> /// The name of the file mapping object to be opened. If there is an open handle to a file mapping object by this name and the security descriptor on the /// mapping object does not conflict with the dwDesiredAccess parameter, the open operation succeeds. The name can have a "Global\" or "Local\" prefix to /// explicitly open an object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). /// For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. The first user to log on /// uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so /// that applications can support multiple users. /// </param> /// <returns> /// <para>If the function succeeds, the return value is an open handle to the specified file mapping object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HANDLE WINAPI OpenFileMapping( _In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandle, _In_ LPCTSTR lpName); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366791")] public static extern SafeHFILE OpenFileMapping(FILE_MAP dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName); /// <summary>Opens a named file mapping object.</summary> /// <param name="DesiredAccess"> /// The access to the file mapping object. This access is checked against any security descriptor on the target file mapping object. For a list of /// values, see File Mapping Security and Access Rights. You can only open the file mapping object for <c>FILE_MAP_EXECUTE</c> access if your app has the /// <c>codeGeneration</c> capability. /// </param> /// <param name="InheritHandle"> /// If this parameter is <c>TRUE</c>, a process created by the <c>CreateProcess</c> function can inherit the handle; otherwise, the handle cannot be inherited. /// </param> /// <param name="Name"> /// The name of the file mapping object to be opened. If there is an open handle to a file mapping object by this name and the security descriptor on the /// mapping object does not conflict with the DesiredAccess parameter, the open operation succeeds. The name can have a "Global\" or "Local\" prefix to /// explicitly open an object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). /// For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. The first user to log on /// uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so /// that applications can support multiple users. /// </param> /// <returns> /// <para>If the function succeeds, the return value is an open handle to the specified file mapping object.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // HANDLE WINAPI OpenFileMappingFromApp( _In_ ULONG DesiredAccess, _In_ BOOL InheritHandle, _In_ PCWSTR Name); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169844")] public static extern SafeHFILE OpenFileMappingFromApp(FILE_MAP DesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool InheritHandle, string Name); /// <summary>Provides an efficient mechanism to bring into memory potentially discontiguous virtual address ranges in a process address space.</summary> /// <param name="hProcess"> /// Handle to the process whose virtual address ranges are to be prefetched. Use the <c>GetCurrentProcess</c> function to use the current process. /// </param> /// <param name="NumberOfEntries">Number of entries in the array pointed to by the VirtualAddresses parameter.</param> /// <param name="VirtualAddresses"> /// Pointer to an array of <c>WIN32_MEMORY_RANGE_ENTRY</c> structures which each specify a virtual address range to be prefetched. The virtual address /// ranges may cover any part of the process address space accessible by the target process. /// </param> /// <param name="Flags">Reserved. Must be 0.</param> /// <returns> /// <para>If the function succeeds, the return value is a nonzero value.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI PrefetchVirtualMemory( _In_ HANDLE hProcess, _In_ ULONG_PTR NumberOfEntries, _In_ PWIN32_MEMORY_RANGE_ENTRY VirtualAddresses, _In_ ULONG Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh780543")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrefetchVirtualMemory(HPROCESS hProcess, UIntPtr NumberOfEntries, IntPtr VirtualAddresses, uint Flags); /// <summary>Retrieves the state of the specified memory resource object.</summary> /// <param name="ResourceNotificationHandle"> /// A handle to a memory resource notification object. The <c>CreateMemoryResourceNotification</c> function returns this handle. /// </param> /// <param name="ResourceState"> /// The memory pointed to by this parameter receives the state of the memory resource notification object. The value of this parameter is set to /// <c>TRUE</c> if the specified memory condition exists, and <c>FALSE</c> if the specified memory condition does not exist. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. For more error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI QueryMemoryResourceNotification( _In_ HANDLE ResourceNotificationHandle, _Out_ PBOOL ResourceState); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366799")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool QueryMemoryResourceNotification([In] SafeMemoryResourceNotification ResourceNotificationHandle, [Out, MarshalAs(UnmanagedType.Bool)] out bool ResourceState); /// <summary> /// The <c>QueryVirtualMemoryInformation</c> function returns information about a page or a set of pages within the virtual address space of the /// specified process. /// </summary> /// <param name="Process">A handle for the process in whose context the pages to be queried reside.</param> /// <param name="VirtualAddress">The address of the region of pages to be queried. This value is rounded down to the next host-page-address boundary.</param> /// <param name="MemoryInformationClass">The memory information class about which to retrieve information. The only supported value is <c>MemoryRegionInfo</c>.</param> /// <param name="MemoryInformation"> /// <para>A pointer to a buffer that receives the specified information.</para> /// <para> /// If the MemoryInformationClass parameter has a value of <c>MemoryRegionInfo</c>, this parameter must point to a <c>WIN32_MEMORY_REGION_INFORMATION</c> structure. /// </para> /// </param> /// <param name="MemoryInformationSize">Specifies the length in bytes of the memory information buffer.</param> /// <param name="ReturnSize">An optional pointer which, if specified, receives the number of bytes placed in the memory information buffer.</param> /// <returns>Returns <c>TRUE</c> on success. Returns <c>FALSE</c> for failure. To get extended error information, call <c>GetLastError</c>.</returns> // BOOL WINAPI QueryVirtualMemoryInformation( _In_ HANDLE Process, _In_ const VOID *VirtualAddress, _In_ WIN32_MEMORY_INFORMATION_CLASS // MemoryInformationClass, _Out_ _writes_bytes_(MemoryInformationSize) PVOID MemoryInformation, _In_ SIZE_T MemoryInformationSize, _Out_opt_ PSIZE_T ReturnSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt845761")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool QueryVirtualMemoryInformation([In] HPROCESS Process, IntPtr VirtualAddress, WIN32_MEMORY_INFORMATION_CLASS MemoryInformationClass, IntPtr MemoryInformation, SizeT MemoryInformationSize, out SizeT ReturnSize); /// <summary>Reads data from an area of memory in a specified process. The entire area to be read must be accessible or the operation fails.</summary> /// <param name="hProcess">A handle to the process with memory that is being read. The handle must have PROCESS_VM_READ access to the process.</param> /// <param name="lpBaseAddress"> /// A pointer to the base address in the specified process from which to read. Before any data transfer occurs, the system verifies that all data in the /// base address and memory of the specified size is accessible for read access, and if it is not accessible the function fails. /// </param> /// <param name="lpBuffer">A pointer to a buffer that receives the contents from the address space of the specified process.</param> /// <param name="nSize">The number of bytes to be read from the specified process.</param> /// <param name="lpNumberOfBytesRead"> /// A pointer to a variable that receives the number of bytes transferred into the specified buffer. If lpNumberOfBytesRead is <c>NULL</c>, the parameter /// is ignored. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// <para>The function fails if the requested read operation crosses into an area of the process that is inaccessible.</para> /// </returns> // BOOL WINAPI ReadProcessMemory( _In_ HANDLE hProcess, _In_ LPCVOID lpBaseAddress, _Out_ LPVOID lpBuffer, _In_ SIZE_T nSize, _Out_ SIZE_T *lpNumberOfBytesRead); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680553")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, IntPtr lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesRead); /// <summary> /// <para>Reclaims a range of memory pages that were offered to the system with <c>OfferVirtualMemory</c>.</para> /// <para> /// If the offered memory has been discarded, the contents of the memory region is undefined and must be rewritten by the application. If the offered /// memory has not been discarded, it is reclaimed intact. /// </para> /// </summary> /// <param name="VirtualAddress">Page-aligned starting address of the memory to reclaim.</param> /// <param name="Size">Size, in bytes, of the memory region to reclaim. Size must be an integer multiple of the system page size.</param> /// <returns> /// <para>Returns ERROR_SUCCESS if successful and the memory was reclaimed intact.</para> /// <para> /// Returns ERROR_BUSY if successful but the memory was discarded and must be rewritten by the application. In this case, the contents of the memory /// region is undefined. /// </para> /// <para>Returns a System Error Code otherwise.</para> /// </returns> // DWORD WINAPI ReclaimVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781437")] public static extern uint ReclaimVirtualMemory(IntPtr VirtualAddress, SizeT Size); /// <summary> /// Registers a bad memory notification that is called when one or more bad memory pages are detected and the system cannot remove at least one of them /// (for example if the pages contains modified data that has not yet been written to the pagefile.) /// </summary> /// <param name="Callback">A pointer to the application-defined BadMemoryCallbackRoutine function to register.</param> /// <returns> /// Registration handle that represents the callback notification. Can be passed to the <c>UnregisterBadMemoryNotification</c> function when no longer needed. /// </returns> // PVOID WINAPI RegisterBadMemoryNotification( _In_ PBAD_MEMORY_CALLBACK_ROUTINE Callback); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691013")] public static extern IntPtr RegisterBadMemoryNotification(PBAD_MEMORY_CALLBACK_ROUTINE Callback); /// <summary> /// <para> /// Resets the write-tracking state for a region of virtual memory. Subsequent calls to the <c>GetWriteWatch</c> function only report pages that are /// written to since the reset operation. /// </para> /// <para><c>64-bit Windows on Itanium-based systems:</c> Due to the difference in page sizes, <c>ResetWriteWatch</c> is not supported for 32-bit applications.</para> /// </summary> /// <param name="lpBaseAddress"> /// <para>A pointer to the base address of the memory region for which to reset the write-tracking state.</para> /// <para>This address must be in a memory region that is allocated by the <c>VirtualAlloc</c> function with <c>MEM_WRITE_WATCH</c>.</para> /// </param> /// <param name="dwRegionSize">The size of the memory region for which to reset the write-tracking information, in bytes.</param> /// <returns> /// <para>If the function succeeds, the return value is 0 (zero).</para> /// <para>If the function fails, the return value is a nonzero value.</para> /// </returns> // UINT WINAPI ResetWriteWatch( _In_ LPVOID lpBaseAddress, _In_ SIZE_T dwRegionSize); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366874")] public static extern uint ResetWriteWatch([In] IntPtr lpBaseAddress, SizeT dwRegionSize); /// <summary> /// <para> /// [Some information relates to pre-released product which may be substantially modified before it's commercially released. Microsoft makes no /// warranties, express or implied, with respect to the information provided here.] /// </para> /// <para> /// Provides CFG with a list of valid indirect call targets and specifies whether they should be marked valid or not. The valid call target information /// is provided as a list of offsets relative to a virtual memory range(start and size of the range). The call targets specified should be 16-byte /// aligned and in ascendingorder. /// </para> /// </summary> /// <param name="hProcess">The handle to the target process.</param> /// <param name="VirtualAddress">The start of the virtual memory region whose call targets are being marked valid.</param> /// <param name="RegionSize">The size of the virtual memory region.</param> /// <param name="NumberOfOffsets">The number of offsets relative to the virtual memory ranges.</param> /// <param name="OffsetInformation">A list of offsets and flags relative to the virtual memory ranges.</param> /// <returns><c>TRUE</c> if the operation was successful; otherwise, <c>FALSE</c>. To retrieve error values for this function, call <c>GetLastError</c>.</returns> // WINAPI SetProcessValidCallTargets( _In_ HANDLE hProcess, _In_ PVOID VirtualAddress, _In_ SIZE_T RegionSize, _In_ ULONG NumberOfOffsets, _Inout_ // PCFG_CALL_TARGET_INFO OffsetInformation); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn934202")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetProcessValidCallTargets(HPROCESS hProcess, IntPtr VirtualAddress, SizeT RegionSize, uint NumberOfOffsets, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] CFG_CALL_TARGET_INFO[] OffsetInformation); /// <summary>Sets the minimum and maximum working set sizes for the specified process.</summary> /// <param name="hProcess"> /// <para>A handle to the process whose working set sizes is to be set.</para> /// <para>The handle must have <c>PROCESS_SET_QUOTA</c> access rights. For more information, see Process Security and Access Rights.</para> /// </param> /// <param name="dwMinimumWorkingSetSize"> /// <para> /// The minimum working set size for the process, in bytes. The virtual memory manager attempts to keep at least this much memory resident in the process /// whenever the process is active. /// </para> /// <para> /// This parameter must be greater than zero but less than or equal to the maximum working set size. The default size is 50 pages (for example, this is /// 204,800 bytes on systems with a 4K page size). If the value is greater than zero but less than 20 pages, the minimum value is set to 20 pages. /// </para> /// <para> /// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( <c>SIZE_T</c>)–1, the function removes as many pages as possible from /// the working set of the specified process. /// </para> /// </param> /// <param name="dwMaximumWorkingSetSize"> /// <para> /// The maximum working set size for the process, in bytes. The virtual memory manager attempts to keep no more than this much memory resident in the /// process whenever the process is active and available memory is low. /// </para> /// <para> /// This parameter must be greater than or equal to 13 pages (for example, 53,248 on systems with a 4K page size), and less than the system-wide maximum /// (number of available pages minus 512 pages). The default size is 345 pages (for example, this is 1,413,120 bytes on systems with a 4K page size). /// </para> /// <para> /// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( <c>SIZE_T</c>)–1, the function removes as many pages as possible from /// the working set of the specified process. For details, see Remarks. /// </para> /// </param> /// <param name="Flags"> /// <para>The flags that control the enforcement of the minimum and maximum working set sizes.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>QUOTA_LIMITS_HARDWS_MIN_DISABLE0x00000002</term> /// <term>The working set may fall below the minimum working set limit if memory demands are high.This flag cannot be used with QUOTA_LIMITS_HARDWS_MIN_ENABLE.</term> /// </item> /// <item> /// <term>QUOTA_LIMITS_HARDWS_MIN_ENABLE0x00000001</term> /// <term>The working set will not fall below the minimum working set limit.This flag cannot be used with QUOTA_LIMITS_HARDWS_MIN_DISABLE.</term> /// </item> /// <item> /// <term>QUOTA_LIMITS_HARDWS_MAX_DISABLE0x00000008</term> /// <term>The working set may exceed the maximum working set limit if there is abundant memory.This flag cannot be used with QUOTA_LIMITS_HARDWS_MAX_ENABLE.</term> /// </item> /// <item> /// <term>QUOTA_LIMITS_HARDWS_MAX_ENABLE0x00000004</term> /// <term>The working set will not exceed the maximum working set limit.This flag cannot be used with QUOTA_LIMITS_HARDWS_MAX_DISABLE.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function is succeeds, the return value is nonzero.</para> /// <para> /// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. If the function fails, the return value /// is zero. To get extended error information, call <c>GetLastError</c>. /// </para> /// </returns> // BOOL WINAPI SetProcessWorkingSetSizeEx( _In_ HANDLE hProcess, _In_ SIZE_T dwMinimumWorkingSetSize, _In_ SIZE_T dwMaximumWorkingSetSize, _In_ DWORD Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms686237")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetProcessWorkingSetSizeEx([In] HPROCESS hProcess, SizeT dwMinimumWorkingSetSize, SizeT dwMaximumWorkingSetSize, QUOTA_LIMITS_HARDWS Flags); /// <summary>Limits the size of the working set for the file system cache.</summary> /// <param name="MinimumFileCacheSize"> /// <para> /// The minimum size of the file cache, in bytes. The virtual memory manager attempts to keep at least this much memory resident in the system file cache. /// </para> /// <para>To flush the cache, specify .</para> /// </param> /// <param name="MaximumFileCacheSize"> /// <para> /// The maximum size of the file cache, in bytes. The virtual memory manager enforces this limit only if this call or a previous call to /// <c>SetSystemFileCacheSize</c> specifies <c>FILE_CACHE_MAX_HARD_ENABLE</c>. /// </para> /// <para>To flush the cache, specify .</para> /// </param> /// <param name="Flags"> /// <para> /// The flags that enable or disable the file cache limits. If this parameter is 0 (zero), the size limits retain the current setting, which is either /// disabled or enabled. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>FILE_CACHE_MAX_HARD_DISABLE0x2</term> /// <term>Disable the maximum size limit.The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive.</term> /// </item> /// <item> /// <term>FILE_CACHE_MAX_HARD_ENABLE0x1</term> /// <term>Enable the maximum size limit.The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive.</term> /// </item> /// <item> /// <term>FILE_CACHE_MIN_HARD_DISABLE0x8</term> /// <term>Disable the minimum size limit.The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive.</term> /// </item> /// <item> /// <term>FILE_CACHE_MIN_HARD_ENABLE0x4</term> /// <term>Enable the minimum size limit.The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive.</term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a nonzero value.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI SetSystemFileCacheSize( _In_ SIZE_T MinimumFileCacheSize, _In_ SIZE_T MaximumFileCacheSize, _In_ DWORD Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa965240")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetSystemFileCacheSize(SizeT MinimumFileCacheSize, SizeT MaximumFileCacheSize, FILE_CACHE_LIMITS Flags); /// <summary>Unmaps a mapped view of a file from the calling process's address space.</summary> /// <param name="lpBaseAddress"> /// A pointer to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value returned by a previous /// call to the <c>MapViewOfFile</c> or <c>MapViewOfFileEx</c> function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI UnmapViewOfFile( _In_ LPCVOID lpBaseAddress); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366882")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile([In] IntPtr lpBaseAddress); /// <summary>Unmaps a previously mapped view of a file or a pagefile-backed section.</summary> /// <param name="ProcessHandle">A HANDLE to the process from which the section will be unmapped.</param> /// <param name="BaseAddress"> /// The base address of a previously mapped view that is to be unmapped. This value must be identical to the value returned by a previous call to MapViewOfFile2. /// </param> /// <param name="UnmapFlags"> /// MEM_UNMAP_WITH_TRANSIENT_BOOST (1) or zero (0). MEM_UNMAP_WITH_TRANSIENT_BOOST should be used if the pages backing this view should be temporarily /// boosted (with automatic short term decay) because another thread will access them shortly. /// </param> /// <returns></returns> [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt492559")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile2([In] HPROCESS ProcessHandle, IntPtr BaseAddress, uint UnmapFlags); /// <summary>This is an extended version of UnmapViewOfFile that takes an additional flags parameter.</summary> /// <param name="BaseAddress"> /// A pointer to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value returned by a previous /// call to the MapViewOfFile or MapViewOfFileEx function. /// </param> /// <param name="UnmapFlags"> /// The only supported flag is MEM_UNMAP_WITH_TRANSIENT_BOOST (0x1), which specifies that the priority of the pages being unmapped should be temporarily /// boosted because the caller expects that these pages will be accessed again shortly. For more information about memory priorities, see the /// SetThreadInformation(ThreadMemoryPriority) function. /// </param> /// <returns> /// <para>If the function succeeds, the return value is a nonzero value.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt670639")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFileEx(IntPtr BaseAddress, uint UnmapFlags); /// <summary>Closes the specified bad memory notification handle.</summary> /// <param name="RegistrationHandle">Registration handle returned from the <c>RegisterBadMemoryNotification</c> function.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI UnregisterBadMemoryNotification( _In_ PVOID RegistrationHandle); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691014")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnregisterBadMemoryNotification(IntPtr RegistrationHandle); /// <summary> /// <para> /// Reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. Memory allocated by this function /// is automatically initialized to zero. /// </para> /// <para>To allocate memory in the address space of another process, use the <c>VirtualAllocEx</c> function.</para> /// </summary> /// <param name="lpAddress"> /// <para> /// The starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the nearest multiple of the /// allocation granularity. If the memory is already reserved and is being committed, the address is rounded down to the next page boundary. To determine /// the size of a page and the allocation granularity on the host computer, use the <c>GetSystemInfo</c> function. If this parameter is <c>NULL</c>, the /// system determines where to allocate the region. /// </para> /// <para> /// If this address is within an enclave that you have not initialized by calling <c>InitializeEnclave</c>, <c>VirtualAlloc</c> allocates a page of zeros /// for the enclave at that address. The page must be previously uncommitted, and will not be measured with the EEXTEND instruction of the Intel Software /// Guard Extensions programming model. /// </para> /// <para>If the address in within an enclave that you initialized, then the allocation operation fails with the <c>ERROR_INVALID_ADDRESS</c> error.</para> /// </param> /// <param name="dwSize"> /// The size of the region, in bytes. If the lpAddress parameter is <c>NULL</c>, this value is rounded up to the next page boundary. Otherwise, the /// allocated pages include all pages containing one or more bytes in the range from lpAddress to lpAddress+dwSize. This means that a 2-byte range /// straddling a page boundary causes both pages to be included in the allocated region. /// </param> /// <param name="flAllocationType"> /// <para>The type of memory allocation. This parameter must contain one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_COMMIT0x00001000</term> /// <term> /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function also /// guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated unless/until /// the virtual addresses are actually accessed.To reserve and commit pages in one step, call VirtualAlloc with .Attempting to commit a specific address /// range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL lpAddress fails unless the entire range has already been reserved. The resulting /// error code is ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means that you /// can commit pages without first determining the current commitment state of each page.If lpAddress specifies an address within an enclave, /// flAllocationType must be MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_RESERVE0x00002000</term> /// <term> /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on /// disk.You can commit reserved pages in subsequent calls to the VirtualAlloc function. To reserve and commit pages in one step, call VirtualAlloc with /// MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and LocalAlloc, cannot use a reserved range of memory until it is released. /// </term> /// </item> /// <item> /// <term>MEM_RESET0x00080000</term> /// <term> /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read from or written to /// the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other /// value.Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, /// decommit the memory and then recommit it.When you specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must /// still set flProtect to a valid protection value, such as PAGE_NOACCESS.VirtualAlloc returns an error if you use MEM_RESET and the range of memory is /// mapped to a file. A shared view is only acceptable if it is mapped to a paging file. /// </term> /// </item> /// <item> /// <term>MEM_RESET_UNDO0x1000000</term> /// <term> /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that the data in the /// specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the effects of MEM_RESET. If the /// function succeeds, that means all data in the specified address range is intact. If the function fails, at least some of the data in the address /// range has been replaced with zeroes.This value cannot be used with any other value. If MEM_RESET_UNDO is called on an address range which was not /// MEM_RESET earlier, the behavior is undefined. When you specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must /// still set flProtect to a valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows /// Server 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// </term> /// </item> /// </list> /// </para> /// <para>This parameter can also specify the following values as indicated.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_LARGE_PAGES0x20000000</term> /// <term> /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this value, use the /// GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_PHYSICAL0x00400000</term> /// <term> /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with MEM_RESERVE and no other values. /// </term> /// </item> /// <item> /// <term>MEM_TOP_DOWN0x00100000</term> /// <term>Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations.</term> /// </item> /// <item> /// <term>MEM_WRITE_WATCH0x00200000</term> /// <term> /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify MEM_RESERVE.To /// retrieve the addresses of the pages that have been written to since the region was allocated or the write-tracking state was reset, call the /// GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or ResetWriteWatch. The write-tracking feature remains enabled for the /// memory region until the region is freed. /// </term> /// </item> /// </list> /// </para> /// </param> /// <param name="flProtect"> /// <para> /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the memory protection constants. /// </para> /// <para>If lpAddress specifies an address within an enclave, flProtect cannot be any of the following values:</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is the base address of the allocated region of pages.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI VirtualAlloc( _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, _In_ DWORD flProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366887")] public static extern IntPtr VirtualAlloc([In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect); /// <summary> /// <para> /// Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process. The function initializes the /// memory it allocates to zero. /// </para> /// <para>To specify the NUMA node for the physical memory, see <c>VirtualAllocExNuma</c>.</para> /// </summary> /// <param name="hProcess"> /// <para>The handle to a process. The function allocates memory within the virtual address space of this process.</para> /// <para>The handle must have the <c>PROCESS_VM_OPERATION</c> access right. For more information, see Process Security and Access Rights.</para> /// </param> /// <param name="lpAddress"> /// <para>The pointer that specifies a desired starting address for the region of pages that you want to allocate.</para> /// <para>If you are reserving memory, the function rounds this address down to the nearest multiple of the allocation granularity.</para> /// <para> /// If you are committing memory that is already reserved, the function rounds this address down to the nearest page boundary. To determine the size of a /// page and the allocation granularity on the host computer, use the <c>GetSystemInfo</c> function. /// </para> /// <para>If lpAddress is <c>NULL</c>, the function determines where to allocate the region.</para> /// <para> /// If this address is within an enclave that you have not initialized by calling <c>InitializeEnclave</c>, <c>VirtualAllocEx</c> allocates a page of /// zeros for the enclave at that address. The page must be previously uncommitted, and will not be measured with the EEXTEND instruction of the Intel /// Software Guard Extensions programming model. /// </para> /// <para>If the address in within an enclave that you initialized, then the allocation operation fails with the <c>ERROR_INVALID_ADDRESS</c> error.</para> /// </param> /// <param name="dwSize"> /// <para>The size of the region of memory to allocate, in bytes.</para> /// <para>If lpAddress is <c>NULL</c>, the function rounds dwSize up to the next page boundary.</para> /// <para> /// If lpAddress is not <c>NULL</c>, the function allocates all pages that contain one or more bytes in the range from lpAddress to lpAddress+dwSize. /// This means, for example, that a 2-byte range that straddles a page boundary causes the function to allocate both pages. /// </para> /// </param> /// <param name="flAllocationType"> /// <para>The type of memory allocation. This parameter must contain one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_COMMIT0x00001000</term> /// <term> /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function also /// guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated unless/until /// the virtual addresses are actually accessed.To reserve and commit pages in one step, call VirtualAllocEx with .Attempting to commit a specific /// address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL lpAddress fails unless the entire range has already been reserved. The /// resulting error code is ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means /// that you can commit pages without first determining the current commitment state of each page.If lpAddress specifies an address within an enclave, /// flAllocationType must be MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_RESERVE0x00002000</term> /// <term> /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on /// disk.You commit reserved pages by calling VirtualAllocEx again with MEM_COMMIT. To reserve and commit pages in one step, call VirtualAllocEx with /// .Other memory allocation functions, such as malloc and LocalAlloc, cannot use reserved memory until it has been released. /// </term> /// </item> /// <item> /// <term>MEM_RESET0x00080000</term> /// <term> /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read from or written to /// the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other /// value.Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, /// decommit the memory and then recommit it.When you use MEM_RESET, the VirtualAllocEx function ignores the value of fProtect. However, you must still /// set fProtect to a valid protection value, such as PAGE_NOACCESS.VirtualAllocEx returns an error if you use MEM_RESET and the range of memory is /// mapped to a file. A shared view is only acceptable if it is mapped to a paging file. /// </term> /// </item> /// <item> /// <term>MEM_RESET_UNDO0x1000000</term> /// <term> /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that the data in the /// specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the effects of MEM_RESET. If the /// function succeeds, that means all data in the specified address range is intact. If the function fails, at least some of the data in the address /// range has been replaced with zeroes.This value cannot be used with any other value. If MEM_RESET_UNDO is called on an address range which was not /// MEM_RESET earlier, the behavior is undefined. When you specify MEM_RESET, the VirtualAllocEx function ignores the value of flProtect. However, you /// must still set flProtect to a valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, /// Windows Server 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// </term> /// </item> /// </list> /// </para> /// <para>This parameter can also specify the following values as indicated.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_LARGE_PAGES0x20000000</term> /// <term> /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this value, use the /// GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_PHYSICAL0x00400000</term> /// <term> /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with MEM_RESERVE and no other values. /// </term> /// </item> /// <item> /// <term>MEM_TOP_DOWN0x00100000</term> /// <term>Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations.</term> /// </item> /// </list> /// </para> /// </param> /// <param name="flProtect"> /// <para> /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the memory protection constants. /// </para> /// <para>If lpAddress specifies an address within an enclave, flProtect cannot be any of the following values:</para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is the base address of the allocated region of pages.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI VirtualAllocEx( _In_ HANDLE hProcess, _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, _In_ DWORD flProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366890")] public static extern IntPtr VirtualAllocEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect); /// <summary> /// Reserves, commits, or changes the state of a region of memory within the virtual address space of the specified process, and specifies the NUMA node /// for the physical memory. /// </summary> /// <param name="hProcess"> /// <para>The handle to a process. The function allocates memory within the virtual address space of this process.</para> /// <para>The handle must have the <c>PROCESS_VM_OPERATION</c> access right. For more information, see Process Security and Access Rights.</para> /// </param> /// <param name="lpAddress"> /// <para>The pointer that specifies a desired starting address for the region of pages that you want to allocate.</para> /// <para>If you are reserving memory, the function rounds this address down to the nearest multiple of the allocation granularity.</para> /// <para> /// If you are committing memory that is already reserved, the function rounds this address down to the nearest page boundary. To determine the size of a /// page and the allocation granularity on the host computer, use the <c>GetSystemInfo</c> function. /// </para> /// <para>If lpAddress is <c>NULL</c>, the function determines where to allocate the region.</para> /// </param> /// <param name="dwSize"> /// <para>The size of the region of memory to be allocated, in bytes.</para> /// <para>If lpAddress is <c>NULL</c>, the function rounds dwSize up to the next page boundary.</para> /// <para> /// If lpAddress is not <c>NULL</c>, the function allocates all pages that contain one or more bytes in the range from lpAddress to . This means, for /// example, that a 2-byte range that straddles a page boundary causes the function to allocate both pages. /// </para> /// </param> /// <param name="flAllocationType"> /// <para>The type of memory allocation. This parameter must contain one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_COMMIT0x00001000</term> /// <term> /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function also /// guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated unless/until /// the virtual addresses are actually accessed.To reserve and commit pages in one step, call the function with .Attempting to commit a specific address /// range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL lpAddress fails unless the entire range has already been reserved. The resulting /// error code is ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means that you /// can commit pages without first determining the current commitment state of each page. /// </term> /// </item> /// <item> /// <term>MEM_RESERVE0x00002000</term> /// <term> /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on /// disk.You commit reserved pages by calling the function again with MEM_COMMIT. To reserve and commit pages in one step, call the function with .Other /// memory allocation functions, such as malloc and LocalAlloc, cannot use reserved memory until it has been released. /// </term> /// </item> /// <item> /// <term>MEM_RESET0x00080000</term> /// <term> /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read from or written to /// the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other /// value.Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, /// decommit the memory and then recommit it.When you use MEM_RESET, the function ignores the value of fProtect. However, you must still set fProtect to /// a valid protection value, such as PAGE_NOACCESS.The function returns an error if you use MEM_RESET and the range of memory is mapped to a file. A /// shared view is only acceptable if it is mapped to a paging file. /// </term> /// </item> /// <item> /// <term>MEM_RESET_UNDO0x1000000</term> /// <term> /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that the data in the /// specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the effects of MEM_RESET. If the /// function succeeds, that means all data in the specified address range is intact. If the function fails, at least some of the data in the address /// range has been replaced with zeroes.This value cannot be used with any other value. If MEM_RESET_UNDO is called on an address range which was not /// MEM_RESET earlier, the behavior is undefined. When you specify MEM_RESET, the VirtualAllocExNuma function ignores the value of flProtect. However, /// you must still set flProtect to a valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008 and Windows /// Vista: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// </term> /// </item> /// </list> /// </para> /// <para>This parameter can also specify the following values as indicated.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_LARGE_PAGES0x20000000</term> /// <term> /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this value, use the /// GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_PHYSICAL0x00400000</term> /// <term> /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with MEM_RESERVE and no other values. /// </term> /// </item> /// <item> /// <term>MEM_TOP_DOWN0x00100000</term> /// <term>Allocates memory at the highest possible address.</term> /// </item> /// </list> /// </para> /// </param> /// <param name="flProtect"> /// <para> /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the memory protection constants. /// </para> /// <para>Protection attributes specified when protecting a page cannot conflict with those specified when allocating a page.</para> /// </param> /// <param name="nndPreferred"> /// <para>The NUMA node where the physical memory should reside.</para> /// <para> /// Used only when allocating a new VA region (either committed or reserved). Otherwise this parameter is ignored when the API is used to commit pages in /// a region that already exists /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is the base address of the allocated region of pages.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // LPVOID WINAPI VirtualAllocExNuma( _In_ HANDLE hProcess, _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, _In_ DWORD // flProtect, _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366891")] public static extern IntPtr VirtualAllocExNuma([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect, uint nndPreferred); /// <summary> /// Reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. Memory allocated by this function /// is automatically initialized to zero. /// </summary> /// <param name="BaseAddress"> /// The starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the nearest multiple of the /// allocation granularity. If the memory is already reserved and is being committed, the address is rounded down to the next page boundary. To determine /// the size of a page and the allocation granularity on the host computer, use the <c>GetSystemInfo</c> function. If this parameter is <c>NULL</c>, the /// system determines where to allocate the region. /// </param> /// <param name="Size"> /// The size of the region, in bytes. If the BaseAddress parameter is <c>NULL</c>, this value is rounded up to the next page boundary. Otherwise, the /// allocated pages include all pages containing one or more bytes in the range from BaseAddress to BaseAddress+Size. This means that a 2-byte range /// straddling a page boundary causes both pages to be included in the allocated region. /// </param> /// <param name="AllocationType"> /// <para>The type of memory allocation. This parameter must contain one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_COMMIT0x00001000</term> /// <term> /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. The function also /// guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical pages are not allocated unless/until /// the virtual addresses are actually accessed.To reserve and commit pages in one step, call VirtualAllocFromApp with .Attempting to commit a specific /// address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL BaseAddress fails unless the entire range has already been reserved. The /// resulting error code is ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means /// that you can commit pages without first determining the current commitment state of each page. /// </term> /// </item> /// <item> /// <term>MEM_RESERVE0x00002000</term> /// <term> /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging file on /// disk.You can commit reserved pages in subsequent calls to the VirtualAllocFromApp function. To reserve and commit pages in one step, call /// VirtualAllocFromApp with MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and LocalAlloc, cannot use a reserved range of /// memory until it is released. /// </term> /// </item> /// <item> /// <term>MEM_RESET0x00080000</term> /// <term> /// Indicates that data in the memory range specified by BaseAddress and Size is no longer of interest. The pages should not be read from or written to /// the paging file. However, the memory block will be used again later, so it should not be decommitted. This value cannot be used with any other /// value.Using this value does not guarantee that the range operated on with MEM_RESET will contain zeros. If you want the range to contain zeros, /// decommit the memory and then recommit it.When you specify MEM_RESET, the VirtualAllocFromApp function ignores the value of Protection. However, you /// must still set Protection to a valid protection value, such as PAGE_NOACCESS.VirtualAllocFromApp returns an error if you use MEM_RESET and the range /// of memory is mapped to a file. A shared view is only acceptable if it is mapped to a paging file. /// </term> /// </item> /// <item> /// <term>MEM_RESET_UNDO0x1000000</term> /// <term> /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that the data in the /// specified memory range specified by BaseAddress and Size is of interest to the caller and attempts to reverse the effects of MEM_RESET. If the /// function succeeds, that means all data in the specified address range is intact. If the function fails, at least some of the data in the address /// range has been replaced with zeroes.This value cannot be used with any other value. If MEM_RESET_UNDO is called on an address range which was not /// MEM_RESET earlier, the behavior is undefined. When you specify MEM_RESET, the VirtualAllocFromApp function ignores the value of Protection. However, /// you must still set Protection to a valid protection value, such as PAGE_NOACCESS. /// </term> /// </item> /// </list> /// </para> /// <para>This parameter can also specify the following values as indicated.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_LARGE_PAGES0x20000000</term> /// <term> /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this value, use the /// GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// </term> /// </item> /// <item> /// <term>MEM_PHYSICAL0x00400000</term> /// <term> /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with MEM_RESERVE and no other values. /// </term> /// </item> /// <item> /// <term>MEM_TOP_DOWN0x00100000</term> /// <term>Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations.</term> /// </item> /// <item> /// <term>MEM_WRITE_WATCH0x00200000</term> /// <term> /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify MEM_RESERVE.To /// retrieve the addresses of the pages that have been written to since the region was allocated or the write-tracking state was reset, call the /// GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or ResetWriteWatch. The write-tracking feature remains enabled for the /// memory region until the region is freed. /// </term> /// </item> /// </list> /// </para> /// </param> /// <param name="Protection"> /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify one of the memory protection /// constants. The following constants generate an error: /// </param> /// <returns> /// <para>If the function succeeds, the return value is the base address of the allocated region of pages.</para> /// <para>If the function fails, the return value is <c>NULL</c>. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // PVOID WINAPI VirtualAllocFromApp( _In_opt_ PVOID BaseAddress, _In_ SIZE_T Size, _In_ ULONG AllocationType, _In_ ULONG Protection); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169845")] public static extern IntPtr VirtualAllocFromApp([In] IntPtr BaseAddress, SizeT Size, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION Protection); /// <summary> /// <para>Releases, decommits, or releases and decommits a region of pages within the virtual address space of the calling process.</para> /// <para>To free memory allocated in another process by the <c>VirtualAllocEx</c> function, use the <c>VirtualFreeEx</c> function.</para> /// </summary> /// <param name="lpAddress"> /// <para>A pointer to the base address of the region of pages to be freed.</para> /// <para> /// If the dwFreeType parameter is <c>MEM_RELEASE</c>, this parameter must be the base address returned by the <c>VirtualAlloc</c> function when the /// region of pages is reserved. /// </para> /// </param> /// <param name="dwSize"> /// <para>The size of the region of memory to be freed, in bytes.</para> /// <para> /// If the dwFreeType parameter is <c>MEM_RELEASE</c>, this parameter must be 0 (zero). The function frees the entire region that is reserved in the /// initial allocation call to <c>VirtualAlloc</c>. /// </para> /// <para> /// If the dwFreeType parameter is <c>MEM_DECOMMIT</c>, the function decommits all memory pages that contain one or more bytes in the range from the /// lpAddress parameter to . This means, for example, that a 2-byte region of memory that straddles a page boundary causes both pages to be decommitted. /// If lpAddress is the base address returned by <c>VirtualAlloc</c> and dwSize is 0 (zero), the function decommits the entire region that is allocated /// by <c>VirtualAlloc</c>. After that, the entire region is in the reserved state. /// </para> /// </param> /// <param name="dwFreeType"> /// <para>The type of free operation. This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_DECOMMIT0x4000</term> /// <term> /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function does not fail if you /// attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first determining the current commitment state.Do /// not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when the lpAddress parameter provides the base address for an enclave. /// </term> /// </item> /// <item> /// <term>MEM_RELEASE0x8000</term> /// <term> /// Releases the specified region of pages. After this operation, the pages are in the free state. If you specify this value, dwSize must be 0 (zero), /// and lpAddress must point to the base address returned by the VirtualAlloc function when the region is reserved. The function fails if either of these /// conditions is not met.If any pages in the region are committed currently, the function first decommits, and then releases them.The function does not /// fail if you attempt to release pages that are in different states, some reserved and some committed. This means that you can release a range of pages /// without first determining the current commitment state.Do not use this value with MEM_DECOMMIT. /// </term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualFree( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD dwFreeType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366892")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualFree([In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE dwFreeType); /// <summary>Releases, decommits, or releases and decommits a region of memory within the virtual address space of a specified process.</summary> /// <param name="hProcess"> /// <para>A handle to a process. The function frees memory within the virtual address space of the process.</para> /// <para>The handle must have the <c>PROCESS_VM_OPERATION</c> access right. For more information, see Process Security and Access Rights.</para> /// </param> /// <param name="lpAddress"> /// <para>A pointer to the starting address of the region of memory to be freed.</para> /// <para> /// If the dwFreeType parameter is <c>MEM_RELEASE</c>, lpAddress must be the base address returned by the <c>VirtualAllocEx</c> function when the region /// is reserved. /// </para> /// </param> /// <param name="dwSize"> /// <para>The size of the region of memory to free, in bytes.</para> /// <para> /// If the dwFreeType parameter is <c>MEM_RELEASE</c>, dwSize must be 0 (zero). The function frees the entire region that is reserved in the initial /// allocation call to <c>VirtualAllocEx</c>. /// </para> /// <para> /// If dwFreeType is <c>MEM_DECOMMIT</c>, the function decommits all memory pages that contain one or more bytes in the range from the lpAddress /// parameter to . This means, for example, that a 2-byte region of memory that straddles a page boundary causes both pages to be decommitted. If /// lpAddress is the base address returned by <c>VirtualAllocEx</c> and dwSize is 0 (zero), the function decommits the entire region that is allocated by /// <c>VirtualAllocEx</c>. After that, the entire region is in the reserved state. /// </para> /// </param> /// <param name="dwFreeType"> /// <para>The type of free operation. This parameter can be one of the following values.</para> /// <para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>MEM_DECOMMIT0x4000</term> /// <term> /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function does not fail if you /// attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first determining their current commitment /// state.Do not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when the lpAddress parameter provides the base address for an enclave. /// </term> /// </item> /// <item> /// <term>MEM_RELEASE0x8000</term> /// <term> /// Releases the specified region of pages. After the operation, the pages are in the free state. If you specify this value, dwSize must be 0 (zero), and /// lpAddress must point to the base address returned by the VirtualAllocEx function when the region is reserved. The function fails if either of these /// conditions is not met.If any pages in the region are committed currently, the function first decommits, and then releases them.The function does not /// fail if you attempt to release pages that are in different states, some reserved and some committed. This means that you can release a range of pages /// without first determining the current commitment state.Do not use this value with MEM_DECOMMIT. /// </term> /// </item> /// </list> /// </para> /// </param> /// <returns> /// <para>If the function succeeds, the return value is a nonzero value.</para> /// <para>If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualFreeEx( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD dwFreeType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366894")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualFreeEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE dwFreeType); /// <summary> /// Locks the specified region of the process's virtual address space into physical memory, ensuring that subsequent access to the region will not incur /// a page fault. /// </summary> /// <param name="lpAddress">A pointer to the base address of the region of pages to be locked.</param> /// <param name="dwSize"> /// The size of the region to be locked, in bytes. The region of affected pages includes all pages that contain one or more bytes in the range from the /// lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes both pages to be locked. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualLock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366895")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualLock([In] IntPtr lpAddress, SizeT dwSize); /// <summary> /// <para>Changes the protection on a region of committed pages in the virtual address space of the calling process.</para> /// <para>To change the access protection of any process, use the <c>VirtualProtectEx</c> function.</para> /// </summary> /// <param name="lpAddress"> /// <para>A pointer an address that describes the starting page of the region of pages whose access protection attributes are to be changed.</para> /// <para> /// All pages in the specified region must be within the same reserved region allocated when calling the <c>VirtualAlloc</c> or <c>VirtualAllocEx</c> /// function using <c>MEM_RESERVE</c>. The pages cannot span adjacent reserved regions that were allocated by separate calls to <c>VirtualAlloc</c> or /// <c>VirtualAllocEx</c> using <c>MEM_RESERVE</c>. /// </para> /// </param> /// <param name="dwSize"> /// The size of the region whose access protection attributes are to be changed, in bytes. The region of affected pages includes all pages containing one /// or more bytes in the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes the protection /// attributes of both pages to be changed. /// </param> /// <param name="flNewProtect"> /// <para>The memory protection option. This parameter can be one of the memory protection constants.</para> /// <para> /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see <c>MapViewOfFile</c>, /// <c>MapViewOfFileEx</c>, and <c>MapViewOfFileExNuma</c>). /// </para> /// </param> /// <param name="lpflOldProtect"> /// A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If this parameter is /// <c>NULL</c> or does not point to a valid variable, the function fails. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualProtect( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flNewProtect, _Out_ PDWORD lpflOldProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366898")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualProtect([In] IntPtr lpAddress, SizeT dwSize, MEM_PROTECTION flNewProtect, [Out] out MEM_PROTECTION lpflOldProtect); /// <summary>Changes the protection on a region of committed pages in the virtual address space of a specified process.</summary> /// <param name="hProcess"> /// A handle to the process whose memory protection is to be changed. The handle must have the <c>PROCESS_VM_OPERATION</c> access right. For more /// information, see Process Security and Access Rights. /// </param> /// <param name="lpAddress"> /// <para>A pointer to the base address of the region of pages whose access protection attributes are to be changed.</para> /// <para> /// All pages in the specified region must be within the same reserved region allocated when calling the <c>VirtualAlloc</c> or <c>VirtualAllocEx</c> /// function using <c>MEM_RESERVE</c>. The pages cannot span adjacent reserved regions that were allocated by separate calls to <c>VirtualAlloc</c> or /// <c>VirtualAllocEx</c> using <c>MEM_RESERVE</c>. /// </para> /// </param> /// <param name="dwSize"> /// The size of the region whose access protection attributes are changed, in bytes. The region of affected pages includes all pages containing one or /// more bytes in the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes the protection attributes /// of both pages to be changed. /// </param> /// <param name="flNewProtect"> /// <para>The memory protection option. This parameter can be one of the memory protection constants.</para> /// <para> /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see <c>MapViewOfFile</c>, /// <c>MapViewOfFileEx</c>, and <c>MapViewOfFileExNuma</c>). /// </para> /// </param> /// <param name="lpflOldProtect"> /// A pointer to a variable that receives the previous access protection of the first page in the specified region of pages. If this parameter is /// <c>NULL</c> or does not point to a valid variable, the function fails. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualProtectEx( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flNewProtect, _Out_ PDWORD lpflOldProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366899")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualProtectEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_PROTECTION flNewProtect, [Out] out MEM_PROTECTION lpflOldProtect); /// <summary>Changes the protection on a region of committed pages in the virtual address space of the calling process.</summary> /// <param name="Address"> /// <para>A pointer an address that describes the starting page of the region of pages whose access protection attributes are to be changed.</para> /// <para> /// All pages in the specified region must be within the same reserved region allocated when calling the <c>VirtualAlloc</c>, <c>VirtualAllocFromApp</c>, /// or <c>VirtualAllocEx</c> function using <c>MEM_RESERVE</c>. The pages cannot span adjacent reserved regions that were allocated by separate calls to /// <c>VirtualAlloc</c>, <c>VirtualAllocFromApp</c>, or <c>VirtualAllocEx</c> using <c>MEM_RESERVE</c>. /// </para> /// </param> /// <param name="Size"> /// The size of the region whose access protection attributes are to be changed, in bytes. The region of affected pages includes all pages containing one /// or more bytes in the range from the Address parameter to . This means that a 2-byte range straddling a page boundary causes the protection attributes /// of both pages to be changed. /// </param> /// <param name="NewProtection"> /// <para>The memory protection option. This parameter can be one of the memory protection constants.</para> /// <para> /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see <c>MapViewOfFile</c>, /// <c>MapViewOfFileEx</c>, and <c>MapViewOfFileExNuma</c>). /// </para> /// <para>The following constants generate an error:</para> /// <para>The following constants are allowed only for apps that have the <c>codeGeneration</c> capability:</para> /// </param> /// <param name="OldProtection"> /// A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If this parameter is /// <c>NULL</c> or does not point to a valid variable, the function fails. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualProtectFromApp( _In_ PVOID Address, _In_ SIZE_T Size, _In_ ULONG NewProtection, _Out_ PULONG OldProtection); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169846")] public static extern bool VirtualProtectFromApp([In] IntPtr Address, SizeT Size, MEM_PROTECTION NewProtection, [Out] out MEM_PROTECTION OldProtection); /// <summary> /// <para>Retrieves information about a range of pages in the virtual address space of the calling process.</para> /// <para>To retrieve information about a range of pages in the address space of another process, use the <c>VirtualQueryEx</c> function.</para> /// </summary> /// <param name="lpAddress"> /// <para> /// A pointer to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To determine the size of a /// page on the host computer, use the <c>GetSystemInfo</c> function. /// </para> /// <para>If lpAddress specifies an address above the highest memory address accessible to the process, the function fails with <c>ERROR_INVALID_PARAMETER</c>.</para> /// </param> /// <param name="lpBuffer">A pointer to a <c>MEMORY_BASIC_INFORMATION</c> structure in which information about the specified page range is returned.</param> /// <param name="dwLength">The size of the buffer pointed to by the lpBuffer parameter, in bytes.</param> /// <returns> /// <para>The return value is the actual number of bytes returned in the information buffer.</para> /// <para> /// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. Possible error values include <c>ERROR_INVALID_PARAMETER</c>. /// </para> /// </returns> // SIZE_T WINAPI VirtualQuery( _In_opt_ LPCVOID lpAddress, _Out_ PMEMORY_BASIC_INFORMATION lpBuffer, _In_ SIZE_T dwLength); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366902")] public static extern SizeT VirtualQuery([In] IntPtr lpAddress, IntPtr lpBuffer, SizeT dwLength); /// <summary>Retrieves information about a range of pages within the virtual address space of a specified process.</summary> /// <param name="hProcess"> /// A handle to the process whose memory information is queried. The handle must have been opened with the <c>PROCESS_QUERY_INFORMATION</c> access right, /// which enables using the handle to read information from the process object. For more information, see Process Security and Access Rights. /// </param> /// <param name="lpAddress"> /// <para> /// A pointer to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To determine the size of a /// page on the host computer, use the <c>GetSystemInfo</c> function. /// </para> /// <para>If lpAddress specifies an address above the highest memory address accessible to the process, the function fails with <c>ERROR_INVALID_PARAMETER</c>.</para> /// </param> /// <param name="lpBuffer">A pointer to a <c>MEMORY_BASIC_INFORMATION</c> structure in which information about the specified page range is returned.</param> /// <param name="dwLength">The size of the buffer pointed to by the lpBuffer parameter, in bytes.</param> /// <returns> /// <para>The return value is the actual number of bytes returned in the information buffer.</para> /// <para> /// If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>. Possible error values include <c>ERROR_INVALID_PARAMETER</c>. /// </para> /// </returns> // SIZE_T WINAPI VirtualQueryEx( _In_ HANDLE hProcess, _In_opt_ LPCVOID lpAddress, _Out_ PMEMORY_BASIC_INFORMATION lpBuffer, _In_ SIZE_T dwLength); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366907")] public static extern SizeT VirtualQueryEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, IntPtr lpBuffer, SizeT dwLength); /// <summary> /// Unlocks a specified range of pages in the virtual address space of a process, enabling the system to swap the pages out to the /// paging file if necessary. /// </summary> /// <param name="lpAddress">A pointer to the base address of the region of pages to be unlocked.</param> /// <param name="dwSize"> /// The size of the region being unlocked, in bytes. The region of affected pages includes all pages containing one or more bytes in /// the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes both pages to be unlocked. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call <c>GetLastError</c>.</para> /// </returns> // BOOL WINAPI VirtualUnlock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366910(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366910")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualUnlock(IntPtr lpAddress, SizeT dwSize); /// <summary>Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails.</summary> /// <param name="hProcess"> /// A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process. /// </param> /// <param name="lpBaseAddress"> /// A pointer to the base address in the specified process to which data is written. Before data transfer occurs, the system verifies that all data in /// the base address and memory of the specified size is accessible for write access, and if it is not accessible, the function fails. /// </param> /// <param name="lpBuffer">A pointer to the buffer that contains data to be written in the address space of the specified process.</param> /// <param name="nSize">The number of bytes to be written to the specified process.</param> /// <param name="lpNumberOfBytesWritten"> /// A pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional. If /// lpNumberOfBytesWritten is <c>NULL</c>, the parameter is ignored. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para> /// If the function fails, the return value is 0 (zero). To get extended error information, call <c>GetLastError</c>. The function fails if the requested /// write operation crosses into an area of the process that is inaccessible. /// </para> /// </returns> // BOOL WINAPI WriteProcessMemory( _In_ HANDLE hProcess, _In_ LPVOID lpBaseAddress, _In_ LPCVOID lpBuffer, _In_ SIZE_T nSize, _Out_ SIZE_T *lpNumberOfBytesWritten); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms681674")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WriteProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, [In] IntPtr lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesWritten); /// <summary>Represents information about call targets for Control Flow Guard (CFG).</summary> // typedef struct _CFG_CALL_TARGET_INFO { ULONG_PTR Offset; ULONG_PTR Flags;} CFG_CALL_TARGET_INFO, *PCFG_CALL_TARGET_INFO; [PInvokeData("Ntmmapi.h", MSDNShortId = "mt219054")] public struct CFG_CALL_TARGET_INFO { /// <summary> /// Flags describing the operation to be performed on the address. If <c>CFG_CALL_TARGET_VALID</c> is set, then the address will be marked valid for /// CFG. Otherwise, it will be marked an invalid call target. /// </summary> public UIntPtr Flags; /// <summary>Offset relative to a provided (start) virtual address. This offset should be 16 byte aligned.</summary> public UIntPtr Offset; } /// <summary>Specifies a range of memory. This structure is used by the <c>PrefetchVirtualMemory</c> function.</summary> // typedef struct _WIN32_MEMORY_RANGE_ENTRY { PVOID VirtualAddress; SIZE_T NumberOfBytes;} WIN32_MEMORY_RANGE_ENTRY, *PWIN32_MEMORY_RANGE_ENTRY; [PInvokeData("WinBase.h", MSDNShortId = "hh780544")] public struct WIN32_MEMORY_RANGE_ENTRY { /// <summary></summary> public SizeT NumberOfBytes; /// <summary></summary> public IntPtr VirtualAddress; } /// <summary>Provides a <see cref="SafeHandle"/> to a memory resource notification object that releases its instance at disposal using CloseHandle.</summary> public class SafeMemoryResourceNotification : SafeSyncHandle { /// <summary>Initializes a new instance of the <see cref="SafeMemoryResourceNotification"/> class and assigns an existing handle.</summary> /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"><see langword="true"/> to reliably release the handle during the finalization phase; otherwise, <see langword="false"/> (not recommended).</param> public SafeMemoryResourceNotification(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MapArcGIS { public struct FeatureTableItem { //byte[] item; } }
using System; using System.Reflection; using System.Text.RegularExpressions; using Terminal.Gui.TextValidateProviders; using Xunit; namespace Terminal.Gui.ViewTests { public class TextValidateField_NET_Provider_Tests { [Fact] [AutoInitShutdown] public void Initialized_With_Cursor_On_First_Editable_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1___)--", field.Provider.DisplayText); Assert.Equal ("--(1 )--", field.Text); } [Fact] [AutoInitShutdown] public void Input_Ilegal_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.A, new KeyModifiers { })); Assert.Equal ("--( )--", field.Text); Assert.Equal ("--(____)--", field.Provider.DisplayText); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Home_Key_First_Editable_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Home, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1___)--", field.Provider.DisplayText); Assert.Equal ("--(1 )--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void End_Key_Last_Editable_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.End, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(___1)--", field.Provider.DisplayText); Assert.Equal ("--( 1)--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Right_Key_Stops_In_Last_Editable_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; for (int i = 0; i < 10; i++) { field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); } field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(___1)--", field.Provider.DisplayText); Assert.Equal ("--( 1)--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Left_Key_Stops_In_First_Editable_Character () { // * // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; for (int i = 0; i < 10; i++) { field.ProcessKey (new KeyEvent (Key.CursorLeft, new KeyModifiers { })); } field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1___)--", field.Provider.DisplayText); Assert.Equal ("--(1 )--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void When_Valid_Is_Valid_True () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1 )--", field.Text); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D2, new KeyModifiers { })); Assert.Equal ("--(12 )--", field.Text); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D3, new KeyModifiers { })); Assert.Equal ("--(123 )--", field.Text); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D4, new KeyModifiers { })); Assert.Equal ("--(1234)--", field.Text); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void Insert_Skips_Non_Editable_Characters () { // ** ** // 01234567890 var field = new TextValidateField (new NetMaskedTextProvider ("--(00-00)--")) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1_-__)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D2, new KeyModifiers { })); Assert.Equal ("--(12-__)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D3, new KeyModifiers { })); Assert.Equal ("--(12-3_)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D4, new KeyModifiers { })); Assert.Equal ("--(12-34)--", field.Provider.DisplayText); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void Initial_Value_Exact_Valid () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--") { Text = "1234" }) { TextAlignment = TextAlignment.Centered, Width = 20 }; Assert.Equal ("--(1234)--", field.Text); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void Initial_Value_Bigger_Than_Mask_Discarded () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--") { Text = "12345" }) { TextAlignment = TextAlignment.Centered, Width = 20 }; Assert.Equal ("--(____)--", field.Provider.DisplayText); Assert.Equal ("--( )--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Initial_Value_Smaller_Than_Mask_Accepted () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--") { Text = "123" }) { TextAlignment = TextAlignment.Centered, Width = 20 }; Assert.Equal ("--(123_)--", field.Provider.DisplayText); Assert.Equal ("--(123 )--", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Delete_Key_Dosent_Move_Cursor () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--") { Text = "1234" }) { TextAlignment = TextAlignment.Centered, Width = 20 }; Assert.Equal ("--(1234)--", field.Provider.DisplayText); Assert.True (field.IsValid); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); Assert.Equal ("--(_234)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); Assert.Equal ("--(_2_4)--", field.Provider.DisplayText); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Backspace_Key_Deletes_Previous_Character () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--") { Text = "1234" }) { TextAlignment = TextAlignment.Centered, Width = 20 }; // Go to the end. field.ProcessKey (new KeyEvent (Key.End, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.Backspace, new KeyModifiers { })); Assert.Equal ("--(12_4)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.Backspace, new KeyModifiers { })); Assert.Equal ("--(1__4)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.Backspace, new KeyModifiers { })); Assert.Equal ("--(___4)--", field.Provider.DisplayText); Assert.False (field.IsValid); // One more field.ProcessKey (new KeyEvent (Key.Backspace, new KeyModifiers { })); Assert.Equal ("--(___4)--", field.Provider.DisplayText); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Set_Text_After_Initialization () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Left, Width = 30 }; field.Text = "1234"; Assert.Equal ("--(1234)--", field.Text); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void Changing_The_Mask_Tries_To_Keep_The_Previous_Text () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Left, Width = 30 }; field.Text = "1234"; Assert.Equal ("--(1234)--", field.Text); Assert.True (field.IsValid); var provider = field.Provider as NetMaskedTextProvider; provider.Mask = "--------(00000000)--------"; Assert.Equal ("--------(1234____)--------", field.Provider.DisplayText); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void MouseClick_Right_X_Greater_Than_Text_Width_Goes_To_Last_Editable_Position () { // **** // 0123456789 var field = new TextValidateField (new NetMaskedTextProvider ("--(0000)--")) { TextAlignment = TextAlignment.Left, Width = 30 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1___)--", field.Provider.DisplayText); Assert.False (field.IsValid); field.MouseEvent (new MouseEvent () { X = 25, Flags = MouseFlags.Button1Pressed }); field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("--(1__1)--", field.Provider.DisplayText); Assert.False (field.IsValid); } } public class TextValidateField_Regex_Provider_Tests { [Fact] [AutoInitShutdown] public void Input_Without_Validate_On_Input () { var field = new TextValidateField (new TextRegexProvider ("^[0-9][0-9][0-9]$") { ValidateOnInput = false }) { Width = 20 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("1", field.Text); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D2, new KeyModifiers { })); Assert.Equal ("12", field.Text); Assert.False (field.IsValid); field.ProcessKey (new KeyEvent (Key.D3, new KeyModifiers { })); Assert.Equal ("123", field.Text); Assert.True (field.IsValid); field.ProcessKey (new KeyEvent (Key.D4, new KeyModifiers { })); Assert.Equal ("1234", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Input_With_Validate_On_Input_Set_Text () { var field = new TextValidateField (new TextRegexProvider ("^[0-9][0-9][0-9]$")) { Width = 20 }; // Input dosen't validates the pattern. field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); Assert.Equal ("", field.Text); Assert.False (field.IsValid); // Dosen't match field.Text = "12356"; Assert.Equal ("", field.Text); Assert.False (field.IsValid); // Yes. field.Text = "123"; Assert.Equal ("123", field.Text); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void Text_With_All_Charset () { var field = new TextValidateField (new TextRegexProvider ("^[0-9][0-9][0-9]$")) { Width = 20 }; var text = ""; for (int i = 0; i < 255; i++) { text += (char)i; } field.Text = text; Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Mask_With_Invalid_Pattern_Exception () { // Regex Exception // Maybe it's not the right behaviour. var mask = ""; for (int i = 0; i < 255; i++) { mask += (char)i; } try { var field = new TextValidateField (new TextRegexProvider (mask)) { Width = 20 }; } catch (RegexParseException ex) { Assert.True (true, ex.Message); return; } Assert.True (false); } [Fact] [AutoInitShutdown] public void Home_Key_First_Editable_Character () { // Range 0 to 1000 // Accepts 001 too. var field = new TextValidateField (new TextRegexProvider ("^[0-9]?[0-9]?[0-9]|1000$")) { Width = 20 }; field.ProcessKey (new KeyEvent (Key.D1, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.D0, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.D0, new KeyModifiers { })); field.ProcessKey (new KeyEvent (Key.D0, new KeyModifiers { })); Assert.Equal ("1000", field.Text); Assert.True (field.IsValid); // HOME KEY field.ProcessKey (new KeyEvent (Key.Home, new KeyModifiers { })); // DELETE field.ProcessKey (new KeyEvent (Key.Delete, new KeyModifiers { })); Assert.Equal ("000", field.Text); Assert.True (field.IsValid); } [Fact] [AutoInitShutdown] public void End_Key_End_Of_Input () { // Exactly 5 numbers var field = new TextValidateField (new TextRegexProvider ("^[0-9]{5}$") { ValidateOnInput = false }) { Width = 20 }; for (int i = 0; i < 4; i++) { field.ProcessKey (new KeyEvent (Key.D0, new KeyModifiers { })); } Assert.Equal ("0000", field.Text); Assert.False (field.IsValid); // HOME KEY field.ProcessKey (new KeyEvent (Key.Home, new KeyModifiers { })); // END KEY field.ProcessKey (new KeyEvent (Key.End, new KeyModifiers { })); // Insert 9 field.ProcessKey (new KeyEvent (Key.D9, new KeyModifiers { })); Assert.Equal ("00009", field.Text); Assert.True (field.IsValid); // Insert 9 field.ProcessKey (new KeyEvent (Key.D9, new KeyModifiers { })); Assert.Equal ("000099", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Right_Key_Stops_At_End_And_Insert () { var field = new TextValidateField (new TextRegexProvider ("^[0-9][0-9][0-9]$") { ValidateOnInput = false }) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.Text = "123"; for (int i = 0; i < 10; i++) { field.ProcessKey (new KeyEvent (Key.CursorRight, new KeyModifiers { })); } Assert.Equal ("123", field.Text); Assert.True (field.IsValid); // Insert 4 field.ProcessKey (new KeyEvent (Key.D4, new KeyModifiers { })); Assert.Equal ("1234", field.Text); Assert.False (field.IsValid); } [Fact] [AutoInitShutdown] public void Left_Key_Stops_At_Start_And_Insert () { var field = new TextValidateField (new TextRegexProvider ("^[0-9][0-9][0-9]$") { ValidateOnInput = false }) { TextAlignment = TextAlignment.Centered, Width = 20 }; field.Text = "123"; for (int i = 0; i < 10; i++) { field.ProcessKey (new KeyEvent (Key.CursorLeft, new KeyModifiers { })); } Assert.Equal ("123", field.Text); Assert.True (field.IsValid); // Insert 4 field.ProcessKey (new KeyEvent (Key.D4, new KeyModifiers { })); Assert.Equal ("4123", field.Text); Assert.False (field.IsValid); } } }
using UnityEngine; using System.Collections; using System; public class overallControl : MonoBehaviour { GameObject canvas; GameObject settings; bool audioOn; GameObject inGameGuide; System.Random random; float startTime; float timeUntilChange; GameObject changingDisplay; SpriteRenderer renderer; TextMesh displaytext; String state; float reactionTimeS; int screenWidth; int screenHeight; GameObject camera; Camera camComponent; // Use this for initialization void Start () { camera = GameObject.Find("Camera"); settings = GameObject.Find("settingsElements"); settings.SetActive(false); audioOn = true; inGameGuide = GameObject.Find("gameInstructions"); random = new System.Random(); changingDisplay = GameObject.Find("display"); renderer = changingDisplay.GetComponent<SpriteRenderer>(); timeUntilChange = 2; displaytext = inGameGuide.GetComponent<TextMesh>(); state = "start"; reactionTimeS = 0.5f; startTime = 0.1f; renderer.color = new Color(0, 0, 1, 1); camComponent = camera.GetComponent<Camera>(); screenWidth = Screen.width; screenHeight = Screen.height; var screenRatio = Convert.ToSingle(screenWidth) / Convert.ToSingle(screenHeight); var worldRatio = 2.8f; camComponent.orthographicSize = screenRatio > worldRatio ? 4.2f : 4.2f * worldRatio / screenRatio; } // Update is called once per frame void Update () { /* if (waitingForTurn && Time.time - timeAtPlayStart >= timeUntilChange) { renderer.color = new Color(1, 0, 0, 1); typeFast = true; timeAtPlayStart = Time.time; waitingForTurn = false; } if(waitingForTurn && Time.time - timeAtPlayStart < timeUntilChange && Input.GetKeyDown("3") && !gameOver) { timeAtPlayStart = Time.time; Debug.Log("Timer reset!"); } if (Input.GetKeyDown("2") && atTitle && settingsDisplayed == false) { settings.SetActive(true); settingsDisplayed = true; }else if(Input.GetKeyDown("2") && atTitle && settingsDisplayed == true) { settings.SetActive(false); settingsDisplayed = false; } if(settingsDisplayed && Input.GetKeyDown("3") && atTitle) { audioOn = !audioOn; } if(!atTitle && Input.GetKeyDown("3") && !waitingForTurn && Time.time > timeAtPlayStart + 2) { inGameGuide.SetActive(false); changeSetup(); } */ if (state == "start") { titleCycle(); }else if(state == "settings") { settingsCycle(); }else if (state == "guideToPlay") { guideCycle(); }else if(state == "beforeTurningToRed") { beforeRedCycle(); }else if(state == "gottaPressFast") { actionRedCycle(); }else if (state == "failure") { retryCycle(); } if (Input.GetKeyDown("up")) { canvas.SetActive(false); renderer.color = new Color(1, 0, 0, 1); successText(); } } void titleCycle() { /* if (Input.GetKeyDown("3")) { canvas.SetActive(false); state = "guideToPlay"; } if (Input.GetKeyDown("2")) { state = "settings"; settings.SetActive(true); } if (Input.GetKeyDown("1")) { Application.Quit(); } */ } void settingsCycle() { if (Input.GetKeyDown("3")) { audioOn = !audioOn; Debug.Log("The state of audio being on is: " + audioOn); }else if (Input.GetKeyDown("2")) { state = "start"; settings.SetActive(false); } } void guideCycle() { if(Time.time > startTime + 0.25) { if (Input.GetKeyDown("3")) { state = "beforeTurningToRed"; var randomDouble = random.NextDouble(); timeUntilChange = 2 + Convert.ToSingle(randomDouble) * 2; startTime = Time.time; //Debug.Log("The timeUntilChange is: " + timeUntilChange); inGameGuide.SetActive(false); } } } void beforeRedCycle() { if(Time.time >= startTime + timeUntilChange) { renderer.color = new Color(1, 0, 0, 1); state = "gottaPressFast"; startTime = Time.time; } if (Input.GetKeyDown("3")) { startTime = Time.time; } } void actionRedCycle() { if (Time.time > startTime + reactionTimeS) { state = "failure"; displaytext.text = "experiment failed. press 3 to" + "\n" + "try again."; inGameGuide.SetActive(true); }else if (Input.GetKeyDown("3")) { state = "success"; // " + "\n" + " successText(); inGameGuide.SetActive(true); } } void successText() { displaytext.text = "experiment succeeded! The" + "\n" + "time you needed to react to " + "\n" + "the color changing was" + "\n" + (Time.time - startTime) + " seconds!"; } void retryCycle() { if (Input.GetKeyDown("3")) { renderer.color = new Color(0, 0, 1, 1); var randomDouble = random.NextDouble(); timeUntilChange = 2 + Convert.ToSingle(randomDouble) * 2; startTime = Time.time; inGameGuide.SetActive(false); state = "beforeTurningToRed"; } } //For changing color: https://docs.unity3d.com/ScriptReference/Color.html }
// <copyright file="MultipleSubstitution.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System.Collections.Generic; namespace WaterTrans.GlyphLoader.Internal.OpenType.GSUB { /// <summary> /// The GSUB multiple substitution lookup. /// </summary> internal sealed class MultipleSubstitution { /// <summary> /// Initializes a new instance of the <see cref="MultipleSubstitution"/> class. /// </summary> /// <param name="glyphIndex">Sets original glyph index.</param> /// <param name="substitutionGlyphIndex">Sets lookup glyph index.</param> internal MultipleSubstitution(ushort glyphIndex, ushort[] substitutionGlyphIndex) { GlyphIndex = glyphIndex; SubstitutionGlyphIndex = substitutionGlyphIndex; } /// <summary>Gets an original glyph index.</summary> public ushort GlyphIndex { get; } /// <summary>Gets a lookup glyph index.</summary> public ushort[] SubstitutionGlyphIndex { get; } } }