text
stringlengths
13
6.01M
using MinecraftToolsBoxSDK; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; namespace MinecraftToolsBox.Commands { /// <summary> /// MobSpawner.xaml 的交互逻辑 /// </summary> public partial class MobSpawner : Grid, ICommandGenerator { public CommandsGeneratorTemplate Tmp; public ObservableCollection<Potential> Data = new ObservableCollection<Potential>(); public MobSpawner(CommandsGeneratorTemplate tmp) { InitializeComponent(); Tmp = tmp; potentials.DataContext = Data; } private void Potentials_AddingNewItem(object sender, AddingNewItemEventArgs e) { potentials.Items.Refresh(); } private void Potentials_UnloadingRow(object sender, DataGridRowEventArgs e) { potentials.Items.Refresh(); } private void Button_Click(object sender, RoutedEventArgs e) { if (potentials.SelectedIndex < 1) return; Data.Move(potentials.SelectedIndex, potentials.SelectedIndex - 1); potentials.Items.Refresh(); } private void Button_Click_1(object sender, RoutedEventArgs e) { if (potentials.SelectedIndex > Data.Count - 2) return; Data.Move(potentials.SelectedIndex, potentials.SelectedIndex + 1); potentials.Items.Refresh(); } string GetNBT() { string nbt = ""; if (range.Value != 4) nbt += "SpawnRange:" + range.Value + ","; if (maxnearby.Value != null) nbt += "MaxNearbyEntities:" + maxnearby.Value + ","; if (requiredrange.Value != null) nbt += "RequiredPlayerRange:" + requiredrange.Value + ","; if (delay.Value != null) nbt += "Delay:" + delay.Value + ","; if (count.Value != 0) nbt += "SpawnCount:" + count.Value + ","; if (mindelay.Value != null) nbt += "MinSpawnDelay:" + mindelay.Value + ","; if (maxdelay.Value != null) nbt += "MaxSpawnDelay:" + maxdelay.Value + ","; if (Data.Count != 0) { nbt += "SpawnPotentials:["; foreach (Potential item in Data) { nbt += "{Weight:" + item.Weight + ",Properties:" + item.NBT + "},"; } nbt = nbt.Substring(0, nbt.Length - 1); nbt += "],"; } if (nbt != "") nbt = "{" + nbt.Substring(0, nbt.Length - 1) + "}"; return nbt; } public string GenerateCommand() { return "/give @p minecraft:mob_spawner 1 0" + GetNBT(); } private void Button_Click_3(object sender, RoutedEventArgs e) { string nbt = GetNBT(); if (nbt != "") nbt = ",tag:{" + nbt + "}"; Tmp.AddCommand("{id:\"mob_spawner\",Count:1,Damage:0" + nbt + "}"); } private void Button_Click_2(object sender, RoutedEventArgs e) { string nbt = GetNBT(); if (nbt == "") nbt = "{}"; Tmp.AddCommand("minecraft:mobspawner-1-" + nbt); } } public class Potential { public int Weight { get; set; } public string NBT { get; set; } } }
using AdminAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AdminAPI.ServiceContract { interface ICurrency_Repository: IDisposable { Task<List<CurrencyMaster>> GetAll(); Task<CurrencyMaster> GetById(int Id); Task<List<CurrencyMaster>> GetAllForBase(); Task Insert(CurrencyMaster currencyMaster); Task Update(CurrencyMaster currencyMaster); Task<bool> Delete(int id); } }
using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using Autofac; using Autofac.Integration.Web; using Autofac.Integration.Mef; using Foundry.Services; using Foundry.Messaging.Infrastructure; using System.ComponentModel.Composition.Hosting; using Foundry.SourceControl; using System.Collections.Generic; using System; using System.Reflection; using System.IO; using Foundry.SourceControl.GitIntegration; using Foundry.Services.Security; using Foundry.Services.SourceControl; using Foundry.Security; using Foundry.Domain; namespace Foundry.Services { public class ServicesModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<SourceControlManager>().As<ISourceControlManager>().PropertiesAutowired(); builder.RegisterType<MembershipService>().As<IMembershipService>().HttpRequestScoped().PropertiesAutowired(); builder.RegisterType<AuthorizationService>().As<IAuthorizationService>().HttpRequestScoped(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameSessionManagerScript : MonoBehaviour { public int MaxLaps = 3; private bool gameOver = false; private void EndGame(){ gameOver = true; } public void NotifyLap(SteeringScript car) { if (!gameOver && car.LapsCompleted >= MaxLaps) { // TODO: still count laps and decide finish order for other cars than winner in 3+ multiplayer EndGame(); } } }
using Uintra.Infrastructure.TypeProviders; namespace Uintra.Features.Notification { public interface INotifierTypeProvider : IEnumTypeProvider { } }
WriterT (Identity ( (), Seq (Assign "arg" (Const (I 10))) ( Seq (Assign "scratch" (Var "arg")) ( Seq (Assign "total" (Const (I 1))) ( Seq (While (Gt (Var "scratch") (Const (I 1))) ( Seq (Assign "total" (Mul (Var "total") (Var "scratch"))) ( Seq (Assign "scratch" (Sub (Var "scratch") (Const (I 1)))) (Print (Var "scratch"))))) (Print (Var "total"))) ) ) ) )
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.Analytics; using System.Collections; using System.Collections.Generic; using System; using System.Linq; using Hakaima; using GoogleMobileAds.Api; public class GameManager : MonoBehaviour { private enum State { Ready, ReadyContinue, Play, BossDefeat, Clear, Continue, TutorialEnd, TutorialHelp, } private class Cell { public int point; public int pointX; public int pointY; public Hakaima.Terrain.Type terrainType; public Hakaima.Obstacle.Type obstacleType; public Hakaima.Enemy.Type enemyType; public Hakaima.Item.Type itemType; public bool isHoleOpen; } private class Score { private const int MAX = 9999999; private int recordScore; private int recordScoreHigh; public int enemy { get; set; } public Dictionary<int, int> bonusList { get; set; } public int timebonus { get; set; } public int high { get { return Mathf.Max (now, recordScoreHigh); } } public int now { get { int s = recordScore; s += enemy; s += bonusList.Sum (obj => obj.Value); s += timebonus; s = Mathf.Max (0, s); s = Mathf.Min (s, MAX); return s; } } public int stage { get { return now - recordScore; } } public int pre { get; set; } public int preHigh { get; set; } public Score (int recordScore, int recordScoreHigh) { this.recordScore = recordScore; this.recordScoreHigh = recordScoreHigh; this.enemy = 0; this.bonusList = new Dictionary<int, int> (); this.bonusList [(int)Bonus.Type.Bonus0] = 0; this.bonusList [(int)Bonus.Type.Bonus1] = 0; this.bonusList [(int)Bonus.Type.Bonus2] = 0; this.bonusList [(int)Bonus.Type.Bonus3] = 0; this.bonusList [(int)Bonus.Type.Bonus4] = 0; this.bonusList [(int)Bonus.Type.Bonus5] = 0; this.bonusList [(int)Bonus.Type.Bonus6] = 0; this.timebonus = 0; this.pre = -1; this.preHigh = -1; } } private class Life { private const int MAX = 99; private int _pre; public int now { get { return MainManager.Instance.life; } set { if (value < 0) value = 0; else if (value > MAX) value = MAX; MainManager.Instance.life = value; } } public int pre { get { return this._pre; } set { this._pre = value; } } public Life (int value) { this.now = value; this.pre = -1; } } private class MyWeapon { private const int MAX = 99; private int _pre; public int now { get { return MainManager.Instance.weapon; } set { if (value < 0) value = 0; else if (value > MAX) value = MAX; MainManager.Instance.weapon = value; } } public int pre { get { return this._pre; } set { this._pre = value; } } public MyWeapon (int value) { this.now = value; this.pre = -1; } } private class RemainingTime { private float _now; private float _pre; public float now { get { return this._now; } set { this._now = value; if (this._now < 0) this._now = 0; } } public float pre { get { return this._pre; } set { this._pre = value; } } public RemainingTime (float value) { this.now = value; this.pre = -1; } } private class OwnerItem { public enum State { NoHave, Have, Use, } public Item.Type type { get; set; } public State state { get; set; } } private class Number { public enum State { None, Action, } public State state { get; private set; } public float time { get; private set; } public float positionX { get; private set; } public float positionY { get; private set; } public bool visible { get; private set; } public Color color { get; private set; } public int value { get; private set; } private float aimDistance; private float aimSpeed; private float startPositionY; public Number () { this.None (); } public void Init (Color color, float aimDistance, float aimSpeed) { this.color = color; this.aimDistance = aimDistance; this.aimSpeed = aimSpeed; } public void Move (float deltaTime, int frameRate) { if (this.state == State.Action) { this.positionY += this.aimSpeed * deltaTime * frameRate; if (this.positionY >= this.startPositionY + this.aimDistance) { this.None (); } } } private void None () { this.state = State.None; this.time = 0; this.visible = false; } public void Action (float positionX, float positionY, int value) { if (this.state == State.None) { this.state = State.Action; this.time = 0; this.positionX = positionX; this.positionY = positionY; this.visible = true; this.value = value; this.startPositionY = positionY; } } } public class ClearPlayer { public Player.Compass compass { get; private set; } public float positionX { get; private set; } public float positionY { get; private set; } public int imageIndex { get; private set; } public float speed { get; private set; } private float imageTime; public void Init (float positionX, float positionY, float speed) { this.compass = Player.Compass.Right; this.positionX = positionX; this.positionY = positionY; this.speed = speed; this.imageIndex = Player.IMAGE_0; } public void Move (float deltaTime, int frameRate) { this.positionX += this.speed; int index = (int)this.imageTime % 4; switch (index) { case 0: this.imageIndex = Player.IMAGE_0; break; case 1: this.imageIndex = Player.IMAGE_1; break; case 2: this.imageIndex = Player.IMAGE_0; break; case 3: this.imageIndex = Player.IMAGE_2; break; } this.imageTime += this.speed * 0.02f; } } private class GroupPlayer { public GameObject gameObject; public GameObject gameObjectSurprise; public GameObject gameObjectLifeup; public GameObject gameObjectParasol; public GameObject gameObjectSweat; public int waitCount; public bool canHoleCycle; public float fallTime; public float invincibleTime; public Chip bathChip; public float bathTime; public Chip hideChip; public float hideTime; public float hoePer = 1; public float lifeTime; public bool isNonStop; public float surpriseTime; public Number lifeup; public float wellEffectTime; public bool isNonStopSound; public bool isParasol; public bool isSweat; } private class GroupEnemy { public enum DieType { None, Tomb, Hole, } public GameObject gameObject; public GameObject gameObjectNotice; public GameObject gameObjectLost; public int waitCount; public float waitTime; public float fallTime; public float angryTime; public float invincibleTime; public Chip bathChip; public float bathTime; public bool isFollow; public float noticeTime; public float lostTime; public DieType dieType; public float dieTime; public bool entrance; public bool isNonStop; public bool isBoss; public int lifeCount; public float wellEffectTime; public int weaponCount; public float weaponStopTime; } private class GroupChip { public GameObject gameObjectTerrain; public GameObject gameObjectHole; public List<GameObject> gameObjectObstacleList; public float holeTime; } private class GroupWeapon { public GameObject gameObject; public GameObject gameObjectImage; } private class GroupItem { public GameObject gameObject; } private class GroupBonus { public GameObject gameObject; public float remainingTime; } private class GroupLight { public GameObject gameObject; } private class GroupNumber { public GameObject gameObject; public GameObject gameObjectText; } private class CollectReady { public GameObject go; public GameObject goStage; public GameObject goDescription; public GameObject goClear; public GameObject goReady; public GameObject goGo; public Color color; public float colorAlphaMax = 200f / 256; } private class CollectPause { public GameObject go; public GameObject goDescription; public GameObject goClear; public GameObject goEncourage; public GameObject goButtonHowTo; public GameObject goButtonBack; public GameObject goButtonMovie; public GameObject goButtonEnd; public GameObject goVolumeOn; public GameObject goVolumeOff; public GameObject goHowTo; public GameObject goHowToImageJp; public GameObject goHowToImageEn; public GameObject goHowToButtonClose; public GameObject goCaution; public GameObject goCautionButtonYes; public GameObject goCautionButtonNo; } private class CollectClear { public GameObject go; public GameObject goTitle; public GameObject goEnemy; public GameObject goEnemyScore; public GameObject goTime; public GameObject goTimeScore; public GameObject goBonus; public Dictionary<int, GameObject> goBonusScoreList; public GameObject goRule; public GameObject goTotal; public GameObject goTotalScore; public GameObject goNextStage; public GameObject goPlayer; public Vector3 positionTitle; public Color color; public Color colorEnemy; public Color colorEnemyScore; public Color colorTime; public Color colorTimeScore; public Color colorBonus; public Dictionary<int, Color> colorBonusScoreList; public Color colorRule; public Color colorTotal; public Color colorTotalScore; public Color colorNextStage; public ClearPlayer player; public int bonusIndex; public float colorAlphaMax = 200f / 256; public bool isAllEnemyDie; } private class CollectContinue { public GameObject go; public GameObject goStage; public GameObject goScore; public GameObject goDescription; public GameObject goPlayer; public GameObject goButtonContinue; public GameObject goButtonMovie; public GameObject goButtonEnd; } private State state; private float time; private int pattern; private GameObject goCover; private GameObject goTouch; private GameObject goMist; private GameObject goTrail; private List<GameObject> goLayerList; private GameObject goOriginEnemy; private GameObject goOriginWeapon; private GameObject goOriginTerrain; private GameObject goOriginHole; private GameObject goOriginObstacle; private GameObject goOriginItem; private GameObject goOriginBonus; private GameObject goOriginLight; private List<Chip> chipList; private Player player; private List<Weapon> playerWeaponList; private List<Enemy> enemyList; private List<Weapon> enemyWeaponList; private List<Item> itemList; private List<Bonus> bonusList; private List<Hakaima.Light> lightList; private List<Item> specialItemList; private List<GroupChip> groupChipList; private GroupPlayer groupPlayer; private List<GroupWeapon> groupPlayerWeaponList; private List<GroupEnemy> groupEnemyList; private List<GroupWeapon> groupEnemyWeaponList; private List<GroupItem> groupItemList; private List<GroupBonus> groupBonusList; private List<GroupLight> groupLightList; private List<GroupItem> groupSpecialItemList; private List<GroupNumber> groupNumberList; private bool isPause; private bool isHowto; private bool isCaution; private Vector3 pauseHowToPosition; private Score score; private Life life; private MyWeapon myWeapon; private RemainingTime remainingTime; private List<OwnerItem> ownerItemList; private List<Number> numberList; private int numberIndex; private GameObject goPause; private GameObject goStage; private GameObject goScore; private GameObject goScoreHigh; private GameObject goPlayer1; private GameObject goLife; private GameObject goMyWeapon; private GameObject goRemainingTime; private GameObject goCompletion; private GameObject goCompletionText; private GameObject goPuaseTwitterButton; private GameObject goContinueTwitterButton; private GameObject goStageClearTwitterButton; private List<GameObject> goOwnerItemList; private List<GameObject> goOwnerItemFrameList; private List<GameObject> goNumberList; private CollectReady collectReady; private CollectPause collectPause; private CollectClear collectClear; private CollectContinue collectContinue; private TitleManager.Catalog help; private GameObject goHelp; private GameObject goHelpPage; private GameObject goHelpPoint; private GameObject goHelpArrowRight; private GameObject goHelpArrowLeft; private bool isTouch; private bool isCommandNoneClick; private Player.Compass playerNextCompass; private int playerNextCommand; public const int PLAYER_NEXT_COMMAND_NONE = 0; public const int PLAYER_NEXT_COMMAND_COMPASS = 1; public const int PLAYER_NEXT_COMMAND_COMPASS_WALK = 2; private int continueCommand; private const int CONTINUE_COMMAND_NONE = 0; private const int CONTINUE_COMMAND_MOVIE = 1; private const int CONTINUE_COMMAND_YES = 2; private const int CONTINUE_COMMAND_NO = 3; private List<Bonus.Type> temporaryBonusTypeList; private Dictionary<Bonus.Type, bool> appearBonusTypeList; private bool isReachBonus6; private int tutorialPlayerIndex; private List<int> tutorialEnemyIndexList; private int lifeupIndex; private const float APPEAR_ENEMY_PERSON_TIME_COEFFICIENT = 3; private float appearEnemyPersonTime; private static List<Cell> keepCellList; private GameObject goDebug; private bool isDebugDamage; private void Awake () { Init (); Create (); } private void Update () { Run (); Draw (); } private void Init () { groupChipList = new List<GroupChip> (); groupPlayer = new GroupPlayer (); groupEnemyList = new List<GroupEnemy> (); groupPlayerWeaponList = new List<GroupWeapon> (); groupEnemyWeaponList = new List<GroupWeapon> (); groupItemList = new List<GroupItem> (); groupBonusList = new List<GroupBonus> (); groupLightList = new List<GroupLight> (); groupSpecialItemList = new List<GroupItem> (); goCover = transform.Find ("UI/Cover").gameObject; goTouch = transform.Find ("Game/Touch").gameObject; goMist = transform.Find ("Game/Mist").gameObject; goTrail = transform.Find ("Game/Trail").gameObject; goLayerList = new List<GameObject> (); goLayerList .Add (transform.Find ("Game/Map/Layer0").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer1").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer2").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer3").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer4").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer5").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer6").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer7").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer8").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer9").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer10").gameObject); goLayerList .Add (transform.Find ("Game/Map/Layer11").gameObject); goPause = transform.Find ("UI/Information/Pause").gameObject; goStage = transform.Find ("UI/Information/Stage").gameObject; goScore = transform.Find ("UI/Information/Score/PlayerScore(Value)").gameObject; goScoreHigh = transform.Find ("UI/Information/Score/HiScore(Value)").gameObject; goPlayer1 = transform.Find ("UI/Information/Score/PlayerScore(Title)").gameObject; goLife = transform.Find ("UI/Information/Life").gameObject; goMyWeapon = transform.Find ("UI/Information/ThrowWepon/Remaining").gameObject; goRemainingTime = transform.Find ("UI/Information/Time").gameObject; goCompletion = transform.Find ("UI/Information/Completion").gameObject; goCompletionText = transform.Find ("UI/Information/Completion/Text").gameObject; goOriginEnemy = transform.Find ("Game/Map/Origin/Enemy").gameObject; goOriginWeapon = transform.Find ("Game/Map/Origin/Weapon").gameObject; goOriginTerrain = transform.Find ("Game/Map/Origin/Terrain").gameObject; goOriginHole = transform.Find ("Game/Map/Origin/Hole").gameObject; goOriginObstacle = transform.Find ("Game/Map/Origin/Obstacle").gameObject; goOriginItem = transform.Find ("Game/Map/Origin/Item").gameObject; goOriginBonus = transform.Find ("Game/Map/Origin/Bonus").gameObject; goOriginLight = transform.Find ("Game/Map/Origin/Light").gameObject; goOwnerItemList = new List<GameObject> (); goOwnerItemList .Add (transform.Find ("UI/Information/OwnerItem/Item0").gameObject); goOwnerItemList .Add (transform.Find ("UI/Information/OwnerItem/Item1").gameObject); goOwnerItemList .Add (transform.Find ("UI/Information/OwnerItem/Item2").gameObject); goOwnerItemList .Add (transform.Find ("UI/Information/OwnerItem/Item3").gameObject); goOwnerItemList .Add (transform.Find ("UI/Information/OwnerItem/Item4").gameObject); goOwnerItemFrameList = new List<GameObject> (); goOwnerItemFrameList .Add (transform.Find ("UI/Information/OwnerItem/Frame0").gameObject); goOwnerItemFrameList .Add (transform.Find ("UI/Information/OwnerItem/Frame1").gameObject); goOwnerItemFrameList .Add (transform.Find ("UI/Information/OwnerItem/Frame2").gameObject); goOwnerItemFrameList .Add (transform.Find ("UI/Information/OwnerItem/Frame3").gameObject); goOwnerItemFrameList .Add (transform.Find ("UI/Information/OwnerItem/Frame4").gameObject); groupPlayer.gameObject = transform.Find ("Game/Map/Origin/Player").gameObject; groupPlayer.gameObjectSurprise = transform.Find ("Game/Map/Num/Surprise").gameObject; groupPlayer.gameObjectLifeup = transform.Find ("Game/Map/Num/Lifeup").gameObject; groupPlayer.gameObjectParasol = transform.Find ("Game/Map/Origin/Player/Parasol").gameObject; groupPlayer.gameObjectSweat = transform.Find ("Game/Map/Origin/Player/Sweat").gameObject; groupNumberList = new List<GroupNumber> (); groupNumberList .Add (new GroupNumber ()); groupNumberList .Add (new GroupNumber ()); groupNumberList .Add (new GroupNumber ()); for (int i = 0; i < groupNumberList.Count; i++) { groupNumberList [i].gameObject = transform.Find ("Game/Map/Num/Num" + i).gameObject; groupNumberList [i].gameObjectText = transform.Find ("Game/Map/Num/Num" + i + "/Text").gameObject; } collectReady = new CollectReady (); collectReady.go = transform.Find ("UI/Logo/Ready").gameObject; collectReady.goStage = collectReady.go.transform.Find ("Stage").gameObject; collectReady.goDescription = collectReady.go.transform.Find ("Description").gameObject; collectReady.goClear = collectReady.go.transform.Find ("Clear").gameObject; collectReady.goReady = collectReady.go.transform.Find ("Ready").gameObject; collectReady.goGo = collectReady.go.transform.Find ("Go").gameObject; collectPause = new CollectPause (); collectPause.go = transform.Find ("UI/Logo/Pause").gameObject; collectPause.goDescription = collectPause.go.transform.Find ("Description").gameObject; collectPause.goClear = collectPause.go.transform.Find ("Clear").gameObject; collectPause.goEncourage = collectPause.go.transform.Find ("Encourage").gameObject; collectPause.goButtonHowTo = collectPause.go.transform.Find ("ButtonHowTo").gameObject; collectPause.goButtonBack = collectPause.go.transform.Find ("ButtonBack").gameObject; collectPause.goButtonMovie = collectPause.go.transform.Find ("ButtonMovie").gameObject; collectPause.goButtonEnd = collectPause.go.transform.Find ("ButtonEnd").gameObject; collectPause.goVolumeOn = collectPause.go.transform.Find ("Volume/On").gameObject; collectPause.goVolumeOff = collectPause.go.transform.Find ("Volume/Off").gameObject; collectPause.goHowTo = collectPause.go.transform.Find ("HowTo").gameObject; collectPause.goHowToImageJp = collectPause.go.transform.Find ("HowTo/Help_jp").gameObject; collectPause.goHowToImageEn = collectPause.go.transform.Find ("HowTo/Help_en").gameObject; collectPause.goHowToButtonClose = collectPause.go.transform.Find ("HowTo/ButtonBack").gameObject; collectPause.goCaution = collectPause.go.transform.Find("Caution").gameObject; collectPause.goCautionButtonYes = collectPause.go.transform.Find("Caution/ButtonYes").gameObject; collectPause.goCautionButtonNo = collectPause.go.transform.Find("Caution/ButtonNo").gameObject; collectClear = new CollectClear (); collectClear.go = transform.Find ("UI/Logo/Clear").gameObject; collectClear.goTitle = collectClear.go.transform.Find ("Title").gameObject; collectClear.goEnemy = collectClear.go.transform.Find ("Enemy").gameObject; collectClear.goEnemyScore = collectClear.go.transform.Find ("EnemyScore").gameObject; collectClear.goTime = collectClear.go.transform.Find ("Time").gameObject; collectClear.goTimeScore = collectClear.go.transform.Find ("TimeScore").gameObject; collectClear.goBonus = collectClear.go.transform.Find ("Bonus").gameObject; collectClear.goRule = collectClear.go.transform.Find ("Rule").gameObject; collectClear.goTotal = collectClear.go.transform.Find ("Total").gameObject; collectClear.goTotalScore = collectClear.go.transform.Find ("TotalScore").gameObject; collectClear.goNextStage = collectClear.go.transform.Find ("NextStage").gameObject; collectClear.goPlayer = collectClear.go.transform.Find ("Player").gameObject; collectClear.goBonusScoreList = new Dictionary<int, GameObject> (); collectClear.goBonusScoreList [(int)Bonus.Type.Bonus0] = collectClear.go.transform.Find ("Bonus0Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus1] = collectClear.go.transform.Find ("Bonus1Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus2] = collectClear.go.transform.Find ("Bonus2Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus3] = collectClear.go.transform.Find ("Bonus3Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus4] = collectClear.go.transform.Find ("Bonus4Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus5] = collectClear.go.transform.Find ("Bonus5Score").gameObject; collectClear.goBonusScoreList [(int)Bonus.Type.Bonus6] = collectClear.go.transform.Find ("Bonus6Score").gameObject; collectClear.colorBonusScoreList = new Dictionary<int, Color> (); collectClear.player = new ClearPlayer (); collectContinue = new CollectContinue (); collectContinue.go = transform.Find ("UI/Logo/Continue").gameObject; collectContinue.goStage = collectContinue.go.transform.Find ("Stage(Value)").gameObject; collectContinue.goScore = collectContinue.go.transform.Find ("Score(Value)").gameObject; collectContinue.goDescription = collectContinue.go.transform.Find ("Description").gameObject; collectContinue.goPlayer = collectContinue.go.transform.Find ("Player").gameObject; collectContinue.goButtonContinue = collectContinue.go.transform.Find ("ButtonContinue").gameObject; collectContinue.goButtonMovie = collectContinue.go.transform.Find ("ButtonMovie").gameObject; collectContinue.goButtonEnd = collectContinue.go.transform.Find ("ButtonEnd").gameObject; goPuaseTwitterButton = collectPause.go.transform.Find ("Twitter").gameObject; goContinueTwitterButton = collectContinue.go.transform.Find ("Twitter").gameObject; goStageClearTwitterButton = collectClear.go.transform.Find ("Twitter").gameObject; goPuaseTwitterButton .GetComponent<Button> ().onClick.AddListener (() => OnTwitter ()); goContinueTwitterButton .GetComponent<Button> ().onClick.AddListener (() => OnTwitter ()); goStageClearTwitterButton .GetComponent<Button> ().onClick.AddListener (() => OnTwitter ()); goStageClearTwitterButton.SetActive (false); goCover.SetActive (true); goOriginEnemy.SetActive (false); goOriginWeapon.SetActive (false); goOriginTerrain.SetActive (false); goOriginHole.SetActive (false); goOriginObstacle.SetActive (false); goOriginItem.SetActive (false); goOriginBonus.SetActive (false); goOriginLight.SetActive (false); collectReady.go.SetActive (false); collectPause.go.SetActive (false); collectClear.go.SetActive (false); collectContinue.go.SetActive (false); goCompletion.SetActive (false); goTrail.GetComponent<TrailRenderer> ().sortingOrder = 1; groupPlayer.lifeup = new Number (); groupPlayer.lifeup.Init (Color.yellow, 100, 3); ownerItemList = new List<OwnerItem> (); ownerItemList.Add (new OwnerItem ()); ownerItemList.Add (new OwnerItem ()); ownerItemList.Add (new OwnerItem ()); ownerItemList.Add (new OwnerItem ()); ownerItemList.Add (new OwnerItem ()); ownerItemList [0].type = Item.Type.Sandal; ownerItemList [1].type = Item.Type.Hoe; ownerItemList [2].type = Item.Type.Stone; ownerItemList [3].type = Item.Type.Amulet; ownerItemList [4].type = Item.Type.Parasol; numberList = new List<Number> (); numberList.Add (new Number ()); numberList.Add (new Number ()); numberList.Add (new Number ()); for (int i = 0; i < numberList.Count; i++) { numberList [i].Init (Color.white, 50, 3); } goTouch.GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.PointerDown) .callback.AddListener (eventData => OnTouchPointerDown ((PointerEventData)eventData)); goTouch.GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.PointerUp) .callback.AddListener (eventData => OnTouchPointerUp ((PointerEventData)eventData)); goTouch.GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.Drag) .callback.AddListener (eventData => OnTouchDrag ((PointerEventData)eventData)); goPause.GetComponent<Button> ().onClick.AddListener (() => OnPause (!isPause)); goOwnerItemList [0].GetComponent<Button> ().onClick.AddListener (() => OnItem (ownerItemList [0])); goOwnerItemList [1].GetComponent<Button> ().onClick.AddListener (() => OnItem (ownerItemList [1])); goOwnerItemList [2].GetComponent<Button> ().onClick.AddListener (() => OnItem (ownerItemList [2])); goOwnerItemList [3].GetComponent<Button> ().onClick.AddListener (() => OnItem (ownerItemList [3])); collectPause.goButtonHowTo .GetComponent<Button> ().onClick.AddListener (() => OnHowTo (true)); collectPause.goButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnPause (false)); collectPause.goButtonMovie .GetComponent<Button> ().onClick.AddListener (() => OnPauseMovie ()); collectPause.goButtonEnd .GetComponent<Button> ().onClick.AddListener (() => OnPauseEnd ()); collectPause.goVolumeOn .GetComponent<Button> ().onClick.AddListener (() => OnVolume (true)); collectPause.goVolumeOff .GetComponent<Button> ().onClick.AddListener (() => OnVolume (false)); collectPause.goHowToButtonClose .GetComponent<Button> ().onClick.AddListener (() => OnHowTo (false)); collectContinue.goButtonContinue .GetComponent<Button> ().onClick.AddListener (() => OnContinue (CONTINUE_COMMAND_YES)); collectContinue.goButtonMovie .GetComponent<Button> ().onClick.AddListener (() => OnContinueMovie ()); collectContinue.goButtonEnd .GetComponent<Button> ().onClick.AddListener (() => OnContinue (CONTINUE_COMMAND_NO)); collectPause.goCautionButtonYes .GetComponent<Button> ().onClick.AddListener (() => OnCaution(true)); collectPause.goCautionButtonNo .GetComponent<Button> ().onClick.AddListener (() => OnCaution(false)); pauseHowToPosition = collectPause.goButtonHowTo.transform.position; OnVolume(SoundManager.Instance.GetMute ()); ShowPauseMovie(); goDebug = transform.Find ("UI/Debug").gameObject; goDebug.transform.Find ("Damage").GetComponent<Button> ().onClick.AddListener (() => OnDebugDamageClick ()); goDebug.transform.Find ("PreStage").GetComponent<Button> ().onClick.AddListener (() => { keepCellList = null; MainManager.Instance.PreStage (); }); goDebug.transform.Find ("NextStage").GetComponent<Button> ().onClick.AddListener (() => { keepCellList = null; MainManager.Instance.NextStage (life.now, myWeapon.now); }); OnDebugDamageClick (); if (!MainManager.Instance.isDebug) { goDebug.SetActive (false); } } private void Create () { score = new Score (MainManager.Instance.score, MainManager.Instance.scoreHigh); life = new Life (MainManager.Instance.life); myWeapon = new MyWeapon (MainManager.Instance.weapon); remainingTime = new RemainingTime (MainManager.Instance.isTutorial ? 0 : Data.GetStageData (MainManager.Instance.stage).limitTime); if (MainManager.Instance.isTutorial) keepCellList = null; keepCellList = keepCellList ?? GetCellList (); List<Cell> cellList = keepCellList; chipList = new List<Chip> (); for (int i = 0; i < cellList.Count; i++) { Cell cell = cellList [i]; Chip chip = new Chip (); chip.Init (cell.pointX, cell.pointY); chipList.Add (chip); GroupChip groupChip = new GroupChip (); groupChip.gameObjectObstacleList = new List<GameObject> (); groupChipList.Add (groupChip); chip.terrain.Set (cell.terrainType); groupChip.gameObjectTerrain = Instantiate (goOriginTerrain) as GameObject; groupChip.gameObjectTerrain.transform.SetParent (goOriginTerrain.transform.parent); if (cell.isHoleOpen) chip.hole.Open (); groupChip.gameObjectHole = Instantiate (goOriginHole) as GameObject; groupChip.gameObjectHole.transform.SetParent (goOriginHole.transform.parent); if (cell.obstacleType != Obstacle.Type.None) { Obstacle obstacle = new Obstacle (); obstacle.Set (cell.obstacleType); chip.obstacleList.Add (obstacle); GameObject goObstacle = Instantiate (goOriginObstacle) as GameObject; goObstacle.transform.SetParent (goOriginObstacle.transform.parent); groupChip.gameObjectObstacleList.Add (goObstacle); if (cell.obstacleType == Obstacle.Type.Tomb) { if (UnityEngine.Random.Range (0, 2) == 0) { obstacle = new Obstacle (); obstacle.Set (Obstacle.Type.Stupa); chip.obstacleList.Insert (chip.obstacleList.Count - 1, obstacle); goObstacle = Instantiate (goOriginObstacle) as GameObject; goObstacle.transform.SetParent (goOriginObstacle.transform.parent); groupChip.gameObjectObstacleList.Insert (groupChip.gameObjectObstacleList.Count - 1, goObstacle); } } else if (cell.obstacleType == Obstacle.Type.CartRight) { if (UnityEngine.Random.Range (0, 2) == 0) { chip.obstacleList.Find (obj => obj.type == Obstacle.Type.CartRight).Set (Obstacle.Type.CartLeft); } } } } player = new Player (); player.Init (Data.PLAYER_START_POINT_X, Data.PLAYER_START_POINT_Y - 1); enemyList = new List<Enemy> (); for (int i = 0; i < cellList.Count; i++) { Cell cell = cellList [i]; if (cell.enemyType != Enemy.Type.None) { Enemy enemy = new Enemy (); enemy.Init (cell.enemyType, cell.pointX, cell.pointY, Data.GetEnemyData (cell.enemyType).isFly); enemyList.Add (enemy); GroupEnemy groupEnemy = new GroupEnemy (); groupEnemy.gameObject = Instantiate (goOriginEnemy) as GameObject; groupEnemy.gameObject.transform.SetParent (goOriginEnemy.transform.parent); groupEnemyList.Add (groupEnemy); groupEnemy.gameObjectNotice = groupEnemy.gameObject.transform.Find ("Notice").gameObject; groupEnemy.gameObjectLost = groupEnemy.gameObject.transform.Find ("Lost").gameObject; groupEnemy.isBoss = enemy.type == Enemy.Type.Tengu; groupEnemy.lifeCount = Data.GetEnemyData (enemy.type).lifeCount; } } playerWeaponList = new List<Weapon> (); enemyWeaponList = new List<Weapon> (); itemList = new List<Item> (); for (int i = 0; i < cellList.Count; i++) { Cell cell = cellList [i]; if (cell.itemType != Item.Type.None) { Item item = new Item (); item.Init (cell.itemType, cell.pointX, cell.pointY); itemList.Add (item); GroupItem groupItem = new GroupItem (); groupItem.gameObject = Instantiate (goOriginItem) as GameObject; groupItem.gameObject.transform.SetParent (goOriginItem.transform.parent); groupItemList.Add (groupItem); } } bonusList = new List<Bonus> (); lightList = new List<Hakaima.Light> (); for (int i = 0; i < cellList.Count; i++) { Cell cell = cellList [i]; if (cell.obstacleType == Obstacle.Type.Tower) { Hakaima.Light light = new Hakaima.Light (); light.Init (cell.pointX, cell.pointY, Data.LAYER_9); lightList.Add (light); GroupLight groupLight = new GroupLight (); groupLight.gameObject = Instantiate (goOriginLight) as GameObject; groupLight.gameObject.transform.SetParent (goOriginLight.transform.parent); groupLightList.Add (groupLight); } } specialItemList = new List<Item> (); goStage.GetComponent<Text> ().text = string.Format ("STAGE {0}", MainManager.Instance.stage + 1); float darkness = Data.GetStageData (MainManager.Instance.stage).darkness; goTouch.GetComponent<Image> ().color = Color.black * darkness; float mist = Data.GetStageData (MainManager.Instance.stage).mist * 0.2f; goMist.GetComponent<ParticleSystem> ().startColor = new Color (1, 1, 1, mist); if (mist == 0) goMist.SetActive (false); string clearText; if (enemyList.Exists (obj => obj.type == Enemy.Type.Tengu)) { clearText = Language.sentence [Language.GAME_READY_APPEAR_BOSS]; } else if (enemyList.Exists (obj => obj.type == Enemy.Type.Person)) { clearText = Language.sentence [Language.GAME_READY_APPEAR_SAMURAI]; } else { clearText = Language.sentence [Language.GAME_READY_APPEAR_NONE]; } collectReady.goStage.GetComponent<Text> ().text = string.Format ("STAGE {0}", MainManager.Instance.stage + 1); collectReady.goDescription.GetComponent<Text> ().text = Language.sentence [Language.GAME_READY_CONDITION]; collectPause.goDescription.GetComponent<Text> ().text = Language.sentence [Language.GAME_READY_CONDITION]; collectReady.goClear.GetComponent<Text> ().text = clearText; collectPause.goClear.GetComponent<Text> ().text = clearText; collectPause.goEncourage.GetComponent<Text> ().text = Language.sentence [Language.GAME_PAUSE]; collectContinue.goDescription.GetComponent<Text> ().text = Language.sentence [Language.GAME_CONTINUE]; if (Language.sentence == Language.sentenceEn) { collectReady.goClear.GetComponent<Text> ().alignment = TextAnchor.UpperCenter; collectPause.goClear.GetComponent<Text> ().alignment = TextAnchor.UpperCenter; } groupPlayer.lifeTime = 180; temporaryBonusTypeList = new List<Bonus.Type> (); appearBonusTypeList = new Dictionary<Bonus.Type, bool> (); appearBonusTypeList [Bonus.Type.Bonus0] = false; appearBonusTypeList [Bonus.Type.Bonus1] = false; appearBonusTypeList [Bonus.Type.Bonus2] = false; appearBonusTypeList [Bonus.Type.Bonus3] = false; appearBonusTypeList [Bonus.Type.Bonus4] = false; appearBonusTypeList [Bonus.Type.Bonus5] = false; appearBonusTypeList [Bonus.Type.Bonus6] = false; lifeupIndex = Data.GetLifeupIndex (score.now); tutorialEnemyIndexList = new List<int> (); for (int i = 0; i < Data.tutorialStageData.enemyDataListList.Count; i++) { tutorialEnemyIndexList.Add (0); } if (MainManager.Instance.isTutorial) { goPause.SetActive (false); goStage.GetComponent<Text> ().text = "TUTORIAL"; FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVNET_START_TUTORIAL); } if (MainManager.Instance.isTutorial) { Analytics.CustomEvent ("tutorial", new Dictionary<string, object> { {"done", true}, }); } else { Analytics.CustomEvent ("stage_start", new Dictionary<string, object> { {"stage_" + (MainManager.Instance.stage + 1), true}, }); } if (!MainManager.Instance.isTutorial) { if (MainManager.Instance.isExtraItemSandal) { ownerItemList.Find (obj => obj.type == Item.Type.Sandal).state = OwnerItem.State.Have; } if (MainManager.Instance.isExtraItemHoe) { ownerItemList.Find (obj => obj.type == Item.Type.Hoe).state = OwnerItem.State.Have; } if (MainManager.Instance.isExtraItemStone) { ownerItemList.Find (obj => obj.type == Item.Type.Stone).state = OwnerItem.State.Have; } if (MainManager.Instance.isExtraItemParasol) { ownerItemList.Find (obj => obj.type == Item.Type.Parasol).state = OwnerItem.State.Have; } } ResourceManager.Instance.SetTerrian (); ResourceManager.Instance.SetObstacle (); ResourceManager.Instance.SetHole (); ResourceManager.Instance.SetItem (); ResourceManager.Instance.SetBonus (); ResourceManager.Instance.SetAllEnemy (); ResourceManager.Instance.SetPlayer (MainManager.Instance.selectCharacter); transform.Find ("UI/Information/Face").GetComponent<Image>().sprite = ResourceManager.Instance.spriteUpperPlayer; SetWeapon (); goPlayer1.GetComponent<Text> ().text = Language.sentenceEn [Language.CHARANAME_SAMURAI + MainManager.Instance.selectCharacter]; } private void SetWeapon() { GameObject goWeapon = transform.Find ("UI/Information/ThrowWepon/Wepon").gameObject; if (MainManager.Instance.IsWeaponCharacter(MainManager.Instance.selectCharacter)) { goWeapon.transform.parent.gameObject.SetActive (true); goWeapon.GetComponent<Image> ().sprite = ResourceManager.Instance.spritePlayerWeapon; } else { goWeapon.transform.parent.gameObject.SetActive (false); } goMyWeapon.GetComponent<Text> ().text = string.Format ("{0:00}", myWeapon.now).ToString (); } private void Run () { bool loop; do { loop = false; switch (state) { case State.Ready: { if (MainManager.Instance.isTutorial) { if (pattern == 0) { if (time == 0) { goCover.SetActive (false); player.Walk (Player.Compass.Top, true); player.SetSpeed (Data.SPEED_3); player.SetImageCoefficient (Data.GetPlayerImageCoefficient (Hakaima.Terrain.Type.Soil)); player.SetBlind (true, Color.cyan); enemyList.ForEach (obj => obj.SetBlind (true, Color.white)); //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide (); goStageClearTwitterButton.SetActive (false); } else if (time >= 2) { player.SetBlind (false); enemyList.ForEach (obj => obj.SetBlind (false)); state = State.Play; time = 0; loop = true; } if (player.state == Player.State.Wait) if (player.compass == Player.Compass.Top) player.Walk (Player.Compass.Bottom, false); } } else { if (pattern == 0) { if (time == 0) { goCover.SetActive (false); collectReady.go.SetActive (true); collectReady.goReady.SetActive (true); collectReady.goGo.SetActive (false); collectReady.color = Color.black; collectReady.color.a = collectReady.colorAlphaMax; enemyList.ForEach (obj => obj.SetBlind (true, Color.white)); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_START); //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide (); FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_STAGE + MainManager.Instance.stage); } else if (time >= 4) { pattern = 1; time = 0; } } if (pattern == 1) { if (time == 0) { collectReady.goReady.SetActive (false); collectReady.goGo.SetActive (true); player.Walk (Player.Compass.Top, true); player.SetSpeed (Data.SPEED_3); player.SetImageCoefficient (Data.GetPlayerImageCoefficient (Hakaima.Terrain.Type.Soil)); player.SetBlind (true, Color.cyan); } else if (time >= 1) { if (player.state == Player.State.Wait) { collectReady.go.SetActive (false); player.SetBlind (false); enemyList.ForEach (obj => obj.SetBlind (false)); state = State.Play; time = 0; loop = true; } } if (player.state == Player.State.Wait) if (player.compass == Player.Compass.Top) player.Walk (Player.Compass.Bottom, false); collectReady.color = Color.black; collectReady.color.a = Mathf.Lerp (collectReady.colorAlphaMax, 0, 2 * time - 1); } } player.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); enemyList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); chipList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); } break; case State.ReadyContinue: { if (pattern == 0) { if (time == 0) { collectReady.go.SetActive (true); collectReady.goReady.SetActive (true); collectReady.goGo.SetActive (false); collectReady.color = Color.black; collectReady.color.a = collectReady.colorAlphaMax; SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_START); } else if (time >= 3) { pattern = 1; time = 0; } } if (pattern == 1) { if (time == 0) { collectReady.goReady.SetActive (false); collectReady.goGo.SetActive (true); } else if (time >= 1) { collectReady.go.SetActive (false); state = State.Play; time = 0; loop = true; } collectReady.color = Color.black; collectReady.color.a = Mathf.Lerp (collectReady.colorAlphaMax, 0, 2 * time - 1); } } break; case State.Play: { CheckBackKey (); if (isPause) { return; } if (time == 0) { playerNextCompass = player.compass; playerNextCommand = PLAYER_NEXT_COMMAND_NONE; SoundManager.Instance.StopSe (); if (!MainManager.Instance.isTutorial) { bool isBoss = groupEnemyList.Exists (obj => obj.isBoss); if (isBoss) { SoundManager.Instance.PlayBgm (SoundManager.BgmName.BGM_BOSS); } else { switch (Data.GetStageData (MainManager.Instance.stage).sound) { case 0: SoundManager.Instance.PlayBgm (SoundManager.BgmName.BGM_GAME_0); break; case 1: SoundManager.Instance.PlayBgm (SoundManager.BgmName.BGM_GAME_1); break; case 2: SoundManager.Instance.PlayBgm (SoundManager.BgmName.BGM_GAME_2); break; } } } } switch (player.state) { case Player.State.Wait: { if (MainManager.Instance.isTutorial) { if (tutorialPlayerIndex < Data.tutorialStageData.playerDataList.Count) { if (Data.tutorialStageData.playerDataList [tutorialPlayerIndex].waitTime > 0) { Data.tutorialStageData.playerDataList [tutorialPlayerIndex].waitTime -= Time.deltaTime; goCompletion.SetActive (true); goCompletionText.GetComponent<Text> ().text = Data.tutorialStageData.playerDataList [tutorialPlayerIndex].waitText; return; } playerNextCompass = Data.tutorialStageData.playerDataList [tutorialPlayerIndex].compass; playerNextCommand = Data.tutorialStageData.playerDataList [tutorialPlayerIndex].command; isCommandNoneClick = Data.tutorialStageData.playerDataList [tutorialPlayerIndex].isCommandNoneClick; groupPlayer.canHoleCycle = Data.tutorialStageData.playerDataList [tutorialPlayerIndex].canHoleCycle; tutorialPlayerIndex++; goCompletion.SetActive (false); } } else { if (!isTouch) { groupPlayer.canHoleCycle = false; playerNextCompass = player.compass; playerNextCommand = PLAYER_NEXT_COMMAND_NONE; } if (groupPlayer.isNonStop) { groupPlayer.isNonStop = false; playerNextCompass = player.compass; playerNextCommand = PLAYER_NEXT_COMMAND_COMPASS_WALK; } } Chip chip = chipList [player.pointX + player.pointY * Data.LENGTH_X]; Chip chip1 = null; switch (playerNextCompass) { case Player.Compass.Right: if (player.pointX + 1 < Data.LENGTH_X) chip1 = chipList [(player.pointX + 1) + player.pointY * Data.LENGTH_X]; break; case Player.Compass.Left: if (player.pointX - 1 >= 0) chip1 = chipList [(player.pointX - 1) + player.pointY * Data.LENGTH_X]; break; case Player.Compass.Top: if (player.pointY + 1 < Data.LENGTH_Y) chip1 = chipList [player.pointX + (player.pointY + 1) * Data.LENGTH_X]; break; case Player.Compass.Bottom: if (player.pointY - 1 >= 0) chip1 = chipList [player.pointX + (player.pointY - 1) * Data.LENGTH_X]; break; } GroupChip groupChip = groupChipList [chip.pointX + chip.pointY * Data.LENGTH_X]; GroupChip groupChip1 = chip1 != null ? groupChipList [chip1.pointX + chip1.pointY * Data.LENGTH_X] : null; switch (playerNextCommand) { case PLAYER_NEXT_COMMAND_NONE: { OwnerItem useOwnerItem = ownerItemList.Find (obj => obj.type == Item.Type.Stone); if (useOwnerItem.state == OwnerItem.State.Use) { if (chip1 != null) if (Data.GetTerrainData (chip1.terrain.type).isThrough) if (chip1.hole.state == Hole.State.Close) if (chip1.obstacleList.Count == 0) { useOwnerItem.state = OwnerItem.State.NoHave; MainManager.Instance.isExtraItemStone = false; Obstacle obstacle = new Obstacle (); obstacle.Set (Obstacle.Type.Stone); chip1.obstacleList.Add (obstacle); GameObject goObstacle = Instantiate (goOriginObstacle) as GameObject; goObstacle.transform.SetParent (goOriginObstacle.transform.parent); groupChip1.gameObjectObstacleList.Add (goObstacle); } } if (groupPlayer.canHoleCycle) { if (chip1 != null) if (Data.GetTerrainData (chip1.terrain.type).isDigging) if (playerWeaponList.Count == 0) if (chip1.obstacleList.Count == 0) { int point = chip1.pointX + chip1.pointY * Data.LENGTH_X; groupChipList [point].holeTime += Data.DELTA_TIME * groupPlayer.hoePer; if (groupChipList [point].holeTime >= 0.3f) { groupChipList [point].holeTime = 0; chip1.hole.Cycle (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_HOLE); if (chip1.hole.state == Hole.State.Open || chip1.hole.state == Hole.State.Close) { groupPlayer.canHoleCycle = false; switch (chip1.hole.state) { case Hole.State.Open: Item item = itemList.Find (obj => obj.pointX == chip1.pointX && obj.pointY == chip1.pointY); if (item != null) item.Appear (); else { Item.Type itemType = Item.Type.None; float ran = UnityEngine.Random.value * 100; if (ran < MainManager.Instance.GetTicketItemPercent ()) itemType = Item.Type.Ticket; else if (ran < MainManager.Instance.GetTicketItemPercent () + MainManager.Instance.GetWeaponItemPercent () && MainManager.Instance.IsWeaponCharacter (MainManager.Instance.selectCharacter)) itemType = Item.Type.Weapon; if (itemType != Item.Type.None) { Item specialItem = new Item (); specialItem.Init (itemType, chip1.pointX, chip1.pointY); specialItem.Appear (); specialItemList.Add (specialItem); GroupItem groupSpecialItem = new GroupItem (); groupSpecialItem.gameObject = Instantiate (goOriginItem) as GameObject; groupSpecialItem.gameObject.transform.SetParent (goOriginItem.transform.parent); groupSpecialItemList.Add (groupSpecialItem); } } PlayerPrefs.SetInt (Data.RECORD_HOLE_OPEN, PlayerPrefs.GetInt (Data.RECORD_HOLE_OPEN) + 1); break; case Hole.State.Close: switch (chip1.terrain.type) { case Hakaima.Terrain.Type.Grass: case Hakaima.Terrain.Type.Ice: chip1.terrain.Set (Hakaima.Terrain.Type.Soil); break; } PlayerPrefs.SetInt (Data.RECORD_HOLE_CLOSE, PlayerPrefs.GetInt (Data.RECORD_HOLE_CLOSE) + 1); break; } } } } } if (isCommandNoneClick) { if (chip1 != null) { if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.Stone)) { chip1.obstacleList.Find (obj => obj.type == Obstacle.Type.Stone).Set (Obstacle.Type.Tomb); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_MAKE); } else if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.Bale)) { bool isBale = chip.obstacleList.Count == 0; if (!isBale) { List<Obstacle.Type> list = new List<Obstacle.Type> (); list.Add (Obstacle.Type.TombCollapseEnd); list.Add (Obstacle.Type.TombPieceEnd); list.Add (Obstacle.Type.Bucket); list.Add (Obstacle.Type.FallTombPieceEnd); isBale = chip.obstacleList.TrueForAll (obj => list.Exists (type => type == obj.type)); } if (isBale) { player.SetPoint (chip1.pointX, chip1.pointY); Obstacle obstacle = chip1.obstacleList.Find (obj => obj.type == Obstacle.Type.Bale); chip.obstacleList.Add (obstacle); chip1.obstacleList.Remove (obstacle); GameObject goObstacle = groupChip1.gameObjectObstacleList [0]; groupChip.gameObjectObstacleList.Add (goObstacle); groupChip1.gameObjectObstacleList.Remove (goObstacle); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CHANGE); } } else if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.Tomb)) { Func<Chip, List<Chip>, List<Chip>> getTombChipList = null; getTombChipList = (Chip tombChip, List<Chip> tombChipList) => { tombChipList.Add (tombChip); Chip nextChip = null; switch (playerNextCompass) { case Player.Compass.Right: if (tombChip.pointX + 1 < Data.LENGTH_X) nextChip = chipList [(tombChip.pointX + 1) + tombChip.pointY * Data.LENGTH_X]; break; case Player.Compass.Left: if (tombChip.pointX - 1 >= 0) nextChip = chipList [(tombChip.pointX - 1) + tombChip.pointY * Data.LENGTH_X]; break; case Player.Compass.Top: if (tombChip.pointY + 1 < Data.LENGTH_Y) nextChip = chipList [tombChip.pointX + (tombChip.pointY + 1) * Data.LENGTH_X]; break; case Player.Compass.Bottom: if (tombChip.pointY - 1 >= 0) nextChip = chipList [tombChip.pointX + (tombChip.pointY - 1) * Data.LENGTH_X]; break; } if (nextChip == null) { tombChipList.Add (tombChipList [tombChipList.Count - 1]); } else { if (nextChip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Tomb)) { return getTombChipList (nextChip, tombChipList); } tombChipList.Add (nextChip); } return tombChipList; }; List<Chip> list = new List<Chip> (); list = getTombChipList (chip1, list); for (int i = 0; i < list.Count; i++) { int point = list [i].pointX + list [i].pointY * Data.LENGTH_X; if (i == list.Count - 1) { bool isPiece = true; if (chipList [point].terrain.type == Hakaima.Terrain.Type.River) isPiece = false; if (chipList [point].obstacleList.Exists (obj => obj.type == Obstacle.Type.Well)) isPiece = false; if (chipList [point].obstacleList.Exists (obj => obj.type == Obstacle.Type.Bathtub)) isPiece = false; if (chipList [point].obstacleList.Exists (obj => obj.type == Obstacle.Type.Stockpile)) isPiece = false; Obstacle obstacle = new Obstacle (); obstacle.Set (isPiece ? Obstacle.Type.TombPiece : Obstacle.Type.FallTombPiece); chipList [point].obstacleList.Add (obstacle); GameObject goObstacle = Instantiate (goOriginObstacle) as GameObject; goObstacle.transform.SetParent (goOriginObstacle.transform.parent); groupChipList [point].gameObjectObstacleList.Add (goObstacle); if (chipList [point].hole.state != Hole.State.Close) chipList [point].hole.Close (); } else { chipList [point].obstacleList.Find (obj => obj.type == Obstacle.Type.Tomb).Set (Obstacle.Type.TombCollapse); if (chipList [point].obstacleList.Exists (obj => obj.type == Obstacle.Type.Stupa)) { int index = chipList [point].obstacleList.FindIndex (obj => obj.type == Obstacle.Type.Stupa); Destroy (groupChipList [point].gameObjectObstacleList [index]); chipList [point].obstacleList.RemoveAt (index); groupChipList [point].gameObjectObstacleList.RemoveAt (index); } PlayerPrefs.SetInt (Data.RECORD_TOMB_COLLAPSE, PlayerPrefs.GetInt (Data.RECORD_TOMB_COLLAPSE) + 1); } } if (!appearBonusTypeList [Bonus.Type.Bonus4]) { int remain = (int)(Data.GetStageData (MainManager.Instance.stage).obstacleTypeList [Obstacle.Type.Tomb] * 0.2f); if (chipList.Sum (obj => obj.obstacleList.Count (obj2 => obj2.type == Obstacle.Type.Tomb)) < remain) { appearBonusTypeList [Bonus.Type.Bonus4] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus4); } } if (list.Count - 1 >= 5) { isReachBonus6 = true; } if (list.Count > 0) SoundManager.Instance.PlaySe (SoundManager.SeName.SE_KNOCK); if (PlayerPrefs.GetInt (Data.RECORD_MAX_TOMB_COLLAPSE) < list.Count - 1) { PlayerPrefs.SetInt (Data.RECORD_MAX_TOMB_COLLAPSE, list.Count - 1); } } else { if (canThrough) if (MainManager.Instance.IsWeaponCharacter (MainManager.Instance.selectCharacter) && myWeapon.now > 0) { Weapon weapon = new Weapon (); weapon.Init ((Weapon.Compass)player.compass, player.positionX, player.positionY); playerWeaponList.Add (weapon); GroupWeapon groupWeapon = new GroupWeapon (); groupWeapon.gameObject = Instantiate (goOriginWeapon) as GameObject; groupWeapon.gameObjectImage = groupWeapon.gameObject.transform.Find ("Image").gameObject; groupPlayerWeaponList.Add (groupWeapon); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_TOUCH); myWeapon.now--; goMyWeapon.GetComponent<Text> ().text = string.Format ("{0:00}", myWeapon.now).ToString (); } } } } } break; case PLAYER_NEXT_COMMAND_COMPASS: { player.Walk (playerNextCompass, false); } break; case PLAYER_NEXT_COMMAND_COMPASS_WALK: { bool isWalk = false; if (chip1 != null) { if (Data.GetTerrainData (chip1.terrain.type).isThrough && chip1.obstacleList.TrueForAll (obj => Data.GetObstacleData (obj.type).isThrough)) isWalk = true; if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartRight) && playerNextCompass != Player.Compass.Right) isWalk = false; if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartLeft) && playerNextCompass != Player.Compass.Left) isWalk = false; } player.Walk (playerNextCompass, isWalk); } break; } } break; } for (int i = 0; i < enemyList.Count; i++) { Enemy enemy = enemyList [i]; GroupEnemy groupEnemy = groupEnemyList [i]; switch (enemy.state) { case Enemy.State.Wait: { if (groupEnemy.waitTime == 0) { if (groupEnemy.bathTime == 0) { bool isNext = false; if (MainManager.Instance.isTutorial) { isNext = true; } else { if (IsEnemyNextCommand (enemy)) isNext = true; if (groupEnemy.isNonStop) isNext = true; } if (isNext) { Enemy.Compass enemyNextCompass = GetEnemyNextCompass (chipList, player, enemy, groupEnemy); if (MainManager.Instance.isTutorial) { if (tutorialEnemyIndexList [i] < Data.tutorialStageData.enemyDataListList [i].Count) { enemyNextCompass = Data.tutorialStageData.enemyDataListList [i] [tutorialEnemyIndexList [i]].compass; tutorialEnemyIndexList [i]++; } } else { if (groupEnemy.isNonStop) { groupEnemy.isNonStop = false; enemyNextCompass = enemy.compass; } } Chip chip1 = null; switch (enemyNextCompass) { case Enemy.Compass.Right: if (enemy.pointX + 1 < Data.LENGTH_X) chip1 = chipList [(enemy.pointX + 1) + enemy.pointY * Data.LENGTH_X]; break; case Enemy.Compass.Left: if (enemy.pointX - 1 >= 0) chip1 = chipList [(enemy.pointX - 1) + enemy.pointY * Data.LENGTH_X]; break; case Enemy.Compass.Top: if (enemy.pointY + 1 < Data.LENGTH_Y) chip1 = chipList [enemy.pointX + (enemy.pointY + 1) * Data.LENGTH_X]; break; case Enemy.Compass.Bottom: if (enemy.pointY - 1 >= 0) chip1 = chipList [enemy.pointX + (enemy.pointY - 1) * Data.LENGTH_X]; break; } bool isWalk = false; if (chip1 != null) { if (Data.GetTerrainData (chip1.terrain.type).isThrough && chip1.obstacleList.TrueForAll (obj => Data.GetObstacleData (obj.type).isThrough)) isWalk = true; if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartRight) && enemyNextCompass != Enemy.Compass.Right) isWalk = false; if (chip1.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartLeft) && enemyNextCompass != Enemy.Compass.Left) isWalk = false; if (chip1.hole.state == Hole.State.Open && Data.GetEnemyData (enemy.type).isAvoidHole) isWalk = false; if (Data.GetEnemyData (enemy.type).isFly) isWalk = true; } enemy.Walk (enemyNextCompass, isWalk); if (groupEnemy.isBoss) { if (groupEnemy.weaponStopTime == 0) { bool isWeapon = false; if (remainingTime.now == 0) { isWeapon = true; } else { if (groupEnemy.lifeCount == 1) isWeapon = groupEnemy.weaponCount % 3 != 0; else isWeapon = groupEnemy.weaponCount % 2 == 0; } if (isWeapon) { Weapon weapon = new Weapon (); weapon.Init ((Weapon.Compass)enemy.compass, enemy.positionX, enemy.positionY); enemyWeaponList.Add (weapon); GroupWeapon groupWeapon = new GroupWeapon (); groupWeapon.gameObject = Instantiate (goOriginWeapon) as GameObject; groupWeapon.gameObjectImage = groupWeapon.gameObject.transform.Find ("Image").gameObject; groupEnemyWeaponList.Add (groupWeapon); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_TOUCH); } groupEnemy.weaponCount++; if (groupEnemy.weaponCount >= 20) { groupEnemy.weaponCount = 0; groupEnemy.weaponStopTime = 2; } } } } else { groupEnemy.waitTime = 1; } if (groupEnemy.entrance) { groupEnemy.entrance = false; enemy.SetBlind (false); } } } break; } } } for (int i = 0; i < ownerItemList.Count; i++) { OwnerItem ownerItem = ownerItemList [i]; switch (ownerItem.type) { case Item.Type.Sandal: if (ownerItem.state == OwnerItem.State.Have) { ownerItem.state = OwnerItem.State.Use; } break; case Item.Type.Hoe: if (ownerItem.state == OwnerItem.State.Have) { ownerItem.state = OwnerItem.State.Use; groupPlayer.hoePer = 1.5f; } break; case Item.Type.Stone: if (ownerItem.state == OwnerItem.State.Use) ownerItem.state = OwnerItem.State.Have; break; case Item.Type.Amulet: if (ownerItem.state == OwnerItem.State.Have) { ownerItem.state = OwnerItem.State.Use; player.SetBlind (true, Color.white); groupPlayer.invincibleTime = 10f; } break; case Item.Type.Parasol: if (ownerItem.state == OwnerItem.State.Have) { ownerItem.state = OwnerItem.State.Use; groupPlayer.isParasol = true; } break; } } isCommandNoneClick = false; chipList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); player.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); enemyList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); playerWeaponList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); enemyWeaponList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); bonusList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); numberList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); groupPlayer.lifeup.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); groupPlayer.isSweat = false; canThrough = true; for (int i = 0; i < enemyList.Count; i++) { Enemy enemy = enemyList [i]; GroupEnemy groupEnemy = groupEnemyList [i]; if (groupEnemy.entrance) continue; switch (enemy.state) { case Enemy.State.Wait: case Enemy.State.Walk: case Enemy.State.Fall: { bool isDie = false; bool isDamage = false; switch (enemy.state) { case Enemy.State.Wait: { Chip chip = chipList [enemy.pointX + enemy.pointY * Data.LENGTH_X]; if (groupEnemy.waitCount == 0) { if (!Data.GetEnemyData (enemy.type).isFly) { if (chip.terrain.type == Hakaima.Terrain.Type.Ice) { groupEnemy.isNonStop = true; } if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartRight)) { chip.obstacleList.Find (obj => obj.type == Obstacle.Type.CartRight).Set (Obstacle.Type.CartLeft); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartLeft)) { chip.obstacleList.Find (obj => obj.type == Obstacle.Type.CartLeft).Set (Obstacle.Type.CartRight); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Bathtub)) { groupEnemy.isNonStop = false; groupEnemy.bathChip = chip; groupEnemy.bathTime = 10; enemy.InSide (); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Well)) { groupEnemy.isNonStop = false; List<Chip> chipAimList = chipList.FindAll (obj => obj.obstacleList.Exists (obj2 => obj2.type == Obstacle.Type.Well) && obj != chip); if (chipAimList.Count > 0) { int index = UnityEngine.Random.Range (0, chipAimList.Count); enemy.SetPoint (chipAimList [index].pointX, chipAimList [index].pointY); enemy.SetBlind (true, Color.cyan); groupEnemy.wellEffectTime = 1f; } } } } if (chip.hole.state == Hole.State.Open) { if (!Data.GetEnemyData (enemy.type).isFly) { groupEnemy.fallTime = Data.GetEnemyData (enemy.type).fallTime; enemy.Fall (); enemy.SetBlind (false); } } groupEnemy.waitCount++; } break; case Enemy.State.Walk: { groupEnemy.waitCount = 0; } break; case Enemy.State.Fall: { Chip chip = chipList [enemy.pointX + enemy.pointY * Data.LENGTH_X]; switch (chip.hole.state) { case Hole.State.Close: { isDie = true; groupEnemy.lifeCount = 0; groupEnemy.dieType = GroupEnemy.DieType.Hole; groupEnemy.dieTime = 0; PlayerPrefs.SetInt (Data.RECORD_ENEMY_DIE_TO_HOLE, PlayerPrefs.GetInt (Data.RECORD_ENEMY_DIE_TO_HOLE) + 1); } break; } } break; } if (groupEnemy.waitTime > 0) { groupEnemy.waitTime -= Data.DELTA_TIME; if (groupEnemy.waitTime <= 0) { groupEnemy.waitTime = 0; } } if (groupEnemy.fallTime > 0) { groupEnemy.fallTime -= Data.DELTA_TIME; if (groupEnemy.fallTime <= 0) { groupEnemy.fallTime = 0; groupEnemy.angryTime = Data.GetEnemyData (enemy.type).angryTime; enemy.Climb (); enemy.SetBlind (true, Color.red); } } if (groupEnemy.angryTime > 0) { groupEnemy.angryTime -= Data.DELTA_TIME; if (groupEnemy.angryTime <= 0) { groupEnemy.angryTime = 0; enemy.SetBlind (false); } } if (groupEnemy.invincibleTime > 0) { groupEnemy.invincibleTime -= Data.DELTA_TIME; if (groupEnemy.invincibleTime <= 0) { groupEnemy.invincibleTime = 0; enemy.SetBlind (groupEnemy.angryTime > 0, Color.red); } } if (groupEnemy.bathTime > 0) { groupEnemy.bathTime -= Data.DELTA_TIME; if (groupEnemy.bathTime <= 0 || groupEnemy.bathChip.obstacleList.Exists (obj => obj.type != Obstacle.Type.Bathtub)) { groupEnemy.bathTime = 0; groupEnemy.bathChip = null; enemy.OutSide (); } } if (groupEnemy.wellEffectTime > 0) { groupEnemy.wellEffectTime -= Data.DELTA_TIME; if (groupEnemy.wellEffectTime <= 0) { groupEnemy.wellEffectTime = 0; enemy.SetBlind (groupEnemy.angryTime > 0, Color.red); enemy.SetBlind (groupEnemy.invincibleTime > 0, Color.white); } } if (groupEnemy.noticeTime > 0) { groupEnemy.noticeTime -= Data.DELTA_TIME; if (groupEnemy.noticeTime <= 0) { groupEnemy.noticeTime = 0; } } if (groupEnemy.lostTime > 0) { groupEnemy.lostTime -= Data.DELTA_TIME; if (groupEnemy.lostTime <= 0) { groupEnemy.lostTime = 0; } } if (groupEnemy.weaponStopTime > 0) { groupEnemy.weaponStopTime -= Data.DELTA_TIME; if (groupEnemy.weaponStopTime <= 0) { groupEnemy.weaponStopTime = 0; } } if (groupEnemy.isFollow) { if (!MainManager.Instance.isTutorial) groupPlayer.isSweat = true; } { int pointX = Mathf.FloorToInt ((enemy.positionX + enemy.size / 2) / enemy.size); int pointY = Mathf.FloorToInt ((enemy.positionY + enemy.size / 2) / enemy.size); Chip chip = chipList [pointX + pointY * Data.LENGTH_X]; enemy.SetSpeed (Data.GetEnemySpeed (enemy.type, chip.terrain.type, groupEnemy.angryTime > 0, groupEnemy.isFollow, !MainManager.Instance.isTutorial && remainingTime.now == 0)); enemy.SetImageCoefficient (Data.GetEnemyImageCoefficient (enemy.type, chip.terrain.type)); if (groupEnemy.invincibleTime == 0) { if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.TombPiece || obj.type == Obstacle.Type.TombCollapse || obj.type == Obstacle.Type.FallTombPiece)) { groupEnemy.lifeCount--; if (groupEnemy.lifeCount == 0) { isDie = true; groupEnemy.dieType = GroupEnemy.DieType.Tomb; groupEnemy.dieTime = 0; PlayerPrefs.SetInt (Data.RECORD_ENEMY_DIE_TO_TOMB, PlayerPrefs.GetInt (Data.RECORD_ENEMY_DIE_TO_TOMB) + 1); } else { isDamage = true; } } } } for (int j = 0; j < playerWeaponList.Count;) { Weapon weapon = playerWeaponList [j]; if (Math.Abs (weapon.positionX - enemy.positionX) < weapon.size * weapon.scaleX && Math.Abs (weapon.positionY - enemy.positionY) < weapon.size * weapon.scaleY) { groupEnemy.lifeCount--; if (groupEnemy.lifeCount == 0) { isDie = true; groupEnemy.dieType = GroupEnemy.DieType.Tomb; groupEnemy.dieTime = 0; } else { isDamage = true; } Destroy (groupPlayerWeaponList [j].gameObject); playerWeaponList.RemoveAt (j); groupPlayerWeaponList.RemoveAt (j); continue; } j++; } if (isDie) { if (groupEnemy.isBoss) { state = State.BossDefeat; time = 0; pattern = 0; loop = true; } else { enemy.Die (); } if (!MainManager.Instance.isTutorial) { int s = Data.GetEnemyScore (enemy.type, groupEnemy.angryTime > 0); if (s > 0) { score.enemy += s; numberList [numberIndex].Action (enemy.positionX, enemy.positionY, s); numberIndex = (numberIndex + 1) % numberList.Count; } int index = Data.GetLifeupIndex (score.now); if (lifeupIndex < index) { lifeupIndex++; life.now++; groupPlayer.lifeup.Action (player.positionX, player.positionY, 1); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_1UP); } } if (enemy.type == Enemy.Type.Person) { if (MainManager.Instance.stage < 5) { appearEnemyPersonTime = APPEAR_ENEMY_PERSON_TIME_COEFFICIENT * 1; } else if (MainManager.Instance.stage < 10) { appearEnemyPersonTime = APPEAR_ENEMY_PERSON_TIME_COEFFICIENT * (1 + (int)(UnityEngine.Random.value * 2)); } else { appearEnemyPersonTime = APPEAR_ENEMY_PERSON_TIME_COEFFICIENT * (2 + (int)(UnityEngine.Random.value * 2)); } } } else if (isDamage) { groupEnemy.invincibleTime = 5; enemy.SetBlind (true, Color.white); if (groupEnemy.isBoss) if (groupEnemy.lifeCount == 1) groupEnemy.angryTime = Data.GetStageData (MainManager.Instance.stage).limitTime; } } break; case Enemy.State.Damage: { if (enemy.isEnd) { enemy.Die (); } } break; case Enemy.State.Die: groupEnemy.dieTime += Data.DELTA_TIME; break; } } switch (player.state) { case Player.State.Wait: case Player.State.Walk: case Player.State.Fall: { switch (player.state) { case Player.State.Wait: { Chip chip = chipList [player.pointX + player.pointY * Data.LENGTH_X]; if (groupPlayer.waitCount == 0) { if (chip.terrain.type == Hakaima.Terrain.Type.Ice) { groupPlayer.isNonStop = true; } if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartRight)) { chip.obstacleList.Find (obj => obj.type == Obstacle.Type.CartRight).Set (Obstacle.Type.CartLeft); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.CartLeft)) { chip.obstacleList.Find (obj => obj.type == Obstacle.Type.CartLeft).Set (Obstacle.Type.CartRight); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Well)) { // groupPlayer.isNonStop = true; List<Chip> chipAimList = chipList.FindAll (obj => obj.obstacleList.Exists (obj2 => obj2.type == Obstacle.Type.Well) && obj != chip); if (chipAimList.Count > 0) { int index = UnityEngine.Random.Range (0, chipAimList.Count); player.SetPoint (chipAimList [index].pointX, chipAimList [index].pointY); player.SetBlind (true, Color.cyan); player.Walk (Player.Compass.Bottom, false); groupPlayer.wellEffectTime = 1f; SoundManager.Instance.PlaySe (SoundManager.SeName.SE_WARP); } } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Bathtub)) { if (groupPlayer.isNonStop) { groupPlayer.isNonStop = false; groupPlayer.bathChip = chip; groupPlayer.bathTime = Data.GetPlayerData ().bathTime; player.InSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Stockpile)) { if (groupPlayer.isNonStop) { groupPlayer.isNonStop = false; groupPlayer.hideChip = chip; groupPlayer.hideTime = Data.GetPlayerData ().hideTime; player.InSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } } if (groupPlayer.isNonStop) { if (!groupPlayer.isNonStopSound) { groupPlayer.isNonStopSound = true; SoundManager.Instance.PlaySe (SoundManager.SeName.SE_SLIP); } } else { groupPlayer.isNonStopSound = false; } } else if (groupPlayer.waitCount == 1) { if (groupPlayer.invincibleTime == 0) { if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Bathtub)) { groupPlayer.bathChip = chip; groupPlayer.bathTime = Data.GetPlayerData ().bathTime; player.InSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } else if (chip.obstacleList.Exists (obj => obj.type == Obstacle.Type.Stockpile)) { groupPlayer.hideChip = chip; groupPlayer.hideTime = Data.GetPlayerData ().hideTime; player.InSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GIMMICK); } if (chip.hole.state == Hole.State.Open) { groupPlayer.fallTime = Data.GetPlayerData ().fallTime; player.Fall (); PlayerPrefs.SetInt (Data.RECORD_HOLE_FALL, PlayerPrefs.GetInt (Data.RECORD_HOLE_FALL) + 1); } } groupPlayer.isNonStopSound = false; } groupPlayer.waitCount++; } break; case Player.State.Walk: { groupPlayer.waitCount = 0; } break; } if (groupPlayer.invincibleTime == 0) { if (groupPlayer.bathTime == 0) { if (groupPlayer.hideTime == 0) { if (isDebugDamage) { for (int i = 0; i < enemyList.Count; i++) { Enemy enemy = enemyList [i]; GroupEnemy groupEnemy = groupEnemyList [i]; if (enemy.state == Enemy.State.Wait || enemy.state == Enemy.State.Walk) if (groupEnemy.bathTime == 0) if (Math.Abs (enemy.positionX - player.positionX) < player.size * 0.7f && Math.Abs (enemy.positionY - player.positionY) < player.size * 0.7f) { player.Damage (); ownerItemList.Find (obj => obj.type == Item.Type.Sandal).state = OwnerItem.State.NoHave; ownerItemList.Find (obj => obj.type == Item.Type.Hoe).state = OwnerItem.State.NoHave; ownerItemList.Find (obj => obj.type == Item.Type.Parasol).state = OwnerItem.State.NoHave; MainManager.Instance.isExtraItemSandal = false; MainManager.Instance.isExtraItemHoe = false; MainManager.Instance.isExtraItemParasol = false; groupPlayer.hoePer = 1; groupPlayer.isParasol = false; SoundManager.Instance.PlaySe (SoundManager.SeName.SE_BUMP); } } for (int i = 0; i < enemyWeaponList.Count; i++) { Weapon weapon = enemyWeaponList [i]; if (Math.Abs (weapon.positionX - player.positionX) < weapon.size * weapon.scaleX && Math.Abs (weapon.positionY - player.positionY) < weapon.size * weapon.scaleY) { player.Damage (); ownerItemList.Find (obj => obj.type == Item.Type.Sandal).state = OwnerItem.State.NoHave; ownerItemList.Find (obj => obj.type == Item.Type.Hoe).state = OwnerItem.State.NoHave; ownerItemList.Find (obj => obj.type == Item.Type.Parasol).state = OwnerItem.State.NoHave; MainManager.Instance.isExtraItemSandal = false; MainManager.Instance.isExtraItemHoe = false; MainManager.Instance.isExtraItemParasol = false; groupPlayer.hoePer = 1; groupPlayer.isParasol = false; SoundManager.Instance.PlaySe (SoundManager.SeName.SE_BUMP); } } } } } } if (groupPlayer.fallTime > 0) { groupPlayer.fallTime -= Data.DELTA_TIME; if (groupPlayer.fallTime <= 0) { groupPlayer.fallTime = 0; player.Climb (); } } if (groupPlayer.invincibleTime > 0) { groupPlayer.invincibleTime -= Data.DELTA_TIME; if (groupPlayer.invincibleTime <= 0) { groupPlayer.invincibleTime = 0; player.SetBlind (false); ownerItemList.Find (obj => obj.type == Item.Type.Amulet).state = OwnerItem.State.NoHave; } } if (groupPlayer.bathTime > 0) { groupPlayer.bathTime -= Data.DELTA_TIME; if (groupPlayer.bathTime <= 0 || player.state != Player.State.Wait) { groupPlayer.bathTime = 0; groupPlayer.bathChip.obstacleList.Find (obj => obj.type == Obstacle.Type.Bathtub).Set (Obstacle.Type.BathtubCollapse); groupPlayer.bathChip = null; groupPlayer.invincibleTime = 10f; player.SetBlind (true, Color.white); player.OutSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_BREAK); } } if (groupPlayer.hideTime > 0) { groupPlayer.hideTime -= Data.DELTA_TIME; if (groupPlayer.hideTime <= 0 || player.state != Player.State.Wait) { groupPlayer.hideTime = 0; groupPlayer.hideChip.obstacleList.Find (obj => obj.type == Obstacle.Type.Stockpile).Set (Obstacle.Type.StockpileCollapse); groupPlayer.hideChip = null; player.OutSide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_BREAK); } } if (groupPlayer.wellEffectTime > 0) { groupPlayer.wellEffectTime -= Data.DELTA_TIME; if (groupPlayer.wellEffectTime <= 0) { groupPlayer.wellEffectTime = 0; player.SetBlind (groupPlayer.invincibleTime > 0, Color.white); } } if (groupPlayer.lifeTime > 0) { groupPlayer.lifeTime -= Data.DELTA_TIME; if (groupPlayer.lifeTime <= 0) { groupPlayer.lifeTime = 0; if (!appearBonusTypeList [Bonus.Type.Bonus5]) { appearBonusTypeList [Bonus.Type.Bonus5] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus5); } } } if (groupPlayer.surpriseTime > 0) { groupPlayer.surpriseTime -= Data.DELTA_TIME; if (groupPlayer.surpriseTime <= 0) { groupPlayer.surpriseTime = 0; } } for (int i = 0; i < itemList.Count;) { Item item = itemList [i]; if (item.visible) { OwnerItem ownerItem = ownerItemList.Find (obj => obj.type == item.type); if (ownerItem.state == OwnerItem.State.NoHave) { if (Math.Abs (item.positionX - player.positionX) < player.size && Math.Abs (item.positionY - player.positionY) < player.size) { Destroy (groupItemList [i].gameObject); ownerItem.state = OwnerItem.State.Have; itemList.RemoveAt (i); groupItemList.RemoveAt (i); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_GOT); PlayerPrefs.SetInt (Data.RECORD_ITEM_GET, PlayerPrefs.GetInt (Data.RECORD_ITEM_GET) + 1); continue; } } } i++; } for (int i = 0; i < specialItemList.Count;) { Item specialItem = specialItemList [i]; if (Math.Abs (specialItem.positionX - player.positionX) < player.size && Math.Abs (specialItem.positionY - player.positionY) < player.size) { Destroy (groupSpecialItemList [i].gameObject); specialItemList.RemoveAt (i); groupSpecialItemList.RemoveAt (i); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_GOT); switch (specialItem.type) { case Item.Type.Ticket: MainManager.Instance.AddTicket (); break; case Item.Type.Weapon: MainManager.Instance.AddWeapon (); break; } continue; } i++; } for (int i = 0; i < bonusList.Count;) { Bonus bonus = bonusList [i]; if (Math.Abs (bonus.positionX - player.positionX) < player.size && Math.Abs (bonus.positionY - player.positionY) < player.size) { Destroy (groupBonusList [i].gameObject); bonusList.RemoveAt (i); groupBonusList.RemoveAt (i); int s = Data.GetBonusData (bonus.type).score; score.bonusList [(int)bonus.type] += s; numberList [numberIndex].Action (bonus.positionX, bonus.positionY, s); numberIndex = (numberIndex + 1) % numberList.Count; int index = Data.GetLifeupIndex (score.now); if (lifeupIndex < index) { lifeupIndex++; life.now++; groupPlayer.lifeup.Action (player.positionX, player.positionY, 1); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_1UP); } SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_GOT); PlayerPrefs.SetInt (Data.RECORD_BONUS_GET, PlayerPrefs.GetInt (Data.RECORD_BONUS_GET) + 1); continue; } i++; } { int pointX = Mathf.FloorToInt ((player.positionX + player.size / 2) / player.size); int pointY = Mathf.FloorToInt ((player.positionY + player.size / 2) / player.size); Chip chip = chipList [pointX + pointY * Data.LENGTH_X]; bool isSandal = ownerItemList.Find (obj => obj.type == Item.Type.Sandal).state == OwnerItem.State.Use; player.SetSpeed (Data.GetPlayerSpeed (chip.terrain.type, isSandal)); player.SetImageCoefficient (Data.GetPlayerImageCoefficient (chip.terrain.type)); } if (MainManager.Instance.isTutorial) { if (tutorialPlayerIndex == Data.tutorialStageData.playerDataList.Count) { state = State.TutorialEnd; time = 0; pattern = 0; loop = true; } } else { bool isBoss = groupEnemyList.Exists (obj => obj.isBoss); if (isBoss) { remainingTime.now -= Data.DELTA_TIME; if (remainingTime.now == 0) { goRemainingTime.GetComponent<Text> ().color = Color.red; } } else { if (enemyList.FindAll (obj => obj.type != Enemy.Type.Person).TrueForAll (obj => obj.state == Enemy.State.Die)) { if (numberList.TrueForAll (obj => obj.state == Number.State.None)) { collectClear.goTitle.GetComponent<Text> ().text = "STAGE CLEAR !"; collectClear.isAllEnemyDie = true; state = State.Clear; time = 0; pattern = 0; loop = true; SoundManager.Instance.StopBgm (); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_CLEAR); FirebaseAnalyticsManager.Instance.LogScreen (Data.FIREBASE_SCREEN_STAGECLEAR + MainManager.Instance.stage.ToString ()); //if (ShowAdsBanner (15)) { // FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_STAGECLEAR_BANNER_ADS); //} } } else { remainingTime.now -= Data.DELTA_TIME; if (remainingTime.now == 0) { collectClear.goTitle.GetComponent<Text> ().text = "GOT CLEAR AWAY!"; state = State.Clear; time = 0; pattern = 0; loop = true; SoundManager.Instance.StopBgm (); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_CLEAR_TIME0); FirebaseAnalyticsManager.Instance.LogScreen (Data.FIREBASE_SCREEN_STAGECLEAR_RUN + MainManager.Instance.stage.ToString ()); //if (ShowAdsBanner (20)) { // FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_STAGECLEAR_BANNER_ADS); //} } } } } } break; case Player.State.Damage: { if (player.isEnd) { if (life.now == 0) { state = State.Continue; time = 0; loop = true; MainManager.Instance.ShowInterstitialNoMovie(); } else { life.now--; player.Rise (); player.SetBlind (true, Color.white); groupPlayer.invincibleTime = 5f; groupPlayer.lifeTime = 0; } PlayerPrefs.SetInt (Data.RECORD_DAMAGE, PlayerPrefs.GetInt (Data.RECORD_DAMAGE) + 1); } groupPlayer.surpriseTime = 0; } break; } for (int i = 0; i < playerWeaponList.Count;) { Weapon weapon = playerWeaponList [i]; bool isEnd = false; if (weapon.isEnd) { isEnd = true; } { int pointX = Mathf.FloorToInt ((weapon.positionX + weapon.size / 2) / weapon.size); int pointY = Mathf.FloorToInt ((weapon.positionY + weapon.size / 2) / weapon.size); if (pointX < 0 || pointX == Data.LENGTH_X) { isEnd = true; } else if (pointY < 0 || pointY == Data.LENGTH_Y) { isEnd = true; } else { Chip chip = chipList [pointX + pointY * Data.LENGTH_X]; if (chip.obstacleList.Exists (obj => !Data.GetObstacleData (obj.type).isThrough)) isEnd = true; } } if (isEnd) { Destroy (groupPlayerWeaponList [i].gameObject); playerWeaponList.RemoveAt (i); groupPlayerWeaponList.RemoveAt (i); continue; } i++; } for (int i = 0; i < enemyWeaponList.Count;) { Weapon weapon = enemyWeaponList [i]; bool isEnd = false; if (weapon.isEnd) { isEnd = true; } { int pointX = Mathf.FloorToInt ((weapon.positionX + weapon.size / 2) / weapon.size); int pointY = Mathf.FloorToInt ((weapon.positionY + weapon.size / 2) / weapon.size); // 画面外になったら即終了 2018.9.19 iwasaki. if (chipList.Count <= (pointX + pointY * Data.LENGTH_X) || (pointX + pointY * Data.LENGTH_X) < 0) { isEnd = true; } else { Chip chip = chipList [pointX + pointY * Data.LENGTH_X]; if (chip.obstacleList.Exists (obj => !Data.GetObstacleData (obj.type).isThrough)) isEnd = true; } } if (isEnd) { Destroy (groupEnemyWeaponList [i].gameObject); enemyWeaponList.RemoveAt (i); groupEnemyWeaponList.RemoveAt (i); continue; } i++; } if (groupEnemyList.Exists (obj => obj.dieType != GroupEnemy.DieType.None && obj.dieTime == 0)) { if (groupEnemyList.Count (obj => obj.dieType != GroupEnemy.DieType.None && obj.dieTime <= 30) >= 5) { if (!appearBonusTypeList [Bonus.Type.Bonus0]) { appearBonusTypeList [Bonus.Type.Bonus0] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus0); } } if (groupEnemyList.Count (obj => obj.dieType == GroupEnemy.DieType.Tomb && obj.dieTime <= 15) >= 3) { if (!appearBonusTypeList [Bonus.Type.Bonus1]) { appearBonusTypeList [Bonus.Type.Bonus1] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus1); } } if (groupEnemyList.Count (obj => obj.dieType == GroupEnemy.DieType.Hole && obj.dieTime <= 30) >= 3) { if (!appearBonusTypeList [Bonus.Type.Bonus2]) { appearBonusTypeList [Bonus.Type.Bonus2] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus2); } } if (groupEnemyList.Count (obj => obj.dieType != GroupEnemy.DieType.None && obj.dieTime == 0) >= 2) { if (!appearBonusTypeList [Bonus.Type.Bonus3]) { appearBonusTypeList [Bonus.Type.Bonus3] = true; temporaryBonusTypeList.Add (Bonus.Type.Bonus3); } } if (groupEnemyList.Count (obj => obj.dieType == GroupEnemy.DieType.Tomb && obj.dieTime == 0) >= 1) { if (!appearBonusTypeList [Bonus.Type.Bonus6]) { appearBonusTypeList [Bonus.Type.Bonus6] = true; if (isReachBonus6) temporaryBonusTypeList.Add (Bonus.Type.Bonus6); } } } for (int i = 0; i < temporaryBonusTypeList.Count; i++) { List<Chip> bonusChipList = chipList.FindAll (obj => Data.GetTerrainData (obj.terrain.type).isThrough && obj.obstacleList.Count == 0); for (int j = 0; j < bonusList.Count; j++) { bonusChipList = bonusChipList.FindAll (obj => !(obj.pointX == bonusList [j].pointX && obj.pointY == bonusList [j].pointY)); } if (bonusChipList.Count > 0) { Chip chip = bonusChipList [UnityEngine.Random.Range (0, bonusChipList.Count)]; Bonus bonus = new Bonus (); bonus.Init (temporaryBonusTypeList [i], chip.pointX, chip.pointY); bonusList.Add (bonus); GroupBonus groupBonus = new GroupBonus (); groupBonus.gameObject = Instantiate (goOriginBonus) as GameObject; groupBonus.remainingTime = 20; groupBonusList.Add (groupBonus); PlayerPrefs.SetInt (Data.RECORD_BONUS_APPEAR, PlayerPrefs.GetInt (Data.RECORD_BONUS_APPEAR) + 1); } } temporaryBonusTypeList.Clear (); isReachBonus6 = false; for (int i = 0; i < bonusList.Count;) { groupBonusList [i].remainingTime -= Data.DELTA_TIME; if (groupBonusList [i].remainingTime <= 0) { Destroy (groupBonusList [i].gameObject); bonusList.RemoveAt (i); groupBonusList.RemoveAt (i); continue; } else if (groupBonusList [i].remainingTime <= 5) { if (!bonusList [i].blind) bonusList [i].SetBlind (true); } i++; } if (appearEnemyPersonTime > 0) { int appearIndex = (int)(appearEnemyPersonTime / APPEAR_ENEMY_PERSON_TIME_COEFFICIENT); appearEnemyPersonTime -= Data.DELTA_TIME; if (appearEnemyPersonTime < 0) appearEnemyPersonTime = 0; if (appearIndex != (int)(appearEnemyPersonTime / APPEAR_ENEMY_PERSON_TIME_COEFFICIENT)) { Enemy enemy = new Enemy (); int startX = Data.PLAYER_START_POINT_X; if (chipList [Data.PLAYER_START_POINT_X].obstacleList.Count > 0) { if (chipList [Data.PLAYER_START_POINT_X + 1].obstacleList.Count == 0) startX = Data.PLAYER_START_POINT_X + 1; else if (chipList [Data.PLAYER_START_POINT_X - 1].obstacleList.Count == 0) startX = Data.PLAYER_START_POINT_X - 1; } enemy.Init (Enemy.Type.Person, startX, Data.PLAYER_START_POINT_Y - 1, Data.GetEnemyData (Enemy.Type.Person).isFly); enemy.Walk (Enemy.Compass.Top, true); enemy.SetSpeed (Data.GetEnemySpeed (enemy.type, Hakaima.Terrain.Type.Soil, false, false, false)); enemy.SetImageCoefficient (Data.GetEnemyImageCoefficient (enemy.type, Hakaima.Terrain.Type.Soil)); enemy.SetBlind (true, Color.white); enemyList.Add (enemy); GroupEnemy groupEnemy = new GroupEnemy (); groupEnemy.gameObject = Instantiate (goOriginEnemy) as GameObject; groupEnemy.gameObject.transform.SetParent (goOriginEnemy.transform.parent); groupEnemyList.Add (groupEnemy); groupEnemy.gameObjectNotice = groupEnemy.gameObject.transform.Find ("Notice").gameObject; groupEnemy.gameObjectLost = groupEnemy.gameObject.transform.Find ("Lost").gameObject; groupEnemy.lifeCount = Data.GetEnemyData (enemy.type).lifeCount; groupEnemy.entrance = true; groupPlayer.surpriseTime = 1.5f; } } } break; case State.BossDefeat: { Enemy enemy = null; for (int i = 0; i < enemyList.Count; i++) { if (groupEnemyList [i].isBoss) { enemy = enemyList [i]; } } if (time == 0) { enemy.Damage (); } enemy.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); if (enemy.isEnd) { enemy.Die (); collectClear.goTitle.GetComponent<Text> ().text = "STAGE CLEAR !"; state = State.Clear; time = 0; pattern = 0; loop = true; SoundManager.Instance.StopBgm (); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_CLEAR); FirebaseAnalyticsManager.Instance.LogScreen (Data.FIREBASE_SCREEN_STAGECLEAR + MainManager.Instance.stage.ToString ()); } } break; case State.Clear: { bool loop2; do { loop2 = false; if (pattern == 0) { if (time == 0) { collectClear.go.SetActive (true); collectClear.goBonus.SetActive (!score.bonusList.ToList ().TrueForAll (obj => obj.Value == 0)); int pos = 0; foreach (Bonus.Type type in Enum.GetValues (typeof(Bonus.Type))) { if (type == Bonus.Type.None) continue; if (score.bonusList [(int)type] == 0) { collectClear.goBonusScoreList [(int)type].SetActive (false); continue; } collectClear.goBonusScoreList [(int)type].transform.localPosition = new Vector3 (0, -20 - 80 * pos); pos++; } collectClear.positionTitle = Vector3.zero; collectClear.goRule.transform.localPosition = new Vector3 (0, -40 - 80 * pos); collectClear.goTotal.transform.localPosition = collectClear.goRule.transform.localPosition + new Vector3 (0, -100); collectClear.goTotalScore.transform.localPosition = collectClear.goTotal.transform.localPosition; collectClear.goNextStage.transform.localPosition = collectClear.goTotal.transform.localPosition + new Vector3 (0, -180); collectClear.goNextStage.GetComponent<Text> ().text = groupEnemyList.Exists (obj => obj.isBoss) ? "GO TO THE PRINCESS" : "NEXT STAGE"; Color color = Color.white; color.a = 0; collectClear.colorEnemy = color; collectClear.colorEnemyScore = color; collectClear.colorTime = color; collectClear.colorTimeScore = color; collectClear.colorBonus = color; collectClear.colorRule = color; collectClear.colorTotal = color; collectClear.colorTotalScore = color; collectClear.colorNextStage = color; foreach (Bonus.Type type in Enum.GetValues (typeof(Bonus.Type))) { if (type == Bonus.Type.None) continue; collectClear.colorBonusScoreList [(int)type] = color; } collectClear.player.Init (-700, -700, Data.SPEED_16); PlayerPrefs.SetInt (Data.RECORD_CLEAR + MainManager.Instance.stage, 1); PlayerPrefs.SetFloat (Data.RECORD_CLEAR_TIME + MainManager.Instance.stage, Mathf.Max (remainingTime.now, PlayerPrefs.GetInt (Data.RECORD_CLEAR_TIME + MainManager.Instance.stage))); } else if (time <= 1) { } else { float aimTime = 2; float value = 1 / (aimTime - 1) * time - 1; value = Mathf.Min (value, 1); collectClear.positionTitle = new Vector3 (0, -500 * value * (value - 2)); collectClear.color = Color.black; collectClear.color.a = Mathf.Lerp (0, collectClear.colorAlphaMax, value); if (time >= aimTime) { pattern = 1; time = 0; //MainManager.Instance.nendAdBanner.Show (); MainManager.Instance.bannerView.Show (); // これが連続で呼ばれている?. goStageClearTwitterButton.SetActive (true); } } } if (pattern == 1) { Color color = Color.white; color.a = Mathf.Lerp (0, 1, 2 * time); collectClear.colorEnemy = color; collectClear.colorEnemyScore = color; if (time >= 0.5f) { pattern = 2; time = 0; } } if (pattern == 2) { Color color = Color.white; color.a = Mathf.Lerp (0, 1, 2 * time); collectClear.colorTime = color; collectClear.colorTimeScore = color; if (time >= 0.5f) { pattern = 3; time = 0; } } if (pattern == 3) { if (remainingTime.now == 0) { pattern = 4; time = 0; collectClear.bonusIndex = (int)Bonus.Type.Bonus0; } else { remainingTime.now--; score.timebonus += (int)(Data.FROM_TIME_TO_SCORE_COEFFICIENT * (0.5f * (MainManager.Instance.stage + 1) + 1)); int index = Data.GetLifeupIndex (score.now); if (lifeupIndex < index) { lifeupIndex++; life.now++; SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_1UP); } } } if (pattern == 4) { if (time == 0) { while (true) { if (collectClear.bonusIndex > (int)Bonus.Type.Bonus6) { pattern = 5; break; } if (score.bonusList [collectClear.bonusIndex] == 0) { collectClear.bonusIndex++; continue; } break; } } if (collectClear.bonusIndex <= (int)Bonus.Type.Bonus6) { Color color = Color.white; color.a = Mathf.Lerp (0, 1, 2 * time); if (collectClear.colorBonus.a < color.a) collectClear.colorBonus = color; collectClear.colorBonusScoreList [collectClear.bonusIndex] = color; if (time >= 0.5f) { time = 0; collectClear.bonusIndex++; loop2 = true; } } } if (pattern == 5) { Color color = Color.white; color.a = Mathf.Lerp (0, 1, 2 * time); collectClear.colorRule = color; collectClear.colorTotal = color; collectClear.colorTotalScore = color; if (time >= 0.5f) { pattern = 10; time = 0; } } if (pattern == 10) { if (time == 0) { while (remainingTime.now > 0) { remainingTime.now--; score.timebonus += (int)(Data.FROM_TIME_TO_SCORE_COEFFICIENT * (0.5f * (MainManager.Instance.stage + 1) + 1)); int index = Data.GetLifeupIndex (score.now); if (lifeupIndex < index) { lifeupIndex++; life.now++; SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_1UP); } } Color color = Color.white; collectClear.colorEnemy = color; collectClear.colorEnemyScore = color; collectClear.colorTime = color; collectClear.colorTimeScore = color; collectClear.colorBonus = color; collectClear.colorRule = color; collectClear.colorTotal = color; collectClear.colorTotalScore = color; foreach (Bonus.Type type in Enum.GetValues (typeof(Bonus.Type))) { if (type == Bonus.Type.None) continue; collectClear.colorBonusScoreList [(int)type] = color; } //MainManager.Instance.nendAdBanner.Show (); MainManager.Instance.bannerView.Show (); goStageClearTwitterButton.SetActive (true); } if (time >= 1) { pattern = 11; time = 0; } } if (pattern == 11) { if (time == 0) { player.Vanish (); } Color color = Color.white; color.a = ((int)(time * 2) % 5 == 4) ? 0 : 1; collectClear.colorNextStage = color; if (collectClear.player.positionX < 700) collectClear.player.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); } } while (loop2); } break; case State.Continue: { if (time == 0) { collectContinue.go.SetActive (true); collectContinue.goStage.GetComponent<Text> ().text = string.Format ("{0}", MainManager.Instance.stage + 1); collectContinue.goScore.GetComponent<Text> ().text = score.now.ToString (); collectContinue.goPlayer.GetComponent<Image> ().sprite = ResourceManager.Instance.GetContinuePlayerSprite (MainManager.Instance.selectCharacter); continueCommand = CONTINUE_COMMAND_NONE; SoundManager.Instance.StopBgm (); SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_GAMEOVER); FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_GAMEOVER); //MainManager.Instance.nendAdBanner.Show (); MainManager.Instance.bannerView.Show (); if (ShowAdsBanner (15)) { FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_GAMEOVER_BANNER_ADS); } } LifeUpForAds (); switch (continueCommand) { case CONTINUE_COMMAND_MOVIE: { collectContinue.go.SetActive (false); state = State.ReadyContinue; time = 0; pattern = 0; loop = true; MainManager.Instance.donePauseMovie = false; ShowPauseMovie(); player.Rise (); player.SetBlind (true, Color.white); groupPlayer.invincibleTime = 5f; remainingTime.now = Data.GetStageData (MainManager.Instance.stage).limitTime; //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide (); } break; case CONTINUE_COMMAND_YES: { // コンティニュー時のライフを指定の数に(3) life.now = Data.CONTINUE_LIFE; MainManager.Instance.CurrentStage (life.now, 0); MainManager.Instance.donePauseMovie = false; ShowPauseMovie(); } break; case CONTINUE_COMMAND_NO: { MainManager.Instance.Title (); MainManager.Instance.donePauseMovie = false; ShowPauseMovie(); } break; } } break; case State.TutorialEnd: { if (pattern == 0) { if (time == 0) { player.Walk (Player.Compass.Top, true); player.SetSpeed (Data.SPEED_3); player.SetImageCoefficient (Data.GetPlayerImageCoefficient (Hakaima.Terrain.Type.Soil)); } if (player.state == Player.State.Wait) { FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVNET_FINISH_TUTORIAL); pattern = 1; time = 0; } } if (pattern == 1) { if (time == 0) { goCover.SetActive (true); } Color color = Color.black; color.a = Mathf.Lerp (0, 0.9f, 1f / 0.6f * time); goCover.GetComponent<Image> ().color = color; if (color.a >= 0.9f) { state = State.TutorialHelp; time = 0; pattern = 0; loop = true; } } player.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); chipList.ForEach (obj => obj.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE)); } break; case State.TutorialHelp: { if (pattern == 0) { if (time == 0) { string path = Application.systemLanguage == SystemLanguage.Japanese ? Data.HELP_PATH_JAPANESE : Data.HELP_PATH_ENGLISH; help = new TitleManager.Catalog (); help.Init (TitleManager.HELP_PAGE_NUM); goHelp = Instantiate (Resources.Load<GameObject> (path)); goHelp.transform.SetParent (transform.Find ("UI")); goHelp.transform.Find ("Attention").GetComponent<Text> ().text = Language.sentence [Language.GAME_HELP]; goHelp.transform.Find ("ButtonBack").GetComponent<Button> ().onClick.AddListener (() => { pattern = 1; time = 0; SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK); }); goHelp.transform.Find ("ButtonBack/Image/Text").GetComponent<Text> ().text = "PLAY START"; goHelp.transform.Find ("ButtonBack/Image/Text").GetComponent<Text> ().fontSize = 45; goHelp.transform.Find ("ButtonBack/Image/Text").GetComponent<Text> ().color = Color.black; goHelpPage = goHelp.transform.Find ("Page").gameObject; goHelpPoint = goHelp.transform.Find ("Point").gameObject; goHelpArrowRight = goHelp.transform.Find ("ArrowRight").gameObject; goHelpArrowLeft = goHelp.transform.Find ("ArrowLeft").gameObject; goHelpArrowRight.GetComponent<Button> ().onClick.AddListener (() => OnHelpNextPage ()); goHelpArrowLeft.GetComponent<Button> ().onClick.AddListener (() => OnHelpPrevPage ()); Destroy (goHelp.transform.Find ("Com").gameObject); Destroy (goHelp.transform.Find ("Logo").gameObject); Destroy (goHelp.transform.Find ("Swipe").gameObject); if (PlayerPrefs.GetInt (Data.RECORD_IS_TUTORIAL_FIRST_HELP) == 1) { pattern = 1; time = 0; } } help.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE); } if (pattern == 1) { if (time == 0) { goHelp.SetActive (false); } Color color = Color.black; color.a = Mathf.Lerp (0.9f, 1, 1f / 0.4f * time); goCover.GetComponent<Image> ().color = color; if (color.a >= 1f) { PlayerPrefs.SetInt (Data.RECORD_IS_TUTORIAL_FIRST_HELP, 1); MainManager.Instance.NextStage (life.now, myWeapon.now); SetClearNextStage (); } } } break; } } while (loop); time += Data.DELTA_TIME; } private void Draw () { { if (groupPlayer.gameObject.activeSelf != player.visible) { groupPlayer.gameObject.SetActive (player.visible); } if (player.visible) { if (groupPlayer.gameObject.transform.parent != goLayerList [player.layer].transform) { groupPlayer.gameObject.transform.SetParent (goLayerList [player.layer].transform); } if (groupPlayer.gameObject.transform.localPosition.x != player.positionX || groupPlayer.gameObject.transform.localPosition.y != player.positionY) { groupPlayer.gameObject.transform.localPosition = new Vector3 (player.positionX, player.positionY); } if (groupPlayer.gameObject.GetComponent<Image> ().color != player.color) { groupPlayer.gameObject.GetComponent<Image> ().color = player.color; } if (groupPlayer.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spritePlayerList [Convert.ToInt32 (player.spin) * ResourceManager.SPRITE_MULTI_TYPE + (int)player.compass * ResourceManager.SPRITE_MULTI_COMPASS + player.imageIndex]) { groupPlayer.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spritePlayerList [Convert.ToInt32 (player.spin) * ResourceManager.SPRITE_MULTI_TYPE + (int)player.compass * ResourceManager.SPRITE_MULTI_COMPASS + player.imageIndex]; } if (groupPlayer.fallTime > 0) { if (groupPlayer.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversalFall) { groupPlayer.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversalFall; } } else if (groupPlayer.bathTime > 0) { if (groupPlayer.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversalHide) { groupPlayer.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversalHide; } } else if (groupPlayer.hideTime > 0) { if (groupPlayer.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversalHide) { groupPlayer.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversalHide; } } else { if (groupPlayer.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversal) { groupPlayer.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversal; } } if (groupPlayer.surpriseTime > 0) { if (!groupPlayer.gameObjectSurprise.activeSelf) { groupPlayer.gameObjectSurprise.SetActive (true); } if (groupPlayer.gameObjectSurprise.transform.localPosition.x != player.positionX + player.size / 2 || groupPlayer.gameObjectSurprise.transform.localPosition.y != player.positionY + player.size / 2 + 80) { groupPlayer.gameObjectSurprise.transform.localPosition = new Vector3 (player.positionX + player.size / 2, player.positionY + player.size / 2 + 80); } } else { if (groupPlayer.gameObjectSurprise.activeSelf) { groupPlayer.gameObjectSurprise.SetActive (false); } } if (groupPlayer.gameObjectLifeup.activeSelf != groupPlayer.lifeup.visible) { groupPlayer.gameObjectLifeup.SetActive (groupPlayer.lifeup.visible); } if (groupPlayer.lifeup.visible) { if (groupPlayer.gameObjectLifeup.transform.localPosition.x != groupPlayer.lifeup.positionX || groupPlayer.gameObjectLifeup.transform.localPosition.y != groupPlayer.lifeup.positionY) { groupPlayer.gameObjectLifeup.transform.localPosition = new Vector3 (groupPlayer.lifeup.positionX, groupPlayer.lifeup.positionY); } } if (groupPlayer.gameObjectParasol.activeSelf != groupPlayer.isParasol) { groupPlayer.gameObjectParasol.SetActive (groupPlayer.isParasol); } if (groupPlayer.gameObjectSweat.activeSelf != groupPlayer.isSweat) { groupPlayer.gameObjectSweat.SetActive (groupPlayer.isSweat); } } } { for (int i = 0; i < enemyList.Count; i++) { Enemy enemy = enemyList [i]; GroupEnemy groupEnemy = groupEnemyList [i]; if (groupEnemy.gameObject.activeSelf != enemy.visible) { groupEnemy.gameObject.SetActive (enemy.visible); } if (enemy.visible) { if (groupEnemy.gameObject.transform.parent != goLayerList [enemy.layer].transform) { groupEnemy.gameObject.transform.SetParent (goLayerList [enemy.layer].transform); } if (groupEnemy.gameObject.transform.localPosition.x != enemy.positionX || groupEnemy.gameObject.transform.localPosition.y != enemy.positionY) { groupEnemy.gameObject.transform.localPosition = new Vector3 (enemy.positionX, enemy.positionY); } if (groupEnemy.gameObject.GetComponent<Image> ().color != enemy.color) { groupEnemy.gameObject.GetComponent<Image> ().color = enemy.color; } if (groupEnemy.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteEnemyList [(int)enemy.type * ResourceManager.SPRITE_MULTI_TYPE + (int)enemy.compass * ResourceManager.SPRITE_MULTI_COMPASS + enemy.imageIndex]) { groupEnemy.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteEnemyList [(int)enemy.type * ResourceManager.SPRITE_MULTI_TYPE + (int)enemy.compass * ResourceManager.SPRITE_MULTI_COMPASS + enemy.imageIndex]; } if (groupEnemy.fallTime > 0) { if (groupEnemy.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversalFall) { groupEnemy.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversalFall; } } else if (groupEnemy.bathTime > 0) { if (groupEnemy.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversalHide) { groupEnemy.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversalHide; } } else { if (groupEnemy.gameObject.GetComponent<Image> ().material != ResourceManager.Instance.materialReversal) { groupEnemy.gameObject.GetComponent<Image> ().material = ResourceManager.Instance.materialReversal; } } if (groupEnemy.noticeTime > 0) { if (!groupEnemy.gameObjectNotice.activeSelf) { groupEnemy.gameObjectNotice.SetActive (true); } } else { if (groupEnemy.gameObjectNotice.activeSelf) { groupEnemy.gameObjectNotice.SetActive (false); } } if (groupEnemy.lostTime > 0) { if (!groupEnemy.gameObjectLost.activeSelf) { groupEnemy.gameObjectLost.SetActive (true); } } else { if (groupEnemy.gameObjectLost.activeSelf) { groupEnemy.gameObjectLost.SetActive (false); } } } } } { bool isObstacleSibling = false; for (int i = 0; i < chipList.Count; i++) { Chip chip = chipList [i]; GroupChip groupChip = groupChipList [i]; if (groupChip.gameObjectTerrain.activeSelf != chip.terrain.visible) { groupChip.gameObjectTerrain.SetActive (chip.terrain.visible); } if (chip.terrain.visible) { if (groupChip.gameObjectTerrain.transform.parent != goLayerList [chip.terrain.layer].transform) { groupChip.gameObjectTerrain.transform.SetParent (goLayerList [chip.terrain.layer].transform); } if (groupChip.gameObjectTerrain.transform.localPosition.x != chip.positionX || groupChip.gameObjectTerrain.transform.localPosition.y != chip.positionY) { groupChip.gameObjectTerrain.transform.localPosition = new Vector3 (chip.positionX, chip.positionY); } if (groupChip.gameObjectTerrain.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteTerrainList [(int)chip.terrain.type * ResourceManager.SPRITE_MULTI_TYPE + chip.terrain.imageIndex]) { groupChip.gameObjectTerrain.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteTerrainList [(int)chip.terrain.type * ResourceManager.SPRITE_MULTI_TYPE + chip.terrain.imageIndex]; } } if (groupChip.gameObjectHole.activeSelf != chip.hole.visible) { groupChip.gameObjectHole.SetActive (chip.hole.visible); } if (chip.hole.visible) { if (groupChip.gameObjectHole.transform.parent != goLayerList [chip.hole.layer].transform) { groupChip.gameObjectHole.transform.SetParent (goLayerList [chip.hole.layer].transform); } if (groupChip.gameObjectHole.transform.localPosition.x != chip.positionX || groupChip.gameObjectHole.transform.localPosition.y != chip.positionY) { groupChip.gameObjectHole.transform.localPosition = new Vector3 (chip.positionX, chip.positionY); } if (groupChip.gameObjectHole.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteHoleList [chip.hole.imageIndex]) { groupChip.gameObjectHole.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteHoleList [chip.hole.imageIndex]; } } for (int j = 0; j < chip.obstacleList.Count; j++) { if (groupChip.gameObjectObstacleList [j].activeSelf != chip.obstacleList [j].visible) { groupChip.gameObjectObstacleList [j].SetActive (chip.obstacleList [j].visible); } if (chip.obstacleList [j].visible) { if (groupChip.gameObjectObstacleList [j].transform.parent != goLayerList [chip.obstacleList [j].layer].transform) { groupChip.gameObjectObstacleList [j].transform.SetParent (goLayerList [chip.obstacleList [j].layer].transform); isObstacleSibling = true; } if (groupChip.gameObjectObstacleList [j].transform.localPosition.x != chip.positionX || groupChip.gameObjectObstacleList [j].transform.localPosition.y != chip.positionY) { groupChip.gameObjectObstacleList [j].transform.localPosition = new Vector3 (chip.positionX, chip.positionY); } if (groupChip.gameObjectObstacleList [j].GetComponent<Image> ().sprite != ResourceManager.Instance.spriteObstacleList [(int)chip.obstacleList [j].type * ResourceManager.SPRITE_MULTI_TYPE + chip.obstacleList [j].imageIndex]) { groupChip.gameObjectObstacleList [j].GetComponent<Image> ().sprite = ResourceManager.Instance.spriteObstacleList [(int)chip.obstacleList [j].type * ResourceManager.SPRITE_MULTI_TYPE + chip.obstacleList [j].imageIndex]; groupChip.gameObjectObstacleList [j].GetComponent<Image> ().SetNativeSize (); } } } } if (isObstacleSibling) { for (int i = 0; i < chipList.Count; i++) { for (int j = 0; j < chipList [i].obstacleList.Count; j++) { groupChipList [i].gameObjectObstacleList [chipList [i].obstacleList.Count - 1 - j].transform.SetAsFirstSibling (); } } } } { for (int i = 0; i < playerWeaponList.Count; i++) { Weapon weapon = playerWeaponList [i]; GroupWeapon groupWeapon = groupPlayerWeaponList [i]; if (groupWeapon.gameObject.activeSelf != weapon.visible) { groupWeapon.gameObject.SetActive (weapon.visible); } if (weapon.visible) { if (groupWeapon.gameObject.transform.parent != goLayerList [weapon.layer].transform) { groupWeapon.gameObject.transform.SetParent (goLayerList [weapon.layer].transform); } if (groupWeapon.gameObject.transform.localPosition.x != weapon.positionX || groupWeapon.gameObject.transform.localPosition.y != weapon.positionY) { groupWeapon.gameObject.transform.localPosition = new Vector3 (weapon.positionX, weapon.positionY); } if (groupWeapon.gameObjectImage.transform.localScale.x != weapon.scaleX || groupWeapon.gameObjectImage.transform.localScale.y != weapon.scaleY) { groupWeapon.gameObjectImage.transform.localScale = new Vector3 (weapon.scaleX, weapon.scaleY); } if (groupWeapon.gameObjectImage.transform.localRotation.z != weapon.rotation) { groupWeapon.gameObjectImage.transform.localRotation = Quaternion.Euler (new Vector3 (0, 0, weapon.rotation)); } if (groupWeapon.gameObjectImage.GetComponent<Image> ().sprite != ResourceManager.Instance.spritePlayerWeapon) { groupWeapon.gameObjectImage.GetComponent<Image> ().sprite = ResourceManager.Instance.spritePlayerWeapon; } } } } { for (int i = 0; i < enemyWeaponList.Count; i++) { Weapon weapon = enemyWeaponList [i]; GroupWeapon groupWeapon = groupEnemyWeaponList [i]; if (groupWeapon.gameObject.activeSelf != weapon.visible) { groupWeapon.gameObject.SetActive (weapon.visible); } if (weapon.visible) { if (groupWeapon.gameObject.transform.parent != goLayerList [weapon.layer].transform) { groupWeapon.gameObject.transform.SetParent (goLayerList [weapon.layer].transform); } if (groupWeapon.gameObject.transform.localPosition.x != weapon.positionX || groupWeapon.gameObject.transform.localPosition.y != weapon.positionY) { groupWeapon.gameObject.transform.localPosition = new Vector3 (weapon.positionX, weapon.positionY); } if (groupWeapon.gameObjectImage.transform.localScale.x != weapon.scaleX || groupWeapon.gameObjectImage.transform.localScale.y != weapon.scaleY) { groupWeapon.gameObjectImage.transform.localScale = new Vector3 (weapon.scaleX, weapon.scaleY); } if (groupWeapon.gameObjectImage.transform.localRotation.z != weapon.rotation) { groupWeapon.gameObjectImage.transform.localRotation = Quaternion.Euler (new Vector3 (0, 0, weapon.rotation)); } if (groupWeapon.gameObjectImage.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteEnemyWeapon) { groupWeapon.gameObjectImage.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteEnemyWeapon; } } } } { for (int i = 0; i < itemList.Count; i++) { Item item = itemList [i]; GroupItem groupItem = groupItemList [i]; if (groupItem.gameObject.activeSelf != item.visible) { groupItem.gameObject.SetActive (item.visible); } if (item.visible) { if (groupItem.gameObject.transform.parent != goLayerList [item.layer].transform) { groupItem.gameObject.transform.SetParent (goLayerList [item.layer].transform); } if (groupItem.gameObject.transform.localPosition.x != item.positionX || groupItem.gameObject.transform.localPosition.y != item.positionY) { groupItem.gameObject.transform.localPosition = new Vector3 (item.positionX, item.positionY); } if (groupItem.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteItemList [(int)item.type * ResourceManager.SPRITE_MULTI_TYPE]) { groupItem.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteItemList [(int)item.type * ResourceManager.SPRITE_MULTI_TYPE]; } } } } { for (int i = 0; i < bonusList.Count; i++) { Bonus bonus = bonusList [i]; GroupBonus groupBonus = groupBonusList [i]; if (groupBonus.gameObject.activeSelf != bonus.visible) { groupBonus.gameObject.SetActive (bonus.visible); } if (bonus.visible) { if (groupBonus.gameObject.transform.parent != goLayerList [bonus.layer].transform) { groupBonus.gameObject.transform.SetParent (goLayerList [bonus.layer].transform); } if (groupBonus.gameObject.transform.localPosition.x != bonus.positionX || groupBonus.gameObject.transform.localPosition.y != bonus.positionY) { groupBonus.gameObject.transform.localPosition = new Vector3 (bonus.positionX, bonus.positionY); } if (groupBonus.gameObject.GetComponent<Image> ().color != bonus.color) { groupBonus.gameObject.GetComponent<Image> ().color = bonus.color; } if (groupBonus.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteBonusList [(int)bonus.type * ResourceManager.SPRITE_MULTI_TYPE]) { groupBonus.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteBonusList [(int)bonus.type * ResourceManager.SPRITE_MULTI_TYPE]; } } } } { for (int i = 0; i < lightList.Count; i++) { Hakaima.Light light = lightList [i]; GroupLight groupLight = groupLightList [i]; if (groupLight.gameObject.activeSelf != light.visible) { groupLight.gameObject.SetActive (light.visible); } if (light.visible) { if (groupLight.gameObject.transform.parent != goLayerList [light.layer].transform) { groupLight.gameObject.transform.SetParent (goLayerList [light.layer].transform); } if (groupLight.gameObject.transform.localPosition.x != light.positionX || groupLight.gameObject.transform.localPosition.y != light.positionY) { groupLight.gameObject.transform.localPosition = new Vector3 (light.positionX, light.positionY); } } } } { for (int i = 0; i < specialItemList.Count; i++) { Item item = specialItemList [i]; GroupItem groupItem = groupSpecialItemList [i]; if (groupItem.gameObject.activeSelf != item.visible) { groupItem.gameObject.SetActive (item.visible); } if (item.visible) { if (groupItem.gameObject.transform.parent != goLayerList [item.layer].transform) { groupItem.gameObject.transform.SetParent (goLayerList [item.layer].transform); } if (groupItem.gameObject.transform.localPosition.x != item.positionX || groupItem.gameObject.transform.localPosition.y != item.positionY) { groupItem.gameObject.transform.localPosition = new Vector3 (item.positionX, item.positionY); } switch (item.type) { case Item.Type.Ticket: { if (groupItem.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteItemList [(int)item.type * ResourceManager.SPRITE_MULTI_TYPE]) { groupItem.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteItemList [(int)item.type * ResourceManager.SPRITE_MULTI_TYPE]; } } break; case Item.Type.Weapon: { if (groupItem.gameObject.GetComponent<Image> ().sprite != ResourceManager.Instance.spritePlayerWeapon) { groupItem.gameObject.GetComponent<Image> ().sprite = ResourceManager.Instance.spritePlayerWeapon; } } break; } } } } { for (int i = 0; i < numberList.Count; i++) { Number number = numberList [i]; GroupNumber groupNumber = groupNumberList [i]; if (groupNumber.gameObject.activeSelf != number.visible) { groupNumber.gameObject.SetActive (number.visible); } if (number.visible) { if (groupNumber.gameObject.transform.localPosition.x != number.positionX || groupNumber.gameObject.transform.localPosition.y != number.positionY) { groupNumber.gameObject.transform.localPosition = new Vector3 (number.positionX, number.positionY); } if (groupNumber.gameObjectText.GetComponent<Text> ().color != number.color) { groupNumber.gameObjectText.GetComponent<Text> ().color = number.color; } if (groupNumber.gameObjectText.GetComponent<Text> ().text != number.value.ToString ()) { groupNumber.gameObjectText.GetComponent<Text> ().text = number.value.ToString (); } } } } { for (int i = 0; i < ownerItemList.Count; i++) { OwnerItem ownerItem = ownerItemList [i]; GameObject goOwnerItem = goOwnerItemList [i]; GameObject goOwnerItemFrame = goOwnerItemFrameList [i]; switch (ownerItem.state) { case OwnerItem.State.NoHave: { if (goOwnerItem.activeSelf) { goOwnerItem.SetActive (false); } if (goOwnerItemFrame.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteUpperItemFrame) { goOwnerItemFrame.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteUpperItemFrame; } } break; case OwnerItem.State.Have: case OwnerItem.State.Use: { if (!goOwnerItem.activeSelf) { goOwnerItem.SetActive (true); } if (goOwnerItem.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteItemList [(int)ownerItem.type * ResourceManager.SPRITE_MULTI_TYPE]) { goOwnerItem.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteItemList [(int)ownerItem.type * ResourceManager.SPRITE_MULTI_TYPE]; } switch (ownerItem.state) { case OwnerItem.State.Have: if (goOwnerItemFrame.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteUpperItemFrame) { goOwnerItemFrame.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteUpperItemFrame; } break; case OwnerItem.State.Use: if (goOwnerItemFrame.GetComponent<Image> ().sprite != ResourceManager.Instance.spriteUpperItemFrameSelect) { goOwnerItemFrame.GetComponent<Image> ().sprite = ResourceManager.Instance.spriteUpperItemFrameSelect; } break; } } break; } } } { if (score.now != score.pre) { goScore.GetComponent<Text> ().text = score.now.ToString (); score.pre = score.now; } if (score.high != score.preHigh) { goScoreHigh.GetComponent<Text> ().text = score.high.ToString (); score.preHigh = score.high; } if (life.now != life.pre) { goLife.GetComponent<Text> ().text = string.Format ("{0:00}", life.now).ToString (); life.pre = life.now; } if (myWeapon.now != myWeapon.pre) { goMyWeapon.GetComponent<Text> ().text = string.Format ("{0:00}", myWeapon.now).ToString (); myWeapon.pre = myWeapon.now; } if (remainingTime.now != remainingTime.pre) { TimeSpan span = TimeSpan.FromSeconds (remainingTime.now); goRemainingTime.GetComponent<Text> ().text = string.Format ("{0:00}:{1:00}:{2}", span.Minutes, span.Seconds, span.Milliseconds.ToString ("000").Substring (0, 2)); remainingTime.pre = remainingTime.now; } } switch (state) { case State.Ready: case State.ReadyContinue: { if (collectReady.go.activeSelf) { if (collectReady.go.GetComponent<Image> ().color != collectReady.color) { collectReady.go.GetComponent<Image> ().color = collectReady.color; } bool active = collectReady.color.a >= 0.5f; if (collectReady.goStage.GetComponent<Text> ().enabled != active) { collectReady.goStage.GetComponent<Text> ().enabled = active; } if (collectReady.goDescription.GetComponent<Text> ().enabled != active) { collectReady.goDescription.GetComponent<Text> ().enabled = active; } if (collectReady.goClear.GetComponent<Text> ().enabled != active) { collectReady.goClear.GetComponent<Text> ().enabled = active; } if (collectReady.goReady.GetComponent<Text> ().enabled != active) { collectReady.goReady.GetComponent<Text> ().enabled = active; } if (collectReady.goGo.GetComponent<Text> ().enabled != active) { collectReady.goGo.GetComponent<Text> ().enabled = active; } } } break; case State.Clear: { if (collectClear.go.activeSelf) { if (collectClear.go.GetComponent<Image> ().color != collectClear.color) { collectClear.go.GetComponent<Image> ().color = collectClear.color; } if (collectClear.goTitle.transform.localPosition != collectClear.positionTitle) { collectClear.goTitle.transform.localPosition = collectClear.positionTitle; } if (collectClear.goEnemy.GetComponent<Text> ().color != collectClear.colorEnemy) { collectClear.goEnemy.GetComponent<Text> ().color = collectClear.colorEnemy; } if (collectClear.goEnemyScore.GetComponent<Text> ().color != collectClear.colorEnemyScore) { collectClear.goEnemyScore.GetComponent<Text> ().color = collectClear.colorEnemyScore; } if (collectClear.goEnemyScore.GetComponent<Text> ().text != score.enemy.ToString ()) { collectClear.goEnemyScore.GetComponent<Text> ().text = score.enemy.ToString (); } if (collectClear.goTime.GetComponent<Text> ().color != collectClear.colorTime) { collectClear.goTime.GetComponent<Text> ().color = collectClear.colorTime; } if (collectClear.goTimeScore.GetComponent<Text> ().color != collectClear.colorTimeScore) { collectClear.goTimeScore.GetComponent<Text> ().color = collectClear.colorTimeScore; } if (collectClear.goTimeScore.GetComponent<Text> ().text != score.timebonus.ToString ()) { collectClear.goTimeScore.GetComponent<Text> ().text = score.timebonus.ToString (); } if (collectClear.goBonus.GetComponent<Text> ().color != collectClear.colorBonus) { collectClear.goBonus.GetComponent<Text> ().color = collectClear.colorBonus; } if (collectClear.goRule.GetComponent<Image> ().color != collectClear.colorRule) { collectClear.goRule.GetComponent<Image> ().color = collectClear.colorRule; } if (collectClear.goTotal.GetComponent<Text> ().color != collectClear.colorTotal) { collectClear.goTotal.GetComponent<Text> ().color = collectClear.colorTotal; } if (collectClear.goTotalScore.GetComponent<Text> ().color != collectClear.colorTotalScore) { collectClear.goTotalScore.GetComponent<Text> ().color = collectClear.colorTotalScore; } if (collectClear.goTotalScore.GetComponent<Text> ().text != score.stage.ToString ()) { collectClear.goTotalScore.GetComponent<Text> ().text = score.stage.ToString (); } if (collectClear.goNextStage.GetComponent<Text> ().color != collectClear.colorNextStage) { collectClear.goNextStage.GetComponent<Text> ().color = collectClear.colorNextStage; } foreach (Bonus.Type type in Enum.GetValues (typeof(Bonus.Type))) { if (type == Bonus.Type.None) continue; if (collectClear.goBonusScoreList [(int)type].GetComponent<Text> ().color != collectClear.colorBonusScoreList [(int)type]) { collectClear.goBonusScoreList [(int)type].GetComponent<Text> ().color = collectClear.colorBonusScoreList [(int)type]; collectClear.goBonusScoreList [(int)type].transform.Find ("Image").GetComponent<Image> ().color = collectClear.colorBonusScoreList [(int)type]; } if (collectClear.goBonusScoreList [(int)type].GetComponent<Text> ().text != score.bonusList [(int)type].ToString ()) { collectClear.goBonusScoreList [(int)type].GetComponent<Text> ().text = score.bonusList [(int)type].ToString (); } } if (collectClear.goPlayer.transform.localPosition.x != collectClear.player.positionX || collectClear.goPlayer.transform.localPosition.y != collectClear.player.positionY) { collectClear.goPlayer.transform.localPosition = new Vector3 (collectClear.player.positionX, collectClear.player.positionY); } if (collectClear.goPlayer.transform.GetComponent<Image> ().sprite != ResourceManager.Instance.spritePlayerList [(int)collectClear.player.compass * ResourceManager.SPRITE_MULTI_COMPASS + collectClear.player.imageIndex]) { collectClear.goPlayer.transform.GetComponent<Image> ().sprite = ResourceManager.Instance.spritePlayerList [(int)collectClear.player.compass * ResourceManager.SPRITE_MULTI_COMPASS + collectClear.player.imageIndex]; } } } break; case State.TutorialHelp: { if (goHelpPage.transform.localPosition.x != help.positionX) { goHelpPage.transform.localPosition = new Vector3 (help.positionX, goHelpPage.transform.localPosition.y); } if (goHelpArrowRight.activeSelf != help.isArrowRight) { goHelpArrowRight.SetActive (help.isArrowRight); } if (goHelpArrowLeft.activeSelf != help.isArrowLeft) { goHelpArrowLeft.SetActive (help.isArrowLeft); } goHelpPoint.transform.Find ("PointNow").localPosition = goHelpPoint.transform.Find ("Point" + help.nowPageIndex).localPosition; } break; } } private void ShowPauseMovie() { collectPause.goButtonMovie.SetActive(!MainManager.Instance.donePauseMovie); if (MainManager.Instance.donePauseMovie) { collectPause.goButtonHowTo.transform.position = collectPause.goButtonMovie.transform.position; } else { collectPause.goButtonHowTo.transform.position = pauseHowToPosition; } } private void OnPause (bool isPause) { if (state == State.Play) { this.isPause = isPause; isHowto = false; isCaution = false; collectPause.go.SetActive (isPause); collectPause.goHowTo.SetActive (isHowto); if (this.isPause) { //MainManager.Instance.nendAdBanner.Show (); //MainManager.Instance.bannerView.Show (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK); FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_PUASE); } else { //MainManager.Instance.nendAdBanner.Hide (); //MainManager.Instance.bannerView.Hide (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL); } } } private void OnPauseMovie () { MainManager.Instance.ShowInterstitial (() => { MainManager.Instance.donePauseMovie = true; ShowPauseMovie(); life.now += 5; FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_PAUSE_ADS); }); } private void OnHowTo(bool isHowto) { this.isHowto = isHowto; collectPause.goHowToImageJp.SetActive (Application.systemLanguage == SystemLanguage.Japanese); collectPause.goHowToImageEn.SetActive (Application.systemLanguage != SystemLanguage.Japanese); collectPause.goHowTo.SetActive (this.isHowto); if (this.isHowto) { SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK); } else { SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL); } } private void OnCaution(bool isCaution) { this.isCaution = isCaution; collectPause.goCaution.SetActive(false); if (this.isCaution) { SoundManager.Instance.PlaySe(SoundManager.SeName.SE_OK); // 武器半分(2以上保持時). if (myWeapon.now > 1) myWeapon.now /= 2; SoundManager.Instance.StopSe(); SoundManager.Instance.PlaySe(SoundManager.SeName.SE_CANCEL); //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide(); MainManager.Instance.Title(); } else { SoundManager.Instance.PlaySe(SoundManager.SeName.SE_CANCEL); } } private void OnPauseEnd () { /* if (state == State.Play) { // 武器半分(2以上保持時). if (myWeapon.now > 1) myWeapon.now /= 2; SoundManager.Instance.StopSe (); SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL); //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide (); MainManager.Instance.Title (); } */ SoundManager.Instance.PlaySe(SoundManager.SeName.SE_OK); collectPause.goCaution.SetActive(true); isCaution = true; } private Player.Compass checkCompass; private Vector2 checkPosition; private Coroutine coroutine; private bool canThrough; private bool isDigged; private void OnTouchPointerDown (PointerEventData eventData) { if (MainManager.Instance.isTutorial) { if (PlayerPrefs.GetInt (Data.RECORD_IS_TUTORIAL_FIRST_HELP) == 1) { MainManager.Instance.NextStage (life.now, myWeapon.now); SetClearNextStage (); FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVNET_FINISH_TUTORIAL); } } switch (state) { case State.Ready: case State.ReadyContinue: { if (!MainManager.Instance.isTutorial) { if (pattern == 0) { if (time > 0) { pattern = 1; time = 0; } } } } break; case State.Play: { isTouch = true; checkCompass = player.compass; checkPosition = eventData.pressPosition; coroutine = StartCoroutine (SetCanHoleCycle ()); } break; case State.Clear: { if (pattern == 0) { } else if (pattern < 10) { pattern = 10; time = 0; } else if (pattern == 11) { Analytics.CustomEvent ("stage_clear", new Dictionary<string, object> { {"stage_" + (MainManager.Instance.stage + 1), true}, }); if (!collectClear.isAllEnemyDie) PlayerPrefs.SetInt (Data.RECORD_ESCAPE, PlayerPrefs.GetInt (Data.RECORD_ESCAPE) + 1); bool isBoss = groupEnemyList.Exists (obj => obj.isBoss); if (isBoss) { MainManager.Instance.StoryEpilogue (); } else { MainManager.Instance.NextStage (life.now, myWeapon.now); } LifeUpForAds(); SetClearNextStage (); } } break; } } private IEnumerator SetCanHoleCycle () { yield return new WaitForSeconds (0.2f); groupPlayer.canHoleCycle = true; isDigged = true; } private void OnTouchPointerUp (PointerEventData eventData) { if (state == State.Play) { isTouch = false; if (isDigged) canThrough = false; isDigged = false; if (playerNextCommand == PLAYER_NEXT_COMMAND_NONE) isCommandNoneClick = true; if (coroutine != null) StopCoroutine (coroutine); } goTrail.GetComponent<TrailRenderer> ().material.color = Color.white; } private void OnTouchDrag (PointerEventData eventData) { float ratio = 1.0f * Screen.width / Data.SCREEN_WIDTH; switch (state) { case State.Play: { Vector2 delta = eventData.delta / ratio; if (delta.magnitude >= 3) { Player.Compass compass; float radian = Mathf.Atan2 (delta.y, delta.x); if (radian < Mathf.PI / 4 * -3) { compass = Player.Compass.Left; } else if (radian < Mathf.PI / 4 * -1) { compass = Player.Compass.Bottom; } else if (radian < Mathf.PI / 4 * 1) { compass = Player.Compass.Right; } else if (radian < Mathf.PI / 4 * 3) { compass = Player.Compass.Top; } else { compass = Player.Compass.Left; } if (checkCompass != compass) { checkCompass = compass; checkPosition = eventData.position; } } Vector2 movePosition = (eventData.position - checkPosition) / ratio; if (playerNextCommand == PLAYER_NEXT_COMMAND_NONE) { if (movePosition.magnitude >= Data.EVENT_MOVE_MAGNITUDE_COMPASS) { playerNextCommand = PLAYER_NEXT_COMMAND_COMPASS; goTrail.GetComponent<TrailRenderer> ().material.color = Color.blue; } } if (playerNextCommand == PLAYER_NEXT_COMMAND_COMPASS) { if (movePosition.magnitude >= Data.EVENT_MOVE_MAGNITUDE_COMPASS) { if (playerNextCompass != checkCompass) groupPlayer.canHoleCycle = false; playerNextCompass = checkCompass; } if (movePosition.magnitude >= Data.EVENT_MOVE_MAGNITUDE_COMPASS_WALK) { playerNextCommand = PLAYER_NEXT_COMMAND_COMPASS_WALK; goTrail.GetComponent<TrailRenderer> ().material.color = Color.white; } } if (playerNextCommand == PLAYER_NEXT_COMMAND_COMPASS_WALK) { if (movePosition.magnitude >= Data.EVENT_MOVE_MAGNITUDE_COMPASS_WALK2) { playerNextCompass = checkCompass; } } } break; case State.TutorialHelp: { Vector2 delta = eventData.delta / ratio; if (delta.x < -5) { OnHelpNextPage (); } else if (delta.x > 5) { OnHelpPrevPage (); } } break; } goTrail.transform.localPosition = eventData.position / ratio; } private void OnItem (OwnerItem ownerItem) { if (state == State.Play) { if (ownerItem.state == OwnerItem.State.Have) ownerItem.state = OwnerItem.State.Use; } } private void OnContinue (int type) { if (state == State.Continue) { // 武器半分(2以上保持時). if (myWeapon.now > 1) myWeapon.now /= 2; continueCommand = type; SoundManager.Instance.StopSe (); SoundManager.Instance.PlaySe (type != CONTINUE_COMMAND_NO ? SoundManager.SeName.SE_OK : SoundManager.SeName.SE_CANCEL); //MainManager.Instance.nendAdBanner.Hide (); MainManager.Instance.bannerView.Hide (); } } private void OnContinueMovie () { MainManager.Instance.ShowInterstitial (() => { life.now += 5; continueCommand = CONTINUE_COMMAND_MOVIE; MainManager.Instance.bannerView.Hide (); }); } private void OnHelpNextPage () { if (!help.isMove) { help.Next (); if (help.isMove) SoundManager.Instance.PlaySe (SoundManager.SeName.SE_MOVE); } } private void OnHelpPrevPage () { if (!help.isMove) { help.Prev (); if (help.isMove) SoundManager.Instance.PlaySe (SoundManager.SeName.SE_MOVE); } } private void OnVolume (bool isMute) { SoundManager.Instance.SetMute (isMute); collectPause.goVolumeOn.SetActive (!isMute); collectPause.goVolumeOff.SetActive (isMute); PlayerPrefs.SetInt (Data.SOUND_MUTE, isMute ? 1 : 0); } private void SetClearNextStage () { keepCellList = null; PlayerPrefs.SetInt (Data.RECORD_SCORE_ALL, PlayerPrefs.GetInt (Data.RECORD_SCORE_ALL) + score.now - MainManager.Instance.score); MainManager.Instance.score = score.now; MainManager.Instance.scoreHigh = score.high; MainManager.Instance.RecordSave (); } private bool IsEnemyNextCommand (Enemy enemy) { int enemyPatternIndex = Data.GetEnemyData (enemy.type).patternIndex; Data.EnemyPatternData enemyPatternData = Data.enemyPatternDataList [enemyPatternIndex]; int random = (int)(UnityEngine.Random.value * 100); if (random < enemyPatternData.rateWait) return false; return true; } private Enemy.Compass GetEnemyNextCompass (List<Chip> chipList, Player player, Enemy enemy, GroupEnemy groupEnemy) { Func<Enemy.Compass> turnRight = () => { switch (enemy.compass) { case Enemy.Compass.Right: return Enemy.Compass.Bottom; case Enemy.Compass.Left: return Enemy.Compass.Top; case Enemy.Compass.Top: return Enemy.Compass.Right; case Enemy.Compass.Bottom: return Enemy.Compass.Left; } return enemy.compass; }; Func<Enemy.Compass> turnLeft = () => { switch (enemy.compass) { case Enemy.Compass.Right: return Enemy.Compass.Top; case Enemy.Compass.Left: return Enemy.Compass.Bottom; case Enemy.Compass.Top: return Enemy.Compass.Left; case Enemy.Compass.Bottom: return Enemy.Compass.Right; } return enemy.compass; }; Func<Enemy.Compass> turnBack = () => { switch (enemy.compass) { case Enemy.Compass.Right: return Enemy.Compass.Left; case Enemy.Compass.Left: return Enemy.Compass.Right; case Enemy.Compass.Top: return Enemy.Compass.Bottom; case Enemy.Compass.Bottom: return Enemy.Compass.Top; } return enemy.compass; }; Func<bool> isFollow = () => { bool success = true; float startPositionX = enemy.positionX + Data.SIZE_CHIP / 2; float startPositionY = enemy.positionY + Data.SIZE_CHIP / 2; float endPositionX = player.positionX + Data.SIZE_CHIP / 2; float endPositionY = player.positionY + Data.SIZE_CHIP / 2; while (success) { Vector2 distance = new Vector2 (endPositionX - startPositionX, endPositionY - startPositionY); int pointX = Mathf.FloorToInt (startPositionX / Data.SIZE_CHIP); int pointY = Mathf.FloorToInt (startPositionY / Data.SIZE_CHIP); Chip chip = chipList [pointX + pointY * Data.LENGTH_X]; success = chip.obstacleList.TrueForAll (obj => Data.GetObstacleData (obj.type).isThrough); if (success) if (distance.magnitude <= Data.SIZE_CHIP) break; startPositionX += distance.normalized.x * Data.SIZE_CHIP; startPositionY += distance.normalized.y * Data.SIZE_CHIP; } return success; }; List<Enemy.Compass> followCompassList = new List<Enemy.Compass> (); Func<bool> follow = () => { Func<int, int, Enemy.Compass, bool> locate = null; locate = (int pointX, int pointY, Enemy.Compass compass) => { if (player.pointX == pointX && player.pointY == pointY) { followCompassList.Add (compass); return true; } bool isWalk = true; isWalk = chipList [pointX + pointY * Data.LENGTH_X].terrain.type != Hakaima.Terrain.Type.River; chipList [pointX + pointY * Data.LENGTH_X].obstacleList.ForEach (obj => { if (isWalk) isWalk = Data.GetObstacleData (obj.type).isThrough; }); bool success = false; if (isWalk) { if (!success) if (player.pointX - pointX > 0) success = locate (pointX + 1, pointY, Enemy.Compass.Right); if (!success) if (player.pointX - pointX < 0) success = locate (pointX - 1, pointY, Enemy.Compass.Left); if (!success) if (player.pointY - pointY > 0) success = locate (pointX, pointY + 1, Enemy.Compass.Top); if (!success) if (player.pointY - pointY < 0) success = locate (pointX, pointY - 1, Enemy.Compass.Bottom); } if (success) followCompassList.Add (compass); return success; }; return locate (enemy.pointX, enemy.pointY, enemy.compass); }; Enemy.Compass nextCompass = enemy.compass; { int enemyPatternIndex = Data.GetEnemyData (enemy.type).patternIndex; Data.EnemyPatternData enemyPatternData = Data.enemyPatternDataList [enemyPatternIndex]; bool loop; do { loop = false; int rateStraight = enemyPatternData.rateStraight; int rateTurnRight = enemyPatternData.rateTurnRight + rateStraight; int rateTurnLeft = enemyPatternData.rateTurnLeft + rateTurnRight; int rateTurnBack = enemyPatternData.rateTurnBack + rateTurnLeft; int rateFollow = enemyPatternData.rateFollow + rateTurnBack; int random = (int)(UnityEngine.Random.value * (100 - enemyPatternData.rateWait)); if (groupEnemy.isFollow) { random = rateFollow - 1; } if (random < rateStraight) { nextCompass = enemy.compass; } else if (random < rateTurnRight) { nextCompass = turnRight (); } else if (random < rateTurnLeft) { nextCompass = turnLeft (); } else if (random < rateTurnBack) { nextCompass = turnBack (); } else if (random < rateFollow) { if (player.state == Player.State.Damage) { enemyPatternData = Data.enemyPatternDataList [Data.ENEMY_PATTERN_NORMAL]; loop = true; if (groupEnemy.isFollow) { groupEnemy.isFollow = false; groupEnemy.lostTime = 0.5f; } continue; } else if (groupPlayer.invincibleTime > 0 || groupPlayer.bathTime > 0 || groupPlayer.hideTime > 0) { enemyPatternData = Data.enemyPatternDataList [Data.ENEMY_PATTERN_NORMAL]; loop = true; if (groupEnemy.isFollow) { groupEnemy.isFollow = false; groupEnemy.lostTime = 0.5f; } continue; } else if (groupPlayer.isParasol) { enemyPatternData = Data.enemyPatternDataList [Data.ENEMY_PATTERN_NORMAL]; loop = true; if (groupEnemy.isFollow) { groupEnemy.isFollow = false; groupEnemy.lostTime = 0.5f; } continue; } else if (!isFollow ()) { enemyPatternData = Data.enemyPatternDataList [Data.ENEMY_PATTERN_NORMAL]; loop = true; if (groupEnemy.isFollow) { groupEnemy.isFollow = false; groupEnemy.lostTime = 0.5f; } continue; } follow (); if (followCompassList.Count == 0) { enemyPatternData = Data.enemyPatternDataList [Data.ENEMY_PATTERN_NORMAL]; loop = true; if (groupEnemy.isFollow) { groupEnemy.isFollow = false; groupEnemy.lostTime = 0.5f; } continue; } else if (followCompassList.Count == 1) { nextCompass = followCompassList [followCompassList.Count - 1]; } else { nextCompass = followCompassList [followCompassList.Count - 2]; } if (!groupEnemy.isFollow) { groupEnemy.isFollow = true; groupEnemy.noticeTime = 0.5f; } } } while (loop); } return nextCompass; } private List<Cell> GetCellList () { List<Cell> cellList = new List<Cell> (); for (int i = 0; i < Data.LENGTH_X * Data.LENGTH_Y; i++) { Cell cell = new Cell (); cell.point = i; cell.pointX = i % Data.LENGTH_X; cell.pointY = i / Data.LENGTH_X; cellList.Add (cell); } if (MainManager.Instance.isTutorial) { for (int i = 0; i < cellList.Count; i++) { cellList [i].terrainType = Data.tutorialStageData.terrainTypeList [i]; cellList [i].obstacleType = Data.tutorialStageData.obstacleTypeList [i]; cellList [i].enemyType = Data.tutorialStageData.enemyTypeList [i]; } return cellList; } Data.StageData stageData = Data.GetStageData (MainManager.Instance.stage); List<Hakaima.Terrain.Type> terrainTypeList = new List<Hakaima.Terrain.Type> (); { int soil = Mathf.Max (0, stageData.terrainTypeList [Hakaima.Terrain.Type.Soil]); int grass = Mathf.Max (0, stageData.terrainTypeList [Hakaima.Terrain.Type.Grass]) + soil; int muddy = Mathf.Max (0, stageData.terrainTypeList [Hakaima.Terrain.Type.Muddy]) + grass; int pavement = Mathf.Max (0, stageData.terrainTypeList [Hakaima.Terrain.Type.Pavement]) + muddy; int ice = Mathf.Max (0, stageData.terrainTypeList [Hakaima.Terrain.Type.Ice]) + pavement; for (int i = 0; i < cellList.Count; i++) { if (i < soil) { terrainTypeList.Add (Hakaima.Terrain.Type.Soil); } else if (i < grass) { terrainTypeList.Add (Hakaima.Terrain.Type.Grass); } else if (i < muddy) { terrainTypeList.Add (Hakaima.Terrain.Type.Muddy); } else if (i < pavement) { terrainTypeList.Add (Hakaima.Terrain.Type.Pavement); } else if (i < ice) { terrainTypeList.Add (Hakaima.Terrain.Type.Ice); } } } List<Hakaima.Obstacle.Type> obstacleTypeList = new List<Hakaima.Obstacle.Type> (); { int tree = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Tree]; int stone = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Stone] + tree; int tomb = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Tomb] + stone; int cartRight = stageData.obstacleTypeList [Hakaima.Obstacle.Type.CartRight] + tomb; int well = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Well] + cartRight; int bale = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Bale] + well; int bathtub = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Bathtub] + bale; int stockpile = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Stockpile] + bathtub; int signboard = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Signboard] + stockpile; int tower = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Tower] + signboard; int fallenTree = stageData.obstacleTypeList [Hakaima.Obstacle.Type.FallenTree] + tower; int stump = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Stump] + fallenTree; int bucket = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Bucket] + stump; int lantern = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Lantern] + bucket; int stupaFence = stageData.obstacleTypeList [Hakaima.Obstacle.Type.StupaFence] + lantern; int stupa = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Stupa] + stupaFence; int largeTreeRight = stageData.obstacleTypeList [Hakaima.Obstacle.Type.LargeTreeRight] + stupa; int rubble = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Rubble] + largeTreeRight; int picket = stageData.obstacleTypeList [Hakaima.Obstacle.Type.Picket] + rubble; for (int i = 0; i < cellList.Count; i++) { if (i < tree) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Tree); } else if (i < stone) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Stone); } else if (i < tomb) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Tomb); } else if (i < cartRight) { obstacleTypeList.Add (Hakaima.Obstacle.Type.CartRight); } else if (i < well) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Well); } else if (i < bale) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Bale); } else if (i < bathtub) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Bathtub); } else if (i < stockpile) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Stockpile); } else if (i < signboard) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Signboard); } else if (i < tower) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Tower); } else if (i < fallenTree) { obstacleTypeList.Add (Hakaima.Obstacle.Type.FallenTree); } else if (i < stump) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Stump); } else if (i < bucket) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Bucket); } else if (i < lantern) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Lantern); } else if (i < stupaFence) { obstacleTypeList.Add (Hakaima.Obstacle.Type.StupaFence); } else if (i < stupa) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Stupa); } else if (i < largeTreeRight) { obstacleTypeList.Add (Hakaima.Obstacle.Type.LargeTreeRight); } else if (i < rubble) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Rubble); } else if (i < picket) { obstacleTypeList.Add (Hakaima.Obstacle.Type.Picket); } } } List<Hakaima.Enemy.Type> enemyTypeList = new List<Hakaima.Enemy.Type> (); { int person = stageData.enemyTypeList [Hakaima.Enemy.Type.Person]; int ghost = stageData.enemyTypeList [Hakaima.Enemy.Type.Ghost] + person; int soul = stageData.enemyTypeList [Hakaima.Enemy.Type.Soul] + ghost; int skeleton = stageData.enemyTypeList [Hakaima.Enemy.Type.Skeleton] + soul; int mummy = stageData.enemyTypeList [Hakaima.Enemy.Type.Mummy] + skeleton; int shadowman = stageData.enemyTypeList [Hakaima.Enemy.Type.Shadowman] + mummy; int golem = stageData.enemyTypeList [Hakaima.Enemy.Type.Golem] + shadowman; int goblin = stageData.enemyTypeList [Hakaima.Enemy.Type.Goblin] + golem; int parasol = stageData.enemyTypeList [Hakaima.Enemy.Type.Parasol] + goblin; int kappa = stageData.enemyTypeList [Hakaima.Enemy.Type.Kappa] + parasol; int tengu = stageData.enemyTypeList [Hakaima.Enemy.Type.Tengu] + kappa; for (int i = 0; i < cellList.Count; i++) { if (i < person) { enemyTypeList.Add (Hakaima.Enemy.Type.Person); } else if (i < ghost) { enemyTypeList.Add (Hakaima.Enemy.Type.Ghost); } else if (i < soul) { enemyTypeList.Add (Hakaima.Enemy.Type.Soul); } else if (i < skeleton) { enemyTypeList.Add (Hakaima.Enemy.Type.Skeleton); } else if (i < mummy) { enemyTypeList.Add (Hakaima.Enemy.Type.Mummy); } else if (i < shadowman) { enemyTypeList.Add (Hakaima.Enemy.Type.Shadowman); } else if (i < golem) { enemyTypeList.Add (Hakaima.Enemy.Type.Golem); } else if (i < goblin) { enemyTypeList.Add (Hakaima.Enemy.Type.Goblin); } else if (i < parasol) { enemyTypeList.Add (Hakaima.Enemy.Type.Parasol); } else if (i < kappa) { enemyTypeList.Add (Hakaima.Enemy.Type.Kappa); } else if (i < tengu) { enemyTypeList.Add (Hakaima.Enemy.Type.Tengu); } } } List<Hakaima.Item.Type> itemTypeList = new List<Hakaima.Item.Type> (); { int sandal = stageData.itemTypeList [Hakaima.Item.Type.Sandal]; int hoe = stageData.itemTypeList [Hakaima.Item.Type.Hoe] + sandal; int stone = stageData.itemTypeList [Hakaima.Item.Type.Stone] + hoe; int amulet = stageData.itemTypeList [Hakaima.Item.Type.Amulet] + stone; int parasol = stageData.itemTypeList [Hakaima.Item.Type.Parasol] + amulet; for (int i = 0; i < cellList.Count; i++) { if (i < sandal) { itemTypeList.Add (Hakaima.Item.Type.Sandal); } else if (i < hoe) { itemTypeList.Add (Hakaima.Item.Type.Hoe); } else if (i < stone) { itemTypeList.Add (Hakaima.Item.Type.Stone); } else if (i < amulet) { itemTypeList.Add (Hakaima.Item.Type.Amulet); } else if (i < parasol) { itemTypeList.Add (Hakaima.Item.Type.Parasol); } } } { List<Cell> cellTerrainPossibleList = new List<Cell> (cellList); { int hIndex = cellTerrainPossibleList.FindIndex (obj => obj.pointX == Data.PLAYER_START_POINT_X && obj.pointY == Data.PLAYER_START_POINT_Y); int tIndex = terrainTypeList.FindIndex (obj => obj == Hakaima.Terrain.Type.Soil || obj == Hakaima.Terrain.Type.Grass); cellTerrainPossibleList [hIndex].terrainType = terrainTypeList [tIndex]; cellTerrainPossibleList.RemoveAt (hIndex); terrainTypeList.RemoveAt (tIndex); } while (cellTerrainPossibleList.Count > 0 && terrainTypeList.Count > 0) { int hIndex = UnityEngine.Random.Range (0, cellTerrainPossibleList.Count); int tIndex = UnityEngine.Random.Range (0, terrainTypeList.Count); cellTerrainPossibleList [hIndex].terrainType = terrainTypeList [tIndex]; cellTerrainPossibleList.RemoveAt (hIndex); terrainTypeList.RemoveAt (tIndex); } List<int> pointXList = Enumerable.Range (0, Data.LENGTH_X).ToList (); List<int> pointYList = Enumerable.Range (0, Data.LENGTH_Y).ToList (); { bool isX = false; bool isY = false; int pavement = stageData.terrainTypeList [Hakaima.Terrain.Type.Pavement]; if (pavement == -1) { if (UnityEngine.Random.Range (0, 2) == 0) { isX = true; } else { isY = true; } } else if (pavement == -2) { isX = true; isY = true; } if (isX) { int pointX = pointXList [UnityEngine.Random.Range (0, pointXList.Count)]; pointXList.Remove (pointX); cellList.FindAll (obj => obj.pointX == pointX).ForEach (obj => obj.terrainType = Hakaima.Terrain.Type.Pavement); cellList.FindAll (obj => obj.pointX == pointX - 1 && obj.pointY % 4 == 0).ForEach (obj => obj.obstacleType = Obstacle.Type.Rubble); cellList.FindAll (obj => obj.pointX == pointX + 1 && obj.pointY % 4 == 0).ForEach (obj => obj.obstacleType = Obstacle.Type.Rubble); } if (isY) { int pointY = pointYList [UnityEngine.Random.Range (0, pointYList.Count)]; pointYList.Remove (pointY); cellList.FindAll (obj => obj.pointY == pointY).ForEach (obj => obj.terrainType = Hakaima.Terrain.Type.Pavement); cellList.FindAll (obj => obj.pointY == pointY - 1 && obj.pointX % 4 == 0).ForEach (obj => obj.obstacleType = Obstacle.Type.Rubble); cellList.FindAll (obj => obj.pointY == pointY + 1 && obj.pointX % 4 == 0).ForEach (obj => obj.obstacleType = Obstacle.Type.Rubble); } cellList.FindAll (obj => obj.terrainType == Hakaima.Terrain.Type.Pavement && obj.obstacleType == Obstacle.Type.Rubble).ForEach (obj => obj.obstacleType = Obstacle.Type.None); } { List<Cell> cellRiverList = null; bool isX = false; bool isY = false; int river = stageData.terrainTypeList [Hakaima.Terrain.Type.River]; int bridge = stageData.terrainTypeList [Hakaima.Terrain.Type.Bridge]; if (river == 1) { isX = true; } else if (river == 2) { isY = true; } else if (river == 3) { isX = true; } else if (river == 4) { isY = true; } if (isX) { pointXList = pointXList.FindAll (n => n != Data.PLAYER_START_POINT_X); int pointX = pointXList [UnityEngine.Random.Range (0, pointXList.Count)]; if (river == 3) pointX = Data.PLAYER_START_POINT_X + 1; pointXList.Remove (pointX); cellRiverList = cellList.FindAll (obj => obj.pointX == pointX); int count = 0; while (cellRiverList.Count > 0) { int index = UnityEngine.Random.Range (0, cellRiverList.Count); if (count < bridge) { if (cellRiverList [index].pointY == 0) { int point = cellRiverList [index].pointX + Data.LENGTH_X * (cellRiverList [index].pointY + 1); if (cellList [point].terrainType != Hakaima.Terrain.Type.BridgeHorizontal) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeHorizontal; cellRiverList.RemoveAt (index); count++; continue; } } else if (cellRiverList [index].pointY == Data.LENGTH_Y - 1) { int point = cellRiverList [index].pointX + Data.LENGTH_X * (cellRiverList [index].pointY - 1); if (cellList [point].terrainType != Hakaima.Terrain.Type.BridgeHorizontal) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeHorizontal; cellRiverList.RemoveAt (index); count++; continue; } } else { int point1 = cellRiverList [index].pointX + Data.LENGTH_X * (cellRiverList [index].pointY + 1); int point2 = cellRiverList [index].pointX + Data.LENGTH_X * (cellRiverList [index].pointY - 1); if (cellList [point1].terrainType != Hakaima.Terrain.Type.BridgeHorizontal && cellList [point2].terrainType != Hakaima.Terrain.Type.BridgeHorizontal) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeHorizontal; cellRiverList.RemoveAt (index); count++; continue; } } } cellRiverList [index].terrainType = Hakaima.Terrain.Type.River; cellRiverList.RemoveAt (index); } } if (isY) { pointYList = pointYList.FindAll (n => n != Data.PLAYER_START_POINT_Y); int pointY = pointYList [UnityEngine.Random.Range (0, pointYList.Count)]; if (river == 4) pointY = Data.LENGTH_Y / 2; pointYList.Remove (pointY); cellRiverList = cellList.FindAll (obj => obj.pointY == pointY); int count = 0; while (cellRiverList.Count > 0) { int index = UnityEngine.Random.Range (0, cellRiverList.Count); if (count < bridge) { if (cellRiverList [index].pointX == 0) { int point = cellRiverList [index].pointX + 1 + Data.LENGTH_X * cellRiverList [index].pointY; if (cellList [point].terrainType != Hakaima.Terrain.Type.BridgeVertical) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeVertical; cellRiverList.RemoveAt (index); count++; continue; } } else if (cellRiverList [index].pointX == Data.LENGTH_X - 1) { int point = cellRiverList [index].pointX - 1 + Data.LENGTH_X * cellRiverList [index].pointY; if (cellList [point].terrainType != Hakaima.Terrain.Type.BridgeVertical) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeVertical; cellRiverList.RemoveAt (index); count++; continue; } } else { int point1 = cellRiverList [index].pointX + 1 + Data.LENGTH_X * cellRiverList [index].pointY; int point2 = cellRiverList [index].pointX - 1 + Data.LENGTH_X * cellRiverList [index].pointY; if (cellList [point1].terrainType != Hakaima.Terrain.Type.BridgeVertical && cellList [point2].terrainType != Hakaima.Terrain.Type.BridgeVertical) { cellRiverList [index].terrainType = Hakaima.Terrain.Type.BridgeVertical; cellRiverList.RemoveAt (index); count++; continue; } } } cellRiverList [index].terrainType = Hakaima.Terrain.Type.River; cellRiverList.RemoveAt (index); } } } } { List<Cell> cellEnemyPossibleList = cellList.FindAll (obj => { switch (obj.pointY) { case 0: case 1: case 2: case 3: return false; } switch (obj.terrainType) { case Hakaima.Terrain.Type.Soil: case Hakaima.Terrain.Type.Grass: case Hakaima.Terrain.Type.Muddy: case Hakaima.Terrain.Type.Pavement: case Hakaima.Terrain.Type.Ice: switch (obj.obstacleType) { case Obstacle.Type.None: return true; } break; } return false; }); while (cellEnemyPossibleList.Count > 0 && enemyTypeList.Count > 0) { if (enemyTypeList.Exists (obj => obj == Enemy.Type.Tengu)) { List<Cell> list = cellEnemyPossibleList.FindAll (obj => (obj.pointX >= 3 && obj.pointX <= 6) && (obj.pointY >= 9 && obj.pointY <= 12)); Cell cell = list [UnityEngine.Random.Range (0, list.Count)]; cell.enemyType = Enemy.Type.Tengu; cellEnemyPossibleList.Remove (cell); enemyTypeList.Remove (Enemy.Type.Tengu); } else { int hIndex = UnityEngine.Random.Range (0, cellEnemyPossibleList.Count); int eIndex = UnityEngine.Random.Range (0, enemyTypeList.Count); cellEnemyPossibleList [hIndex].enemyType = enemyTypeList [eIndex]; cellEnemyPossibleList.RemoveAt (hIndex); enemyTypeList.RemoveAt (eIndex); } } } { List<Cell> cellObstaclePossibleList = cellList.FindAll (obj => { switch (obj.point) { case (Data.PLAYER_START_POINT_X) + (Data.PLAYER_START_POINT_Y) * Data.LENGTH_X: case (Data.PLAYER_START_POINT_X - 1) + (Data.PLAYER_START_POINT_Y) * Data.LENGTH_X: case (Data.PLAYER_START_POINT_X + 1) + (Data.PLAYER_START_POINT_Y) * Data.LENGTH_X: case (Data.PLAYER_START_POINT_X) + (Data.PLAYER_START_POINT_Y + 1) * Data.LENGTH_X: return false; } if (obj.enemyType != Enemy.Type.None) { return false; } switch (obj.terrainType) { case Hakaima.Terrain.Type.Soil: case Hakaima.Terrain.Type.Grass: case Hakaima.Terrain.Type.Ice: if (obj.pointX + 1 < Data.LENGTH_X) { switch (cellList [(obj.pointX + 1) + obj.pointY * Data.LENGTH_X].terrainType) { case Hakaima.Terrain.Type.BridgeVertical: case Hakaima.Terrain.Type.BridgeHorizontal: return false; } } if (obj.pointX - 1 >= 0) { switch (cellList [(obj.pointX - 1) + obj.pointY * Data.LENGTH_X].terrainType) { case Hakaima.Terrain.Type.BridgeVertical: case Hakaima.Terrain.Type.BridgeHorizontal: return false; } } if (obj.pointY + 1 < Data.LENGTH_Y) { switch (cellList [obj.pointX + (obj.pointY + 1) * Data.LENGTH_X].terrainType) { case Hakaima.Terrain.Type.BridgeVertical: case Hakaima.Terrain.Type.BridgeHorizontal: return false; } } if (obj.pointY - 1 >= 0) { switch (cellList [obj.pointX + (obj.pointY - 1) * Data.LENGTH_X].terrainType) { case Hakaima.Terrain.Type.BridgeVertical: case Hakaima.Terrain.Type.BridgeHorizontal: return false; } } switch (obj.obstacleType) { case Obstacle.Type.None: return true; } break; } return false; }); while (cellObstaclePossibleList.Count > 0 && obstacleTypeList.Count > 0) { int hIndex = UnityEngine.Random.Range (0, cellObstaclePossibleList.Count); int oIndex = UnityEngine.Random.Range (0, obstacleTypeList.Count); switch (obstacleTypeList [oIndex]) { case Obstacle.Type.LargeTreeRight: { Cell cellRight = cellObstaclePossibleList [hIndex]; Cell cellLeft = cellObstaclePossibleList.Find (obj => obj.point == cellRight.point - 1); if (cellRight.pointX != 0) { if (cellLeft != null) { cellRight.obstacleType = Obstacle.Type.LargeTreeRight; cellLeft.obstacleType = Obstacle.Type.LargeTreeLeft; cellObstaclePossibleList.Remove (cellRight); cellObstaclePossibleList.Remove (cellLeft); obstacleTypeList.RemoveAt (oIndex); } } } break; case Obstacle.Type.CartRight: { List<Cell> list = cellObstaclePossibleList.FindAll (obj => (obj.pointX != 0 && obj.pointX != Data.LENGTH_X - 1)); list = list.FindAll (obj => cellList [obj.point - 1].obstacleType == Obstacle.Type.None && cellList [obj.point + 1].obstacleType == Obstacle.Type.None); if (list.Count > 0) { Cell cell = list [UnityEngine.Random.Range (0, list.Count)]; cell.obstacleType = Obstacle.Type.CartRight; cellObstaclePossibleList.Remove (cell); cellObstaclePossibleList.Remove (cellList.Find (obj => obj.point == cell.point - 1)); cellObstaclePossibleList.Remove (cellList.Find (obj => obj.point == cell.point + 1)); obstacleTypeList.Remove (Obstacle.Type.CartRight); } else { obstacleTypeList.RemoveAt (oIndex); } } break; case Obstacle.Type.Tower: { List<Cell> towerList = cellList.FindAll (obj => obj.obstacleType == Obstacle.Type.Tower); List<Cell> list = cellObstaclePossibleList; for (int i = 0; i < towerList.Count; i++) { Cell tower = towerList [i]; list = list.FindAll (obj => obj.pointX != tower.pointX + 1 && obj.pointX != tower.pointX - 1); list = list.FindAll (obj => obj.pointY != tower.pointY + 1 && obj.pointY != tower.pointY - 1); } Cell cell = list [UnityEngine.Random.Range (0, list.Count)]; cell.obstacleType = Obstacle.Type.Tower; cellObstaclePossibleList.Remove (cell); obstacleTypeList.Remove (Obstacle.Type.Tower); } break; case Obstacle.Type.Well: { List<Cell> wellList = cellList.FindAll (obj => obj.obstacleType == Obstacle.Type.Well); List<Cell> list = cellObstaclePossibleList; for (int i = 0; i < wellList.Count; i++) { Cell well = wellList [i]; list = list.FindAll (obj => obj.pointX != well.pointX + 1 && obj.pointX != well.pointX - 1); list = list.FindAll (obj => obj.pointY != well.pointY + 1 && obj.pointY != well.pointY - 1); } Cell cell = list [UnityEngine.Random.Range (0, list.Count)]; cell.obstacleType = Obstacle.Type.Well; cellObstaclePossibleList.Remove (cell); obstacleTypeList.Remove (Obstacle.Type.Well); } break; default: cellObstaclePossibleList [hIndex].obstacleType = obstacleTypeList [oIndex]; cellObstaclePossibleList.RemoveAt (hIndex); obstacleTypeList.RemoveAt (oIndex); break; } } if (stageData.darkness <= 0.2f) cellList.FindAll (obj => obj.obstacleType == Obstacle.Type.Rubble).ForEach (obj => obj.obstacleType = Obstacle.Type.RubbleOff); } { List<Cell> cellItemPossibleList = cellList.FindAll (obj => { switch (obj.terrainType) { case Hakaima.Terrain.Type.Soil: case Hakaima.Terrain.Type.Grass: case Hakaima.Terrain.Type.Muddy: switch (obj.obstacleType) { case Hakaima.Obstacle.Type.None: return true; } break; } return false; }); while (cellItemPossibleList.Count > 0 && itemTypeList.Count > 0) { int hIndex = UnityEngine.Random.Range (0, cellItemPossibleList.Count); int eIndex = UnityEngine.Random.Range (0, itemTypeList.Count); cellItemPossibleList [hIndex].itemType = itemTypeList [eIndex]; cellItemPossibleList.RemoveAt (hIndex); itemTypeList.RemoveAt (eIndex); } } { List<Cell> cellHolePossibleList = cellList.FindAll (obj => { switch (obj.point) { case (Data.PLAYER_START_POINT_X) + (Data.PLAYER_START_POINT_Y) * Data.LENGTH_X: return false; } if (Data.GetTerrainData (obj.terrainType).isDigging) if (obj.obstacleType == Obstacle.Type.None) if (obj.enemyType == Enemy.Type.None) return true; return false; }); int holeOpen = stageData.holeOpen; while (cellHolePossibleList.Count > 0 && holeOpen > 0) { int hIndex = UnityEngine.Random.Range (0, cellHolePossibleList.Count); cellHolePossibleList [hIndex].isHoleOpen = true; cellHolePossibleList.RemoveAt (hIndex); holeOpen--; } } return cellList; } private void CheckBackKey () { if (Input.GetKeyDown (KeyCode.Escape)) { if (isHowto) { OnHowTo (false); return; } if (isCaution) { OnCaution (false); return; } OnPause (!isPause); } } private void OnApplicationPause (bool pauseStatus) { if (!isPause) { OnPause (true); } } private void OnDebugDamageClick () { isDebugDamage = !isDebugDamage; transform.Find ("UI/Debug/Damage/Text").GetComponent<Text> ().text = string.Format ("敵当\n{0}", isDebugDamage ? "ON" : "OFF"); } private void OnTwitter () { // Add 2017.11.7 #if UNITY_ANDROID FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_TWITTER); SocialConnector.SocialConnector.Share (Language.sentence [Language.TWITTER], Data.URL, null); #elif UNITY_IOS FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_TWITTER); SocialConnector.SocialConnector.Share (Language.sentence [Language.TWITTER], Data.URL_IOS, null); #endif } // バナーが出たらガチャチケット1枚. private bool ShowAdsBanner(int n) { /*int randNum = (MainManager.Instance.stage >= 5) ? n * 2 : n; bool flag = false; UnityEngine.Random.InitState ((int)Time.time); if (UnityEngine.Random.Range (0, 100) < randNum) { MainManager.Instance.ShowInterstitialNoMovie (); } return flag; */ MainManager.Instance.ShowInterstitialNoMovie (); return true; } private void LifeUpForAds() { if (MainManager.Instance.isInterstitialClose) { life.now++; SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_1UP); MainManager.Instance.isInterstitialClose = false; } } }
using Trace = Sentry.Protocol.Trace; namespace Sentry.Tests.Protocol.Context; public class TraceTests { private readonly IDiagnosticLogger _testOutputLogger; public TraceTests(ITestOutputHelper output) { _testOutputLogger = new TestOutputDiagnosticLogger(output); } [Fact] public void Ctor_NoPropertyFilled_SerializesEmptyObject() { // Arrange var trace = new Trace(); // Act var actual = trace.ToJsonString(_testOutputLogger); // Assert Assert.Equal("""{"type":"trace"}""", actual); } [Fact] public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() { // Arrange var trace = new Trace { Operation = "op123", Status = SpanStatus.Aborted, IsSampled = false, ParentSpanId = SpanId.Parse("1000000000000000"), SpanId = SpanId.Parse("2000000000000000"), TraceId = SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8") }; // Act var actual = trace.ToJsonString(_testOutputLogger, indented: true); // Assert Assert.Equal( """ { "type": "trace", "span_id": "2000000000000000", "parent_span_id": "1000000000000000", "trace_id": "75302ac48a024bde9a3b3734a82e36c8", "op": "op123", "status": "aborted" } """, actual); } [Fact] public void Clone_CopyValues() { // Arrange var trace = new Trace { Operation = "op123", Status = SpanStatus.Aborted, IsSampled = false, ParentSpanId = SpanId.Parse("1000000000000000"), SpanId = SpanId.Parse("2000000000000000"), TraceId = SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8") }; // Act var clone = trace.Clone(); // Assert Assert.Equal(trace.Operation, clone.Operation); Assert.Equal(trace.Status, clone.Status); Assert.Equal(trace.IsSampled, clone.IsSampled); Assert.Equal(trace.ParentSpanId, clone.ParentSpanId); Assert.Equal(trace.SpanId, clone.SpanId); Assert.Equal(trace.TraceId, clone.TraceId); } }
using System; namespace Ibit.Core.Data { [Serializable] public class Pacient { public static Pacient Loaded; public int Id; public string Name; public Sex Sex; public DateTime Birthday; public Capacities Capacities; public string Observations; public ConditionType Condition; public int UnlockedLevels; public float AccumulatedScore; public int PlaySessionsDone; public bool CalibrationDone; public bool HowToPlayDone; public float Weight; public float Height; public float PitacoThreshold; public string Ethnicity; public DateTime CreatedOn; public bool IsCalibrationDone => this.Capacities.RawInsPeakFlow < 0 && this.Capacities.RawInsFlowDuration > 0 && this.Capacities.RawExpPeakFlow > 0 && this.Capacities.RawExpFlowDuration > 0 && this.Capacities.RawRespRate > 0; #if UNITY_EDITOR static Pacient() { if (Loaded == null) Loaded = new Pacient { Id = -1, CalibrationDone = true, HowToPlayDone = true, Condition = ConditionType.Normal, Name = "NetRunner", PlaySessionsDone = 0, UnlockedLevels = 15, AccumulatedScore = 0, PitacoThreshold = 7.5f, Capacities = new Capacities { RespiratoryRate = 0.3f, ExpPeakFlow = 1600, InsPeakFlow = -330, ExpFlowDuration = 18000, InsFlowDuration = 10000 } }; } #endif } public enum ConditionType { Restrictive = 1, Normal = 2, Obstructive = 3 } public enum Sex { Male, Female } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallMovement : MonoBehaviour { public float speed = 200f; public Rigidbody2D rb; public Vector3 startPosition; // Start is called before the first frame update void Start() { startPosition = this.transform.position; Launch(); } public void Reset() { //rb.velocity = new Vector2(0, 0); transform.position = startPosition; Launch(); } public void Launch() { float randomX = Random.Range(0, 2) == 0 ? -1 : 1; float randomY = Random.Range(0, 2) == 0 ? -1 : 1; rb.velocity = new Vector2(randomX * speed, randomY * speed) * Time.deltaTime; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Word = Microsoft.Office.Interop.Word; using System.Diagnostics; namespace WorldTemplate { public partial class Form1 : Form { //private readonly string TemplateFileName = @"D:\File.docx";//путь к файлу private Word.Application wordapp; private Word.Document worddocument; public Form1() { InitializeComponent(); } //метод замены заглушек private void ReplaceWordStub(string stubToReplace, string text, Word.Document worddocument) { var range = worddocument.Content; range.Find.ClearFormatting(); range.Find.Execute(FindText: stubToReplace, ReplaceWith: text); } //кнопка открытия private void btnStart_Click(object sender, EventArgs e) { //открытие файла #region try { wordapp = new Word.Application();//запускаем Word wordapp.Visible = false;//делаем не видимым его Object filename = @"D:\A1.docx"; worddocument = wordapp.Documents.Open(ref filename); } catch (Exception ex) { MessageBox.Show(ex.Message); } #endregion //переменные с формы #region string bosname = textBox1.Text; string postion = textBox2.Text; string applicant = textBox3.Text; var date = endData.Value.ToShortDateString(); #endregion ReplaceWordStub("{bosname}", bosname, worddocument); ReplaceWordStub("{position}", postion, worddocument); ReplaceWordStub("{applicant}", applicant, worddocument); ReplaceWordStub("{date}", date, worddocument); //сохраняем документ worddocument.SaveAs2(@"D:\result.docx"); } //кнопка закрытия private void button2_Click(object sender, EventArgs e) { Object saveChanges = Word.WdSaveOptions.wdSaveChanges; Object originalFormat = Word.WdOriginalFormat.wdWordDocument; Object routeDocument = Type.Missing; wordapp.Quit(ref saveChanges,ref originalFormat, ref routeDocument); wordapp = null; } } }
namespace Airelax.Infrastructure.ThirdPartyPayment.ECPay.Request { public class TransactRequestData { public string PlatformId { get; set; } public string MerchantId { get; set; } public string PayToken { get; set; } public string MerchantTradeNo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using UIKit; using Foundation; using Aquamonix.Mobile.Lib.Database; using Aquamonix.Mobile.IOS.Views; using Aquamonix.Mobile.Lib.Domain; using Aquamonix.Mobile.Lib.ViewModels; using Aquamonix.Mobile.Lib.Utilities; using Aquamonix.Mobile.Lib.Domain.Responses; using Aquamonix.Mobile.Lib.Services; using Aquamonix.Mobile.IOS.UI; using MapKit; using CoreLocation; using CoreGraphics; using Aquamonix.Mobile.IOS.Model; namespace Aquamonix.Mobile.IOS.ViewControllers { /// <summary> /// Device details screen. /// </summary> public partial class DeviceDetailsViewController : ListViewControllerBase { private static DeviceDetailsViewController _instance; private bool ShowNavFooter { get { return (Device.SupportsIrrigationStop || Device.SupportsIrrigationPrev || Device.SupportsIrrigationNext); } } protected override nfloat ReconBarVerticalLocation { get { //TODO: add IsDisposed method return _tableViewController.TableView.Frame.Top; } } private DeviceDetailsViewController(string deviceId) : base(deviceId) { // temporarily moved to parent class //ExceptionUtility.Try(() => //{ //this.DeviceId = deviceId; //this.Device = new DeviceDetailViewModel(DataCache.GetDeviceFromCache(deviceId)); //this.Initialize(); //NSNotificationCenter.DefaultCenter.AddObserver(new NSString(NotificationType.Reconnected.ToString()), this.OnReconnect); //NSNotificationCenter.DefaultCenter.AddObserver(new NSString(NotificationType.Activated.ToString()), this.OnReconnect); // temporary fix //}); } public static DeviceDetailsViewController CreateInstance(string deviceId) { ExceptionUtility.Try(() => { if (_instance != null && _instance.DeviceId != deviceId) { _instance.Dispose(); _instance = null; } }); if (_instance == null) _instance = new DeviceDetailsViewController(deviceId); return _instance; } protected override void HandleViewWillAppear(bool animated) { base.HandleViewWillAppear(animated); // _tableViewController.TableView.Frame = new CGRect(0, 0, 400, 500); } protected override void HandleViewDidAppear(bool animated) { base.HandleViewDidAppear(animated); } protected override void DoLoadData() { ExceptionUtility.Try(() => { base.DoLoadData(); this.Device = new DeviceDetailViewModel(DataCache.GetDeviceFromCache(this.DeviceId)); this.Device.ChangeFeatureSettingValue = this.FeatureSettingValueChanged; if (this.Device == null) { AlertUtility.ShowAlert(StringLiterals.DeviceNotFoundErrorTitle, StringLiterals.FormatDeviceNotFoundErrorMessage(this.DeviceId)); } else { this._tableViewController.LoadData(this.Device); this._navBarView.SetDevice(this.Device); this._navFooterView.Device = this.Device; var pendingCommands = DataCache.GetCommandProgressesSubIds(CommandType.DeviceFeatureSetting, this.DeviceId); foreach (var feature in this.Device.Features) { if (pendingCommands.Contains(feature.Id)) feature.ValueChanging = true; } this._tableViewController.TableViewSource.NavigateToAction = NavigateTo; } this.HandleViewDidLayoutSubviews(); }); } protected override void InitializeViewController() { ExceptionUtility.Try(() => { base.InitializeViewController(); this.NavigationBarView = this._navBarView; this._navFooterView.Hidden = (!this.ShowNavFooter); this.SetCustomBackButton(); if (this.ShowNavFooter) this.FooterView = this._navFooterView; this.TableViewController = this._tableViewController; }); } protected override bool ScreenIsEmpty(out string emptyMessage) { emptyMessage = null; bool isEmpty = true; if (this.Device != null) { //if it has visible features, it's not empty if (this.Device.Features != null) { if (this.Device.Features.Where((f) => f.IsVisible(this.Device?.Device)).Any()) isEmpty = false; } //if it's a group, and it has displayable devices, it's not empty if (this.Device.IsGroup) { if (isEmpty) { if (this.Device.DevicesInGroup != null && this.Device.DevicesInGroup.Any()) isEmpty = false; } } } return isEmpty; } protected override void AfterShowReconBar() { base.AfterShowReconBar(); this.AdjustTableForReconBar(_tableViewController, true); } protected override void AfterHideReconBar() { base.AfterHideReconBar(); this.AdjustTableForReconBar(_tableViewController, false); } private void NavigateTo(DeviceFeatureViewModel feature) { switch (feature.Destination) { case StringLiterals.Alerts: this.NavigateToAlerts(); break; case StringLiterals.Schedules: this.NavigateToSchedules(); break; case StringLiterals.Circuits: this.NavigateToCircuits(); break; case StringLiterals.Stations: this.NavigateToStations(this.Device, feature); break; case StringLiterals.Programs: this.NavigateToPrograms(this.Device, feature); break; case StringLiterals.PivotPrograms: this.NavigateToPivotPrograms(this.Device, feature); break; case StringLiterals.Pivot: this.NavigateToPivotControls(this.Device, feature); break; case "ProgramDisable": this.LaunchEnableTimerScreen(this.Device, feature); break; } } private void NavigateToPivotPrograms(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { MainThreadUtility.InvokeOnMain(() => { this.NavigateTo(PivotProgramsViewController.CreateInstance(this.Device?.Id)); // this.NavigateTo(ProgramListViewController.CreateInstance(this.Device?.Id)); }); } private void NavigateToPivotControls(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { MainThreadUtility.InvokeOnMain(() => { PivotControlViewController timerVc = PivotControlViewController.CreateInstance(device, feature as ProgramDisableFeatureViewModel, this.Device?.Id); this.NavigateTo(timerVc); }); } private void NavigateToAlerts() { ProgressUtility.SafeShow("Getting Alerts", () => { ServiceContainer.AlertService.RequestAlerts(this.Device.Device, NavigateToAlerts).ContinueWith((r) => { MainThreadUtility.InvokeOnMain(() => { ProgressUtility.Dismiss(); if (r.Result != null && r.Result.IsSuccessful) { this.NavigateTo(AlertListViewController.CreateInstance(this.Device?.Id)); } }); }); }, true); } private void NavigateToPrograms(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { MainThreadUtility.InvokeOnMain(() => { this.NavigateTo(ProgramListViewController.CreateInstance(this.Device?.Id)); }); } private void NavigateToStations(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { MainThreadUtility.InvokeOnMain(() => { this.NavigateTo(StationListViewController.CreateInstance(this.Device?.Id)); }); } private void NavigateToCircuits() { MainThreadUtility.InvokeOnMain(() => { this.NavigateTo(CircuitListViewController.CreateInstance(this.Device?.Id)); }); } private void NavigateToSchedules() { MainThreadUtility.InvokeOnMain(() => { this.NavigateTo(ScheduleListViewController.CreateInstance(this.Device?.Id)); }); } private void LaunchEnableTimerScreen(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { ExceptionUtility.Try(() => { EnableTimerViewController timerVc = EnableTimerViewController.CreateInstance(device, feature as ProgramDisableFeatureViewModel); this.NavigateTo(timerVc); }); } private void FeatureSettingValueChanged(DeviceDetailViewModel device, DeviceFeatureViewModel feature, DeviceSetting newSetting) { ExceptionUtility.Try(() => { //TODO: is this always null? DeviceSettingValue originalSettingValue = null; //var originalValue = feature?.Feature?.Setting?.GetValue(out originalSettingValue); var settingValue = newSetting?.GetValue(); string confirmText = originalSettingValue?.Dictionary?.PromptConfirm?.LastOrDefault() ?? "Confirm"; string cancelText = originalSettingValue?.Dictionary?.PromptCancel?.LastOrDefault() ?? "Cancel"; if (settingValue != null) { string promptText = String.Empty; if (!String.IsNullOrEmpty(feature?.SettingsValueDictionary?.PromptText?.LastOrDefault())) { promptText = feature.SettingsValueDictionary.PromptText?.LastOrDefault(); } else { promptText = String.Format("{0} {1}{2} {3}", feature?.SettingsValueDictionary?.PromptPrefix?.LastOrDefault(), feature.PromptValue, newSetting?.Values?.Items?.FirstOrDefault().Value.Units, feature?.SettingsValueDictionary?.PromptSuffix?.LastOrDefault()); } AlertUtility.ShowConfirmationAlert(originalSettingValue?.Title, promptText, (b) => { if (b) { this.FeatureSettingValueChangeConfirmed(device, feature, originalSettingValue, newSetting, newSetting.Id); } else { var cell = this._tableViewController.GetCellFromFeatureId(feature.Id) as FeatureCell; if (cell != null) { feature.ValueChanging = false; cell.LoadCellValues(device, device.Features.Where((f) => f.Id == feature.Id).FirstOrDefault()); } } }, okButtonText: confirmText, cancelButtonText: cancelText); } }); } private void FeatureSettingValueChangeConfirmed(DeviceDetailViewModel device, DeviceFeatureViewModel feature, DeviceSettingValue originalSettingValue, DeviceSetting newSetting, string settingId) { ExceptionUtility.Try(() => { feature.ValueChanging = true; var cell = this._tableViewController.GetCellFromFeatureId(feature.Id) as FeatureCell; ProgressUtility.SafeShow(String.Empty, () => { feature.ValueChanging = true; ServiceContainer.StatusService.SetSettings( device.Device, newSetting, settingId, handleUpdates: (r) => { this.HandleUpdatesForFeatureSetting(r, device, feature, originalSettingValue, newSetting, settingId); }, onReconnect: () => { FeatureSettingValueChangeConfirmed(device, feature, originalSettingValue, newSetting, settingId); }).ContinueWith((r) => { MainThreadUtility.InvokeOnMain(() => { ProgressUtility.Dismiss(); if (r.Result != null && !r.Result.IsFinal) { if (cell != null) { cell.Enabled = false; if (cell is ProgramDisableViewCell) { var disableFeature = (feature as ProgramDisableFeatureViewModel); cell.DisabledText = newSetting?.Values?.Items?.FirstOrDefault().Value?.Value == disableFeature.EnableValue ? "Enabling..." : "Disabling..."; cell.LoadCellValues(this.Device, feature); } else { cell.DisabledText = StringLiterals.UpdatingText; //"Updating..."; cell.LoadCellValues(this.Device, feature); } } } }); }); }); }); } private void HandleUpdatesForFeatureSetting(ProgressResponse response, DeviceDetailViewModel device, DeviceFeatureViewModel feature, DeviceSettingValue originalSettingValue, DeviceSetting newSetting, string settingId) { if (response != null) { var commandProgress = new CommandProgress(CommandType.DeviceFeatureSetting, response?.Body); commandProgress.SubItemIds = new string[] { feature.Id }; DataCache.AddCommandProgress(commandProgress); if (response.IsFinal) { var cell = this._tableViewController.GetCellFromFeatureId(feature.Id) as FeatureCell; feature.ValueChanging = false; if (cell != null) { cell.Enabled = true; cell.LoadCellValues(this.Device, feature); } if (response.IsSuccessful) { //AlertUtility.ShowProgressResponse("Stop/Start Program " + program.Id, response); } else { if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse) AlertUtility.ShowAppError(response?.ErrorBody); } } } AlertUtility.ShowProgressResponse(feature.Id, response); } // temporarily moved to parent class //private void OnReconnect(NSNotification notification) //{ // ExceptionUtility.Try(() => // { // if (this.IsShowing) // { // if (this.Device?.Device != null) // { // ServiceContainer.DeviceService.RequestDevice(this.Device.Device, silentMode: true); // } // } // }); //} private class NavBarView : NavigationBarView { private const int RightMargin = 0; /// 12; private readonly AquamonixLabel _titleLabel = new AquamonixLabel(); private readonly AquamonixLabel _subtextLabel = new AquamonixLabel(); public NavBarView() : base() { ExceptionUtility.Try(() => { this._titleLabel.SetFontAndColor(NavHeaderFontBig); this._titleLabel.TextAlignment = UITextAlignment.Center; this._titleLabel.LineBreakMode = UILineBreakMode.MiddleTruncation; this._subtextLabel.SetFontAndColor(NavHeaderFontSmall); this._subtextLabel.TextAlignment = UITextAlignment.Center; this.AddSubviews(_titleLabel, _subtextLabel); }); } public void SetDevice(DeviceDetailViewModel device) { ExceptionUtility.Try(() => { if (device != null) { this._titleLabel.Text = device.Name; this._titleLabel.SetFrameHeight(Height); this._titleLabel.SizeToFit(); this._subtextLabel.Text = this.GetSubtext(device); this._subtextLabel.SizeToFit(); } }); } public override void LayoutSubviews() { ExceptionUtility.Try(() => { base.LayoutSubviews(); this._titleLabel.SetFrameLocation(0, 0); this._titleLabel.SetFrameWidth(this.Frame.Width); this._titleLabel.EnforceMaxXCoordinate(this.Frame.Width - RightMargin); this._subtextLabel.SetFrameLocation(0, this._titleLabel.Frame.Bottom); this._subtextLabel.CenterHorizontallyInParent(); this._subtextLabel.EnforceMaxXCoordinate(this.Frame.Width - RightMargin); }); } private string GetSubtext(DeviceDetailViewModel device) { string output = String.Empty; if (device != null) { if (!String.IsNullOrEmpty(device.StatusText)) output += device.StatusText + ". "; if (device.StatusLastUpdated != null) { output += String.Format("Updated {0} ago.", DateTimeUtil.HowLongAgo(device.StatusLastUpdated.Value)); } } return output.Trim(); } } private class DeviceDetailsTableViewController : TableViewControllerBase { public DeviceDetailsTableViewSource TableViewSource { get { if (this.TableView != null) return this.TableView.Source as DeviceDetailsTableViewSource; return null; } } public DeviceDetailsTableViewController() : base() { ExceptionUtility.Try(() => { this.TableView.RegisterClassForCellReuse(typeof(SensorsViewCell), SensorsViewCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(NormalFeatureCell), NormalFeatureCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(SpecialViewCell), SpecialViewCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(SliderFeatureViewCell), SliderFeatureViewCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(ProgramDisableViewCell), ProgramDisableViewCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(DeviceListViewCell), DeviceListViewCell.TableCellKey); this.TableView.RegisterClassForCellReuse(typeof(SpecialViewCellMap), SpecialViewCellMap.TableCellKeymm); this.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; }); } public void LoadData(DeviceDetailViewModel device) { ExceptionUtility.Try(() => { DeviceDetailsTableViewSource source = new DeviceDetailsTableViewSource(device); TableView.Source = source; TableView.ReloadData(); }); } protected override void HandleViewDidLoad() { base.HandleViewDidLoad(); } public UITableViewCell GetCellFromFeatureId(string featureId) { UITableViewCell output = null; ExceptionUtility.Try(() => { if (this.TableViewSource != null) output = this.TableViewSource.GetCellFromFeatureId(this.TableView, featureId); }); return output; } } private class DeviceDetailsTableViewSource : TableViewSourceBase<DeviceFeatureViewModel> { private DeviceDetailViewModel _device; private Action<DeviceFeatureViewModel> _navigateToAction; public const int PivotFeatureRowHeight = 390; public Action<DeviceFeatureViewModel> NavigateToAction { get { return this._navigateToAction; } set { this._navigateToAction = WeakReferenceUtility.MakeWeakAction(value); } } public DeviceDetailsTableViewSource(DeviceDetailViewModel device) : base() { ExceptionUtility.Try(() => { this._device = device; foreach (var feature in device.Features) { if (feature.DisplayType != DeviceFeatureRowDisplayType.None) this.Values.Add(feature); } if (device.IsGroup) { this.Values.Add(new DeviceFeatureViewModel() { DisplayType = DeviceFeatureRowDisplayType.Devices }); } }); } public override nfloat GetHeightForHeader(UITableView tableView, nint section) { // reversed changes from build 84 //tableView.ScrollEnabled = true; //tableView.Frame = new CGRect(0, 70, UIScreen.MainScreen.Bounds.Width, 560); return 0; } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { return ExceptionUtility.Try<nfloat>(() => { //tableView.ScrollEnabled = true; // reversed changes from build 84 if (Values != null && indexPath.Row < Values.Count) { if (Values[indexPath.Row].DisplayType == DeviceFeatureRowDisplayType.Sensors) return SensorsPanel.CalculateHeight(this._device.Sensors); if (Values[indexPath.Row].DisplayType == DeviceFeatureRowDisplayType.Normal) return DefaultRowHeight; if (Values[indexPath.Row].DisplayType == DeviceFeatureRowDisplayType.Devices) return DeviceGroupListPanel.CalculateHeight(this._device.Sensors); if (Values[indexPath.Row].DisplayType == DeviceFeatureRowDisplayType.PivotFeature) { //tableView.Frame = new CGRect(0, 70, UIScreen.MainScreen.Bounds.Width, 390); return PivotFeatureRowHeight; } } return DefaultRowHeight; }); } protected override UITableViewCell GetCellInternal(UITableView tableView, NSIndexPath indexPath) { if (indexPath.Row < this.Values.Count) { var feature = this.Values[indexPath.Row]; switch (feature.DisplayType) { case DeviceFeatureRowDisplayType.Sensors: var sensorsCell = (SensorsViewCell)tableView.DequeueReusableCell(SensorsViewCell.TableCellKey, indexPath); sensorsCell.SetSensors(_device, feature, _device.Sensors); return sensorsCell; case DeviceFeatureRowDisplayType.PivotFeature: var PivotMapCell = (SpecialViewCellMap)tableView.DequeueReusableCell(SpecialViewCellMap.TableCellKeymm, indexPath); PivotMapCell.LoadCellValues(_device, feature); return PivotMapCell; case DeviceFeatureRowDisplayType.Devices: var devicesCell = (DeviceListViewCell)tableView.DequeueReusableCell(DeviceListViewCell.TableCellKey, indexPath); devicesCell.SetDevices(_device); return devicesCell; case DeviceFeatureRowDisplayType.Normal: var normalCell = (NormalFeatureCell)tableView.DequeueReusableCell(NormalFeatureCell.TableCellKey, indexPath); normalCell.LoadCellValues(_device, feature); return normalCell; case DeviceFeatureRowDisplayType.Slider: var sliderCell = (SliderFeatureViewCell)tableView.DequeueReusableCell(SliderFeatureViewCell.TableCellKey, indexPath); sliderCell.LoadCellValues(_device, feature); return sliderCell; case DeviceFeatureRowDisplayType.Special: if (feature.Id == "ProgramDisable") { var disableCell = (ProgramDisableViewCell)tableView.DequeueReusableCell(ProgramDisableViewCell.TableCellKey, indexPath); disableCell.LoadCellValues(_device, feature); return disableCell; } else { var specialCell = (SpecialViewCell)tableView.DequeueReusableCell(SpecialViewCell.TableCellKey, indexPath); specialCell.LoadCellValues(_device, feature); return specialCell; } } } return null; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { ExceptionUtility.Try(() => { if (indexPath.Row < this.Values.Count) { var cell = tableView.CellAt(indexPath) as FeatureCell; if (cell != null) { if (cell.Enabled) { var feature = this.Values[indexPath.Row]; if (!feature.ValueChanging) { if (!String.IsNullOrEmpty(feature.Destination)) { if (this.NavigateToAction != null) this.NavigateToAction(feature); } } } } else { var mapcell = tableView.CellAt(indexPath) as FeatureCellforMap; var feature = this.Values[indexPath.Row]; if (!feature.ValueChanging) { if (!String.IsNullOrEmpty(feature.Destination)) { if (this.NavigateToAction != null) this.NavigateToAction(feature); } } } } }); } public UITableViewCell GetCellFromFeatureId(UITableView tableView, string featureId) { UITableViewCell output = null; ExceptionUtility.Try(() => { int index = 0; for (int n = 0; n < this.Values.Count; n++) { if (featureId == this.Values[n].Id) { index = n; break; } } if (index >= 0) { output = tableView.CellAt(NSIndexPath.FromRowSection(index, 0)); } }); return output; } } private class SensorsViewCell : TableViewCellBase { public const string TableCellKey = "SensorsViewCell"; private readonly SensorsPanel _sensorsPanel = new SensorsPanel(); private DeviceDetailViewModel _device; public SensorsViewCell(IntPtr handle) : base(handle) { ExceptionUtility.Try(() => { this._sensorsPanel.OnUpdateClicked = () => { ExceptionUtility.Try(() => { this._sensorsPanel.SetUpdatingMode(true); ProgressUtility.SafeShow("Updating Sensors", () => { ServiceContainer.SensorService.RequestSensors( this._device.Device, handleUpdates: this.HandleUpdatesForRequestSensors, onReconnect: this._sensorsPanel.OnUpdateClicked ).ContinueWith((r) => { if (r.Result != null) { DataCache.AddCommandProgress(new CommandProgress(CommandType.UpdateSensors, r.Result.Body)); } MainThreadUtility.InvokeOnMain(() => { ProgressUtility.Dismiss(); if (r.Result != null && r.Result.IsSuccessful) { } //else // AlertUtility.ShowAppError(r.Result?.ErrorBody); }); }); }, blockUI: false); }); }; this.ContentView.AddSubview(_sensorsPanel); }); } public void SetSensors(DeviceDetailViewModel device, DeviceFeatureViewModel sensorsFeature, IEnumerable<SensorGroupViewModel> sensors) { ExceptionUtility.Try(() => { this._device = device; this._sensorsPanel.SetSensors(sensors, sensorsFeature); bool isUpdating = device.IsUpdatingStatus; if (!isUpdating) { if (DataCache.HasPendingCommands(CommandType.UpdateSensors, _device.Id)) isUpdating = true; } this._sensorsPanel.SetUpdatingMode(isUpdating); }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); _sensorsPanel.SetFrameLocation(0, 0); _sensorsPanel.SetFrameSize(this.ContentView.Frame.Width, _sensorsPanel.CalculateHeight()); } private void HandleUpdatesForRequestSensors(ProgressResponse response) { MainThreadUtility.InvokeOnMain(() => { if (response != null) { DataCache.AddCommandProgress(new CommandProgress(CommandType.UpdateSensors, response.Body)); if (response.IsFinal) { this._sensorsPanel.SetUpdatingMode(false); //this._sensorsPanel.SetSensors(); //if (!response.IsSuccessful) // AlertUtility.ShowAppError(response.ErrorBody); } } }); } } private class DeviceListViewCell : TableViewCellBase { public const string TableCellKey = "DeviceListViewCell"; private readonly DeviceGroupListPanel _devicesPanel = new DeviceGroupListPanel(); //private DeviceDetailViewModel _device; //private AquamonixLabel _measuringLabel = new AquamonixLabel(); public DeviceListViewCell(IntPtr handle) : base(handle) { ExceptionUtility.Try(() => { this.ContentView.AddSubview(_devicesPanel); }); } public void SetDevices(DeviceDetailViewModel device) { ExceptionUtility.Try(() => { //this._device = device; this._devicesPanel.SetDevices(device.Sensors); }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); _devicesPanel.SetFrameLocation(0, 350); _devicesPanel.SetFrameSize(this.ContentView.Frame.Width, _devicesPanel.CalculateHeight()); } } private class SliderFeatureViewCell : FeatureCell { public const string TableCellKey = "SliderViewCell"; private const int SliderDelayMs = 100; private Dictionary<long, float> _savedValues = new Dictionary<long, float>(); private bool _hideText; private AquamonixLabel _measuringLabel = new AquamonixLabel(); private readonly CustomSlider _slider = new CustomSlider(); public override bool Enabled { get { return base.Enabled; } set { this._slider.Enabled = value; base.Enabled = value; } } public SliderFeatureViewCell(IntPtr handle) : base(handle) { ExceptionUtility.Try(() => { this._arrowImageView.Hidden = true; this._slider.Continuous = true; this._slider.OnTouchesEnded = () => { if (this.Device != null && this.Device.ChangeFeatureSettingValue != null) { if (this.Feature.Feature.Setting != null) { var newSetting = new DeviceSetting() { Id = this.Feature.Feature.Setting.Id, Values = new ItemsDictionary<DeviceSettingValue>() }; DeviceSettingValue settingValueObj = null; this.Feature?.Feature?.Setting?.GetValue(out settingValueObj); if (settingValueObj != null) { var settingValueClone = settingValueObj.Clone(); //get rid of unnecessary & big properties settingValueClone.Dictionary = null; settingValueClone.Validation = null; settingValueClone.Enum = null; settingValueClone.DisplayType = null; settingValueClone.DisplayPrecision = null; settingValueClone.EditPrecision = null; settingValueClone.Title = null; double valueFactor = this.GetValueFactor(); int precision = 10; int p; if (Int32.TryParse(settingValueObj?.EditPrecision, out p)) precision = p; var sliderValue = GetSliderValueFromEarlier(); settingValueClone.Value = (MathUtil.RoundToNearest((int)(sliderValue * valueFactor), precision)).ToString(); newSetting.Values.Add("Value", settingValueClone); this.Feature.PromptValue = settingValueClone.Value; this.Device.ChangeFeatureSettingValue(this.Device, this.Feature, newSetting); this._slider.Enabled = false; this.SetSettingValueText(settingValueClone.Value, settingValueClone); } } } this._savedValues.Clear(); }; this._slider.ValueChanged += (o, e) => { this.SetCurrentSliderValueText(); }; this._measuringLabel.Font = this._label.Font; this._measuringLabel.Text = StringLiterals.UpdatingText; this.AddSubview(this._slider); }); } public override void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { ExceptionUtility.Try(() => { base.LoadCellValues(device, feature); DeviceSettingValue settingValueObj = null; var settingValue = feature?.Feature?.Setting?.GetValue(out settingValueObj); if (!this.Enabled) { if (!String.IsNullOrEmpty(this.DisabledText)) this.SetText(this.DisabledText); this._label.TextColor = Colors.LightGrayTextColor; } else { this._label.TextColor = Colors.StandardTextColor; this.SetSettingValueText(settingValue, settingValueObj); var valueFactor = this.GetValueFactor(); float value = 0; Single.TryParse(settingValue, out value); this._slider.SetValue(value / (float)valueFactor, false); } this._slider.Enabled = !feature.ValueChanging && feature.Editable && this.Enabled; }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); var minSliderWidth = (UIScreen.MainScreen.Bounds.Width / 2); var textLen = this._measuringLabel.Text.StringSize(this._measuringLabel.Font).Width; this._slider.SetFrameX(this._label.Frame.X + textLen + 20); this._slider.SetFrameWidth(this.ContentView.Frame.Width - this._slider.Frame.X - RightMargin); this._slider.CenterVerticallyInParent(); //ensure slider is at least 50% of screen width if (this._slider.Frame.Width < minSliderWidth) { if (!_hideText) { _hideText = true; this.SetCurrentSliderValueText(false); } this._slider.SetFrameWidth(minSliderWidth); this._slider.AlignToRightOfParent(RightMargin); } } private void SetCurrentSliderValueText(bool save = true) { DeviceSettingValue settingValueObj = null; this.Feature?.Feature?.Setting?.GetValue(out settingValueObj); var valueFactor = this.GetValueFactor(); var value = this._slider.Value; if (save) { while (_savedValues.Count > 200) { _savedValues.Remove(_savedValues.Keys.First()); } //save the values on a timescale long time = DateTime.Now.ToFileTime(); if (_savedValues.ContainsKey(time)) _savedValues[time] = value; else _savedValues.Add(time, value); } int precision = 10; int p; if (Int32.TryParse(settingValueObj?.EditPrecision, out p)) precision = p; value = (int)(value * (double)valueFactor); value = MathUtil.RoundToNearest((int)value, precision); this.SetSettingValueText(value.ToString(), settingValueObj); } private float GetSliderValueFromEarlier() { return ExceptionUtility.Try<float>(() => { var keys = _savedValues.Keys.ToArray(); var before = DateTime.Now.Subtract(TimeSpan.FromMilliseconds(200)).ToFileTime(); //for (int n = keys.Length - 1; n >= 0; n--) //{ // if (keys[n] <= before) // { // if (_savedValues.ContainsKey(keys[n])) // { // var output = _savedValues[keys[n]]; // return output; // } // } //} return _slider.Value; }); } private void SetSettingValueText(string valueString, DeviceSettingValue valueObj) { //find shortest text string shortestText = String.Empty; if (!_hideText) { int shortestLength = 10000; if (valueObj?.Dictionary?.ValuePrefix != null) { foreach (string s in valueObj.Dictionary.ValuePrefix) { if (!String.IsNullOrEmpty(s) && s.Length < shortestLength) { shortestText = s; shortestLength = s.Length; } } } } this._label.Text = String.Format("{0} {1}{2}", shortestText.Trim(), valueString, valueObj?.Units); this._label.SizeToFit(); } private double GetValueFactor() { DeviceSettingValue settingValueObj = null; this.Feature?.Feature?.Setting?.GetValue(out settingValueObj); double valueFactor = 100; if (settingValueObj?.Validation != null) valueFactor = settingValueObj.Validation.Max; return valueFactor; } private class CustomSlider : UISlider { public CustomSlider() : base() { } public Action OnTouchesEnded { get; set; } public override void TouchesEnded(NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); if (this.OnTouchesEnded != null) this.OnTouchesEnded(); } } } private class SpecialViewCell : FeatureCell { public const string TableCellKey = "SpecialViewCell"; public SpecialViewCell(IntPtr handle) : base(handle) { } public override void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { base.LoadCellValues(device, feature); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); } } private class ProgramDisableViewCell : SpecialViewCell { public new const string TableCellKey = "ProgramDisableViewCell"; public ProgramDisableViewCell(IntPtr handle) : base(handle) { } public override void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { var programDisableViewModel = (feature as ProgramDisableFeatureViewModel); if (device.IsGroup) programDisableViewModel.DisplayText = programDisableViewModel.SettingName; base.LoadCellValues(device, feature); if (!this.Enabled) { if (!String.IsNullOrEmpty(this.DisabledText)) this.SetText(this.DisabledText); this._label.TextColor = Colors.LightGrayTextColor; } else this._label.TextColor = Colors.StandardTextColor; //disabled for 9h, 20m //disabled indefinitely //enabled } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); } } private class NormalFeatureCell : FeatureCell { public const string TableCellKey = "NormalFeatureCell"; public NormalFeatureCell(IntPtr handle) : base(handle) { } public override void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { ExceptionUtility.Try(() => { base.LoadCellValues(device, feature); this._descriptionLabel.Hidden = true; if (!String.IsNullOrEmpty(feature.Description)) { this._descriptionLabel.Hidden = false; this._descriptionLabel.Text = feature.Description; this._descriptionLabel.SizeToFit(); } }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); } } private class FeatureCell : TableViewCellBase { protected const int RightMargin = 13; protected const int RightTextMargin = 37; protected const int LeftMargin = 10; protected readonly UIImageView _arrowImageView = new UIImageView(); protected readonly UIImageView _iconImageView = new UIImageView(); protected readonly AquamonixLabel _label = new AquamonixLabel(); protected readonly AquamonixLabel _descriptionLabel = new AquamonixLabel(); protected readonly AquamonixLabel _descriptionByLineLabel = new AquamonixLabel(); private static UIImage _alertsIcon = UIImage.FromFile("Images/alarms1.png"); private static UIImage _alertsIconRed = UIImage.FromFile("Images/alarms1_active.png"); private static UIImage _stationsIcon = UIImage.FromFile("Images/stations.png"); private static UIImage _schedulesIcon = UIImage.FromFile("Images/schedule.png"); private static UIImage _programsIcon = UIImage.FromFile("Images/programs1.png"); private static UIImage _circuitsIcon = UIImage.FromFile("Images/Circuits.png"); private static UIImage _scaleFactorIcon = UIImage.FromFile("Images/percentage.png"); private static UIImage _disableIcon = UIImage.FromFile("Images/disable.png"); public DeviceDetailViewModel Device { get; protected set; } public DeviceFeatureViewModel Feature { get; protected set; } public virtual bool Enabled { get; set; } public string DisabledText { get; set; } protected virtual UIImage Image { get; } public FeatureCell(IntPtr handle) : base(handle) { ExceptionUtility.Try(() => { this.Enabled = true; _arrowImageView.Image = Images.TableRightArrow; _arrowImageView.SizeToFit(); _descriptionLabel.SetFontAndColor(MainTextNormal); _descriptionByLineLabel.SetFontAndColor(ByLineText); _label.SetFontAndColor(MainTextNormal); this.ContentView.AddSubviews(_iconImageView, _label, _descriptionLabel, _arrowImageView); }); } public virtual void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { ExceptionUtility.Try(() => { this.Device = device; this.Feature = feature; this.Feature = feature; var image = GetImageForFeature(feature); this.SetTextAndImage(image, feature.DisplayText); if (feature.ShowRed) this._label.SetFontAndColor(MainTextBoldRed); else this._label.SetFontAndColor(MainTextNormal); this._label.SizeToFit(); }); } protected UIImage GetImageForFeature(DeviceFeatureViewModel feature) { UIImage image = null; ExceptionUtility.Try(() => { switch (feature.Type) { case DeviceFeatureTypes.AlertList: image = _alertsIcon; if (feature.ShowRed) image = _alertsIconRed; break; case DeviceFeatureTypes.StationList: image = _stationsIcon; break; case DeviceFeatureTypes.ProgramList: image = _programsIcon; break; case DeviceFeatureTypes.PivotProgramsFeature: image = _programsIcon; break; case DeviceFeatureTypes.ScheduleList: image = _schedulesIcon; break; case DeviceFeatureTypes.CircuitList: image = _circuitsIcon; break; case DeviceFeatureTypes.Setting: switch (feature.Id) { case DeviceFeatureIds.ProgramScaleFactor: image = _scaleFactorIcon; break; case DeviceFeatureIds.ProgramDisable: image = _disableIcon; break; } break; } }); return image; } protected void SetTextAndImage(UIImage image, string text) { ExceptionUtility.Try(() => { this.SetImage(image); this.SetText(text); }); } protected void SetText(string text) { ExceptionUtility.Try(() => { this._label.Text = text; this._label.SizeToFit(); }); } protected void SetImage(UIImage image) { ExceptionUtility.Try(() => { this._iconImageView.Image = image; this._iconImageView.SizeToFit(); }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); this._iconImageView.SetFrameLocation(LeftMargin, this.ContentView.Frame.Height / 2 - this._iconImageView.Frame.Height / 2); this._label.SetFrameHeight(20); this._label.SetFrameX(45); this._label.CenterVerticallyInParent(); this._label.EnforceMaxXCoordinate(this.Frame.Width - RightMargin); //this._label.SetFrameY(-100); this._arrowImageView.CenterVerticallyInParent(); this._arrowImageView.AlignToRightOfParent(RightMargin); //this._arrowImageView.SetFrameY(-50); this._descriptionLabel.SetFrameHeight(_label.Frame.Height); this._descriptionLabel.SetFrameY(_label.Frame.Y); this._descriptionLabel.EnforceMaxWidth(this.Frame.Width - RightTextMargin - (this._label.Frame.Right + 8)); this._descriptionLabel.AlignToRightOfParent(RightTextMargin); if (Feature == null) { this._arrowImageView.Hidden = true; } //this._descriptionLabel.EnforceMaxXCoordinate(this.Frame.Width - RightTextMargin); } } private class FeatureCellforMap : TableViewCellBase { // call api for status penal and circle // protected const int RightMargin = 13; protected const int RightTextMargin = 37; protected const int LeftMargin = 10; public DeviceDetailViewModel Device { get; protected set; } public DeviceFeatureViewModel Feature { get; protected set; } public DeviceFeatureViewModel Program { get; protected set; } public virtual bool Enabled { get; set; } public string DisabledText { get; set; } private CLLocationManager _location = new CLLocationManager(); private string _status = string.Empty; private string _direction; private int _currentProgramId; private PivotMapDelegate _mapDel; protected readonly UIImageView _arrowImageView = new UIImageView(); protected readonly UIView _topView = new UIView(); protected UIView _pivotView = new MKAnnotationView(); private readonly UILabel _lblRunning = new UILabel(); protected readonly UIImageView _runningImageView = new UIImageView(); private readonly UILabel _lblStop = new UILabel(); protected readonly UIImageView _stopImageView = new UIImageView(); private readonly UILabel _lblEndGun = new UILabel(); private readonly UILabel _lblAux1 = new UILabel(); private readonly UILabel _lblAux2 = new UILabel(); private readonly UILabel _lblProgramStatus = new UILabel(); private readonly UILabel _lblProgramStatusEdit = new UILabel(); protected readonly UIImageView _waitingImageView = new UIImageView(); protected virtual MKMapView _mapView { set; get; } private readonly UILabel _lblforward = new UILabel(); protected readonly UIImageView _forwardImageView = new UIImageView(); private readonly UILabel _lblRevers = new UILabel(); protected readonly UIImageView _reversImageView = new UIImageView(); private readonly UILabel _lblwet = new UILabel(); private readonly UILabel _lblDry = new UILabel(); protected readonly UIImageView _wetImageView = new UIImageView(); private readonly UILabel _lblSpeed = new UILabel(); private readonly UILabel _lblWatering = new UILabel(); protected readonly UIImageView _speedImageView = new UIImageView(); protected readonly UIImageView _dryImageView = new UIImageView(); private readonly UIImageView _btnNext = new UIImageView(); private readonly UIImageView _aux1 = new UIImageView(); private readonly UIImageView _aux2 = new UIImageView(); private readonly UIView _separator1 = new UIView(); private readonly UIView _separator2 = new UIView(); private readonly UIView _separator3 = new UIView(); private readonly UIView _separator4 = new UIView(); public virtual void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { // ProgranStart = program; var data = device.Device.MetaData.Device.Features; ExceptionUtility.Try(() => { //this.Program = program; this.Device = device; this.Feature = feature; this._direction = device.DirectionValue; // var u = Aquamonix.Mobile.Lib.Environment.AppSettings.unit; //const double lat = 28.612840; //const double lon = 77.231127; double lat = double.Parse(device.Device.MetaData.Device.Location.Latitude.ToString()); double lon = double.Parse(device.Device.MetaData.Device.Location.Longitude.ToString()); if (device.Device.MetaData.Device.Location.Latitude == 0 && device.Device.MetaData.Device.Location.Longitude == 0) { lat = 0.000001; lon = 0.000001; } var mapCenter = new CLLocationCoordinate2D(lat, lon); var length = int.Parse(Device.Device.MetaData.Device.LengthMetres?.Value) + 20; // todo increase the size of the pivot mimic _mapView.Frame = new CGRect(-150, 0, this.Frame.Width + 150, 390); //new CGRect(0 - this._topView.Frame.Width, 0, this.Frame.Width + this._topView.Frame.Width, 390); var mapLength = 135 * length / 20; //length * 2 * (this.Frame.Width + this._topView.Frame.Width) / (this.Frame.Width - this._topView.Frame.Width) / 0.9; var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, mapLength, mapLength); _mapView.CenterCoordinate = mapCenter; _mapView.Region = mapRegion; if (_mapView.Overlays != null && _mapView.Overlays.Length > 0) { foreach (var overlay in _mapView.Overlays.ToList()) { _mapView.RemoveOverlay(overlay); } } if (_mapView.Annotations != null && _mapView.Annotations.Length > 0) { foreach (var annotation in _mapView.Annotations.ToList()) { _mapView.RemoveAnnotation(annotation); } } _mapDel = new PivotMapDelegate(device); _mapView.Delegate = _mapDel; //var circleOverlay = MKCircle.Circle(mapCenter, int.Parse(Device.Device.MetaData.Device.LengthMetres.Value)); var circleOverlay = MKCircle.Circle(mapCenter, length); _mapView.AddOverlay(circleOverlay); _mapView.AddAnnotation(new PivotAnnotation("", mapCenter)); _mapView.AddAnnotation(new NextLineAnnotation("", mapCenter)); _mapView.AddAnnotation(new ZeroAnnotation("", mapCenter)); this._mapView.MapType = MKMapType.Satellite; this._mapView.SizeToFit(); //TODO fix all of the below program name strings if (device.Device.Programs.Status != null) { if (device.Device.Programs.Status.Value == StringLiterals.Running) { if (this.Device != null) { foreach (var p in this.Device.Programs) ; //p.StopStartProgram = this._lblProgramStatus; this._runningImageView.Image = Images.Running; this.SetRunningLabelText(this.FormatStatusDescription(device.Device.Programs.StatusDescription)); // "Moving"; _currentProgramId = device.Device.Programs.CurrentProgramId != string.Empty ? Convert.ToInt32(device.Device.Programs.CurrentProgramId) - 1 : 0; //CurrentProgramId = DataCache.CurrenprogramId-1; this._lblProgramStatus.Text = StringLiterals.ProgramRunning;// device.Device.MetaData.Device.Programs.Items.Values.ElementAt(CurrentProgramId).Name + " " + ProgramStatus.Running; // this._lblProgramStatus.Text = program.Name; } } else if (device.Device.Programs.Status.Value == StringLiterals.Waiting) { this._runningImageView.Image = Images.Waiting; this.SetRunningLabelText(this.FormatStatusDescription(device.Device.Programs.StatusDescription)); //device.Device.Programs.Status.Value; this._lblProgramStatus.Text = StringLiterals.ProgramRunning; } else if (device.Device.Programs.Status.Value == StringLiterals.Stopped) { this._runningImageView.Image = Images.Stop; this.SetRunningLabelText(this.FormatStatusDescription(device.Device.Programs.StatusDescription)); //StringLiterals.Stopped; _currentProgramId = device.Device.Programs.CurrentProgramId != string.Empty ? Convert.ToInt32(device.Device.Programs.CurrentProgramId) - 1 : 0; //CurrentProgramId = DataCache.CurrenprogramId-1; this._lblProgramStatus.Text = StringLiterals.ProgramStopped;// device.Device.MetaData.Device.Programs.Items.Values.ElementAt(CurrentProgramId).Name + " " + ProgramStatus.Stopped; //this._lblProgramStatus.Text = program.Name; } else { this._lblStop.Text = StringLiterals.Stopped; this._runningImageView.Image = Images.Stop; this._lblProgramStatus.Text = "Program Stopped"; } } else { this._runningImageView.Hidden = false; } if (device.DirectionStatus) { if (device.DirectionValue == StringLiterals.Forward || device.DirectionValue == "1") { this._lblforward.Text = StringLiterals.Forward; this._forwardImageView.Image = Images.Farrow; } else { this._lblforward.Text = StringLiterals.Reverse; this._forwardImageView.Image = Images.RevImage; } } else { this._lblforward.Text = ""; } if (device.WetDryStatus) { if (Device.SpeedStatus) { DeviceSettingValue settingValueObj = null; this.Feature?.Feature?.Setting?.GetValue(out settingValueObj); if (settingValueObj != null) { var settingValueClone = settingValueObj.Clone(); } try { var unit = device.Device.Features.Values.Where(x => x.Type.ToLower() == "pivotfeature").FirstOrDefault().Unit; this._lblSpeed.Text = device.SpeedValue.ToString() + unit; } catch (Exception e) { LogUtility.LogException(e); } this._speedImageView.Image = Images.Speed; } else { this._lblSpeed.Text = device.AppAmountValue.ToString() + "mm"; // this._lblSpeed.Text = Device.Device.CurrentStep.ApplicationAmount.Value.ToString() + "mm"; this._speedImageView.Image = Images.Speed; } if (device.WetDryValue == "true" || device.WetDryValue == "1") { this._lblwet.Text = StringLiterals.Wet; this._wetImageView.Image = Images.Wet; } else { this._lblwet.Text = StringLiterals.Dry; this._wetImageView.Image = Images.Dry; } } else { this._lblSpeed.Text = ""; this._lblwet.Text = ""; this._wetImageView.Image = Images.Dry; } if (device.EndGunStatus) { if (device.EndGunValue == "true" || device.EndGunValue == "1") { this._lblEndGun.Text = StringLiterals.EndGun + StringLiterals.Auto; // "Auto"; } else { this._lblEndGun.Text = StringLiterals.EndGun + " " + "Off"; // this._lblEndGun.Text = device.Device.MetaData.Device.Features.Items.Values.FirstOrDefault().Program.Steps.Items["-1"].EndGun.Dictionary.Title.FirstOrDefault().ToString() + "off"; } } else { this._lblEndGun.Text = ""; } if (device.Aux1Status) { //if ((device.Aux1Value == "true" || device.Aux1Value == "1") && device.Device.MetaData.Device.Features.Items.Values.Count > 0) if (device.Aux1Value == "true" || device.Aux1Value == "1") { try { this._lblAux1.Text = device.Device.MetaData.Device.Features.Items.Values.FirstOrDefault().Program.Steps.Items["-1"].Auxiliary1.Dictionary.Title.FirstOrDefault().ToString() + " On"; } catch (Exception) { this._lblAux1.Text = String.Format("{0} {1}", StringLiterals.Aux1, StringLiterals.On); //"Aux1 On"; } this._aux1.Image = Images.PowerOn; this._aux1.SizeToFit(); } else { this._lblAux1.Text = String.Format("{0} {1}", StringLiterals.Aux1, StringLiterals.Off); //"Aux1 Off"; this._aux1.Image = Images.PowerOff; this._aux1.SizeToFit(); } } else { this._lblAux1.Text = ""; this._aux1.Image = Images.PowerOff; this._aux1.SizeToFit(); } if (device.Aux2Status) { if (device.Aux2Value == "true" || device.Aux2Value == "1") { try { this._lblAux2.Text = device.Device.MetaData.Device.Features.Items.Values.FirstOrDefault().Program.Steps.Items["-1"].Auxiliary2.Dictionary.Title.FirstOrDefault().ToString() + " On"; } catch (Exception) { this._lblAux2.Text = String.Format("{0} {1}", StringLiterals.Aux2, StringLiterals.On); //"Aux2 On"; } this._aux2.Image = Images.PowerOn; this._aux2.SizeToFit(); } else { this._lblAux2.Text = String.Format("{0} {1}", StringLiterals.Aux2, StringLiterals.Off); //"Aux2 Off"; this._aux2.Image = Images.PowerOff; this._aux2.SizeToFit(); } } else { this._lblAux2.Text = ""; this._aux2.Image = Images.PowerOff; this._aux2.SizeToFit(); } //this.CurrentStepId = int.Parse(device.Device.Programs.CurrentProgramId); //try //{ // this.CurrentStepId = int.Parse(device.Device.Programs.Items.FirstOrDefault().Value.CurrentStepId); // this.CurrentProgId = int.Parse(device.Device.Programs.CurrentProgramId); // //this.CurrentStepId = device.Device.Programs.Items.FirstOrDefault().Value.CurrentStepId; // this._lblProgramStatus.Text = device.Device.MetaData.Device.Programs.Items.Values.ElementAt(CurrentStepId).Name; //} //catch(Exception e) //{ // this.CurrentStepId = int.Parse(device.Device.Programs.Items.FirstOrDefault().Value.CurrentStepId); // this.CurrentProgId = int.Parse(device.Device.Programs.CurrentProgramId); // //this.CurrentStepId = device.Device.Programs.Items.FirstOrDefault().Value.CurrentStepId; // this._lblProgramStatus.Text = device.Device.MetaData.Device.Programs.Items.Values.ElementAt(CurrentStepId).Name; //} //try //{ // this._lblProgramStatusEdit.Text = Device.Device.MetaData.Device.Programs.Items.Values.ElementAt(CurrentStepId).Steps.Items[CurrentStepId.ToString()].Name + " Repeat " + device.Device.Programs.Items.Values.ElementAt(CurrentStepId).RepeatNumber.ToString() + " of " + device.Device.Programs.Items.Values.ElementAt(CurrentStepId).NumberOfRepeats.ToString(); //} //catch (Exception ex) //{ // this._lblProgramStatusEdit.Text = string.Empty; // LogUtility.LogException(ex); //} }); } public FeatureCellforMap(IntPtr handle) : base(handle) { ExceptionUtility.Try(() => { this._mapView = new MKMapView(); //this.mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; this._mapView.ZoomEnabled = false; // Request permission to access device location _location.RequestWhenInUseAuthorization(); // Indicates User Location this._mapView.ShowsUserLocation = false; this._mapView.ScrollEnabled = false; this._mapView.ZoomEnabled = false; this._mapView.UserInteractionEnabled = false; this._topView.Layer.CornerRadius = 5; this._topView.Layer.BorderColor = UIColor.Black.CGColor; this._topView.BackgroundColor = UIColor.White; this._topView.Alpha = .9f; this._runningImageView.Image = Images.Running; this._lblRunning.SetFrameWidth(100); this._lblRunning.SetFrameHeight(30); this._lblRunning.Font = UIFont.PreferredHeadline; this._lblRunning.Lines = 0; this._lblRunning.LineBreakMode = UILineBreakMode.WordWrap; this._separator1.BackgroundColor = UIColor.Gray; this._forwardImageView.Image = Images.Farrow; this._lblforward.Font = UIFont.PreferredHeadline; this._separator2.BackgroundColor = UIColor.Gray; this._speedImageView.Image = Images.Speed; this._lblSpeed.Font = UIFont.PreferredHeadline; this._lblWatering.Font = UIFont.PreferredCaption2; this._separator3.BackgroundColor = UIColor.Gray; this._lblwet.Font = UIFont.PreferredHeadline; this._lblDry.Font = UIFont.PreferredHeadline; this._separator4.BackgroundColor = UIColor.Gray; this._lblEndGun.Font = UIFont.PreferredHeadline; this._btnNext.Image = Images.Slice; this._lblAux1.Font = UIFont.PreferredHeadline; this._lblAux2.Font = UIFont.PreferredHeadline; this._lblProgramStatus.Font = UIFont.PreferredCallout; this._lblProgramStatusEdit.Font = UIFont.PreferredCaption1; this._topView.AddSubviews(_lblRunning, _runningImageView, _waitingImageView, _lblStop, _stopImageView, _separator1, _forwardImageView, _lblforward, _wetImageView, _dryImageView, _lblwet, _lblDry, _separator2, _separator3, _lblSpeed, _speedImageView, _lblEndGun, _lblAux1, _lblAux2, _lblProgramStatus, _lblProgramStatusEdit, _btnNext, _separator4, _aux2, _aux1); // this.mapView.AddSubviews(this._topView); this.ContentView.AddSubviews(this._mapView); this.ContentView.AddSubviews(this._topView); }); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); this._mapView.Frame = new CGRect(-150, 0, this.Frame.Width + 150, 390); // hardcoded: 150 is this._topView.Frame.Width that is set below //this.mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; this._topView.Frame = new CGRect(UIScreen.MainScreen.Bounds.Width - 150, 5, 150, 300); this._runningImageView.Frame = new CGRect(3, 8, 30, 30); this._lblRunning.SetFrameLocation(new CGPoint(this._runningImageView.Frame.Right, 5)); this._waitingImageView.Frame = new CGRect(this._lblRunning.Frame.Right, 8, 20, 20); this._separator1.Frame = new CGRect(0, _lblRunning.Frame.Bottom, _topView.Frame.Width, .5); this._forwardImageView.Frame = new CGRect(3, this._separator1.Frame.Bottom + 3, 30, 30); this._lblforward.Frame = new CGRect(this._forwardImageView.Frame.Right, this._separator1.Frame.Bottom, 70, 30); this._separator2.Frame = new CGRect(0, _lblforward.Frame.Bottom, _topView.Frame.Width, .5); this._speedImageView.Frame = new CGRect( /*_forwardImageView.Frame.X _wetImageView.Frame.Right +*/ 2, this._separator2.Frame.Bottom, 35, 35); this._lblSpeed.Frame = new CGRect(_speedImageView.Frame.Right, this._separator2.Frame.Bottom, 70, 30); this._lblWatering.Frame = new CGRect(_lblSpeed.Frame.Right + 5, this._separator2.Frame.Bottom, 70, 30); this._separator3.Frame = new CGRect(0, _lblSpeed.Frame.Bottom, _topView.Frame.Width, .5); this._wetImageView.Frame = new CGRect(3, this._separator3.Frame.Bottom + 3, 30, 30); this._lblwet.Frame = new CGRect(this._wetImageView.Frame.Right, this._separator3.Frame.Bottom, 70, 30); this._dryImageView.Frame = new CGRect(_lblwet.Frame.Right + 1, this._separator3.Frame.Bottom + 5, 25, 25); this._lblDry.Frame = new CGRect(this._dryImageView.Frame.Right, this._separator3.Frame.Bottom, 70, 30); this._separator4.Frame = new CGRect(0, _lblDry.Frame.Bottom, _topView.Frame.Width, .5); this._lblEndGun.Frame = new CGRect(5, this._separator4.Frame.Bottom, 120, 30); this._btnNext.Frame = new CGRect(_topView.Bounds.Right - 40, this._separator4.Frame.Bottom + 4, 30, 30); this._aux1.Frame = new CGRect(9, _lblEndGun.Frame.Bottom + 7, 20, 30); this._lblAux1.Frame = new CGRect(_aux1.Frame.Right + 3, _lblEndGun.Frame.Bottom, 120, 30); this._aux2.Frame = new CGRect(9, _lblAux1.Frame.Bottom + 7, 20, 30); this._lblAux2.Frame = new CGRect(_aux2.Frame.Right + 3, _lblAux1.Frame.Bottom, 120, 30); this._aux1.SizeToFit(); this._aux2.SizeToFit(); this._lblProgramStatus.Frame = new CGRect(5, _lblAux2.Frame.Bottom, 190, 30); this._lblProgramStatusEdit.Frame = new CGRect(5, _lblProgramStatus.Frame.Bottom, 180, 30); if (this._topView.Frame.Height < this._lblProgramStatusEdit.Frame.Bottom) { this._topView.SetFrameHeight(this._lblProgramStatusEdit.Frame.Bottom); } } private string FormatStatusDescription(IEnumerable<string> descriptionTexts) { return ExceptionUtility.Try<string>(() => { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (string s in descriptionTexts) { if (sb.Length > 0) sb.Append(" "); sb.Append(s); } string output = sb.ToString(); output = output.Replace("Go ", "Moving "); return output; }); } private void SetRunningLabelText(string text) { this._lblRunning.SetFrameWidth(100); this._lblRunning.Text = text; //"Moving to 120 at midnight on the seventeenth of April and what was the name of that place again?"; this._lblRunning.SizeToFit(); if (this._lblRunning.Frame.Height < 30) this._lblRunning.SetFrameHeight(30); this._lblRunning.SetFrameWidth(100); } } private class SpecialViewCellMap : FeatureCellforMap { public const string TableCellKeymm = "SpecialViewCellmm"; public SpecialViewCellMap(IntPtr handle) : base(handle) { } public override void LoadCellValues(DeviceDetailViewModel device, DeviceFeatureViewModel feature) { base.LoadCellValues(device, feature); } protected override void HandleLayoutSubviews() { base.HandleLayoutSubviews(); } } public class PivotMapDelegate : MKMapViewDelegate { //protected UIView _pivotView = new UIView(); string pId = "PinAnnotation"; string mId = "PivotAnnotation"; //private string Direction; public DeviceDetailViewModel Device { get; protected set; } public PivotMapDelegate(DeviceDetailViewModel dev) { Device = dev; } public override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) { MKAnnotationView AnnotationView; //this._pivotView = new DrawingView(200, 200, Direction); //this._pivotView.Frame = new CGRect(-80, -80, 150, 150); //this._pivotView.Layer.BorderWidth = 8; //this._pivotView.Layer.BorderColor = UIColor.Gray.CGColor; //this._pivotView.Alpha = .9f; //this._pivotView.Transform.Translate(-80, -80); //this._pivotView.Layer.CornerRadius = this._pivotView.Frame.Width / 2; //this._pivotView.Layer.MasksToBounds = true; //this._pivotView.UserInteractionEnabled = false; if (annotation is MKUserLocation) return null; if (annotation is PivotAnnotation) { try { AnnotationView = mapView.DequeueReusableAnnotation(mId); if (AnnotationView == null) AnnotationView = new MKAnnotationView(annotation, mId); if (Device.Device.CurrentStep != null && Device.Device.CurrentStep.Direction != null && Device.Device.CurrentStep.Direction.Visible) { if (Device.Device.CurrentStep.Direction.Value == "Forward" || Device.Device.CurrentStep.Direction.Value == "1") { AnnotationView.Image = UIImage.FromFile("Images/CurrentAngleFwd.png"); double fromAngle = double.Parse(Device.Device.CurrentAngle.Value); var currentAngle = Math.PI * (fromAngle) / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)currentAngle), 6, -25); } else { AnnotationView.Image = UIImage.FromFile("Images/CurrentAngleRev.png"); double fromAngle = double.Parse(Device.Device.CurrentAngle.Value); var currentAngle = Math.PI * (fromAngle) / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)currentAngle), -6, -25); } } else { AnnotationView.Image = UIImage.FromFile("Images/CurrentAngleLine.png"); double fromAngle = double.Parse(Device.Device.CurrentAngle.Value); double offset = double.Parse(Device.Device.AngleOffset == null ? "0" : Device.Device.AngleOffset.Value); var currentAngle = Math.PI * (fromAngle + offset) / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)currentAngle), 0, -25); } //AnnotationView.SetFrameHeight(int.Parse(Device.Device.MetaData.Device.LengthMetres.Value) / 10); } catch (Exception e) { AnnotationView = mapView.DequeueReusableAnnotation(mId); // double FromAngle = 0; AnnotationView.Image = UIImage.FromFile("Images/CurrentAngleLine.png"); double fromAngle = double.Parse(Device.Device.CurrentAngle.Value); double offset = double.Parse(Device.Device.AngleOffset == null ? "0" : Device.Device.AngleOffset.Value); var currentAngle = Math.PI * (fromAngle + offset) / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)currentAngle), -6, -25); LogUtility.LogException(e); } } else if (annotation is NextLineAnnotation) { AnnotationView = mapView.DequeueReusableAnnotation(mId); try { if (AnnotationView == null) AnnotationView = new MKAnnotationView(annotation, mId); // AnnotationView.Image = UIImage.FromFile("Images/NextAngle.png"); if (Device.Device.CurrentStep?.ToAngle?.Visible ?? false) { AnnotationView.Image = UIImage.FromFile("Images/NextAngle.png"); } else { AnnotationView.Image = UIImage.FromFile("Images/bx3.png"); } double.TryParse(Device.Device.CurrentStep?.ToAngle?.Value, out double toAngle); var nextAngle = Math.PI * toAngle / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)nextAngle), 0, -26); } catch (Exception) { AnnotationView.Image = UIImage.FromFile("Images/NextAngle.png"); double toAngle = 0; var nextAngle = Math.PI * toAngle / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)nextAngle), 0, -26); } //AnnotationView.SetFrameHeight(int.Parse(Device.Device.MetaData.Device.LengthMetres.Value) / 10); } else if (annotation is ZeroAnnotation) { AnnotationView = mapView.DequeueReusableAnnotation(mId); try { if (AnnotationView == null) AnnotationView = new MKAnnotationView(annotation, mId); //AnnotationView.Image = UIImage.FromFile("Images/Zeromark.png"); //double ToAngle = double.Parse(Device.Device.CurrentStep == null ? "0" : Device.Device.CurrentStep.ToAngle.Value); //var Zeromark = Math.PI * ToAngle / 180.0; //AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)Zeromark), 0, -62); AnnotationView.Image = UIImage.FromFile("Images/Zeromark.png"); double toAngle = double.Parse(Device.Device.AngleOffset == null ? "1" : Device.Device.AngleOffset.Value); var zeromark = Math.PI * toAngle / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)zeromark), 0, -62); //AnnotationView.Image = UIImage.FromFile("Images/CurrentAngleFwd.png"); //double FromAngle = double.Parse(Device.Device.CurrentAngle.Value); //var CurrentAngle = Math.PI * (FromAngle) / 180.0; //AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)CurrentAngle), 6, -25); // AnnotationView.Transform = CGAffineTransform.MakeTranslation(0, -(int.Parse(Device.Device.MetaData.Device.LengthMetres.Value)-10)); } catch (Exception) { AnnotationView.Image = UIImage.FromFile("Images/Zeromark.png"); double toAngle = 0; var zeromark = Math.PI * toAngle / 180.0; AnnotationView.Transform = CGAffineTransform.Translate(CGAffineTransform.MakeRotation((float)zeromark), 0, -62); } } else { AnnotationView = (MKPinAnnotationView)mapView.DequeueReusableAnnotation(pId); if (AnnotationView == null) AnnotationView = new MKPinAnnotationView(annotation, pId); ((MKPinAnnotationView)AnnotationView).PinColor = MKPinAnnotationColor.Red; AnnotationView.CanShowCallout = true; } return AnnotationView; } public override MKOverlayView GetViewForOverlay(MKMapView mapView, IMKOverlay overlay) { var circleOverlay = overlay as MKCircle; var circleView = new MKCircleView(circleOverlay); if (Device.Device.CurrentStep != null && Device.Device.CurrentStep.Wet != null && Device.Device.CurrentStep.Wet.Visible) { if (Device.Device.CurrentStep.Wet.Value == "1" || Device.Device.CurrentStep.Wet.Value == "true") { circleView.FillColor = UIColor.FromRGB(57, 198, 249); } else if (Device.Device.CurrentStep.Wet.Value == "0" || Device.Device.CurrentStep.Wet.Value == "false") { circleView.FillColor = UIColor.FromRGB(93, 163, 40); } } else if (Device.IsFaultActive) { circleView.FillColor = UIColor.Red; } else { circleView.FillColor = UIColor.Gray; } circleView.Alpha = 0.9f; circleView.StrokeColor = UIColor.Gray; return circleView; } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EvrakArşiv.Models { public class MyDbInitializer : DropCreateDatabaseAlways<DBContext> { protected override void Seed(DBContext dc) { PersonelGrup personelGrup1 = new PersonelGrup { GrupAdı = "Yönetici" }; dc.PersonelGrups.Add(personelGrup1); dc.SaveChanges(); Personel newPersonel = new Personel { AdıSoyadı = "GAMZE ÖZTÜRK", PersonelYeniMi = true, KullanıcıAdı = "admin", PersonelGrupId = personelGrup1.PersonelGrupId }; dc.Personels.Add(newPersonel); dc.SaveChanges(); MyUtils.Extension.AktifPersonel = newPersonel; Modül modül1 = new Modül { ModülAdı = "Yazışmalar Ekranı" }; dc.Modüls.Add(modül1); Modül modül2 = new Modül { ModülAdı = "Dosyalar Ekranı" }; dc.Modüls.Add(modül2); Modül modül3 = new Modül { ModülAdı = "Döküman Sorgulama Ekranı" }; dc.Modüls.Add(modül3); Modül modül4 = new Modül { ModülAdı = "Kullanıcılar Ekranı" }; dc.Modüls.Add(modül4); dc.SaveChanges(); ModülÖzellik Modül1_Özellik1 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Modüle Erişim" }; dc.ModülÖzelliks.Add(Modül1_Özellik1); ModülÖzellik Modül1_Özellik2 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Yeni Gelen Evrak" }; dc.ModülÖzelliks.Add(Modül1_Özellik2); ModülÖzellik Modül1_Özellik3 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Yeni Giden Evrak" }; dc.ModülÖzelliks.Add(Modül1_Özellik3); ModülÖzellik Modül1_Özellik4 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Cevapla" }; dc.ModülÖzelliks.Add(Modül1_Özellik4); ModülÖzellik Modül1_Özellik5 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Düzenle" }; dc.ModülÖzelliks.Add(Modül1_Özellik5); ModülÖzellik Modül1_Özellik6 = new ModülÖzellik { ModülId = modül1.ModülId, ÖzellikAdı = "Dışa Aktarma" }; dc.ModülÖzelliks.Add(Modül1_Özellik6); dc.SaveChanges(); ModülÖzellik Modül2_Özellik1 = new ModülÖzellik { ModülId = modül2.ModülId, ÖzellikAdı = "Modüle Erişim" }; dc.ModülÖzelliks.Add(Modül2_Özellik1); ModülÖzellik Modül2_Özellik2 = new ModülÖzellik { ModülId = modül2.ModülId, ÖzellikAdı = "Dosya Oluşturma" }; dc.ModülÖzelliks.Add(Modül2_Özellik2); ModülÖzellik Modül2_Özellik3 = new ModülÖzellik { ModülId = modül2.ModülId, ÖzellikAdı = "Dışa Aktarma" }; dc.ModülÖzelliks.Add(Modül2_Özellik3); ModülÖzellik Modül2_Özellik4 = new ModülÖzellik { ModülId = modül2.ModülId, ÖzellikAdı = "Döküman Ekleme" }; dc.ModülÖzelliks.Add(Modül2_Özellik4); ModülÖzellik Modül2_Özellik5 = new ModülÖzellik { ModülId = modül2.ModülId, ÖzellikAdı = "Döküman Silme" }; dc.ModülÖzelliks.Add(Modül2_Özellik5); dc.SaveChanges(); ModülÖzellik Modül3_Özellik1 = new ModülÖzellik { ModülId = modül3.ModülId, ÖzellikAdı = "Modüle Erişim" }; dc.ModülÖzelliks.Add(Modül3_Özellik1); dc.SaveChanges(); ModülÖzellik Modül4_Özellik1 = new ModülÖzellik { ModülId = modül4.ModülId, ÖzellikAdı = "Modüle Erişim" }; dc.ModülÖzelliks.Add(Modül4_Özellik1); dc.SaveChanges(); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik1.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik2.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik3.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik4.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik5.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül1_Özellik6.ÖzellikId, Izin = true }); dc.SaveChanges(); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül2_Özellik1.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül2_Özellik2.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül2_Özellik3.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül2_Özellik4.ÖzellikId, Izin = true }); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül2_Özellik5.ÖzellikId, Izin = true }); dc.SaveChanges(); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül3_Özellik1.ÖzellikId, Izin = true }); dc.SaveChanges(); dc.Grupİzins.Add(new Grupİzin { PersonelGrupId = personelGrup1.PersonelGrupId, ÖzellikId = Modül4_Özellik1.ÖzellikId, Izin = true }); dc.SaveChanges(); dc.KonuBaşlığıs.Add(new KonuBaşlığı { Başlık = "KREDİ BAŞVURUSU"}); dc.KonuBaşlığıs.Add(new KonuBaşlığı { Başlık = "İŞ GÜVENLİĞİ"}); dc.KonuBaşlığıs.Add(new KonuBaşlığı { Başlık = "ESNAF VE SANATKARLAR"}); dc.Dosyas.Add(new Dosya { DosyaAdı = "SAMSUN ESNAF VE SANATKARLAR ODALARI BİRLİĞİ", KayıtOluşturanPersonelId = newPersonel.PersonelId, KayıtOluşturulmaTarihi = DateTime.Now, EnSonGüncelleyenPersonelId = newPersonel.PersonelId, EnSonGüncellemeTarihi = DateTime.Now }); dc.Dosyas.Add(new Dosya { DosyaAdı = "PERSONEL", KayıtOluşturanPersonelId = newPersonel.PersonelId, KayıtOluşturulmaTarihi = DateTime.Now, EnSonGüncelleyenPersonelId = newPersonel.PersonelId, EnSonGüncellemeTarihi = DateTime.Now }); dc.Dosyas.Add(new Dosya { DosyaAdı = "SATIN ALMA", KayıtOluşturanPersonelId = newPersonel.PersonelId, KayıtOluşturulmaTarihi = DateTime.Now, EnSonGüncelleyenPersonelId = newPersonel.PersonelId, EnSonGüncellemeTarihi = DateTime.Now }); dc.Dosyas.Add(new Dosya { DosyaAdı = "DİLEKÇELER", KayıtOluşturanPersonelId = newPersonel.PersonelId, KayıtOluşturulmaTarihi = DateTime.Now, EnSonGüncelleyenPersonelId = newPersonel.PersonelId, EnSonGüncellemeTarihi = DateTime.Now }); dc.GeldiğiYers.Add(new GeldiğiYer { YerAdı = "SAMSUN ESNAF VE SANATKARLAR ODALARI BİRLİĞİ" }); dc.GeldiğiYers.Add(new GeldiğiYer { YerAdı = "HALK BANKASI" }); dc.GeldiğiYers.Add(new GeldiğiYer { YerAdı = "MALİYE BAKANLIĞI" }); dc.GeldiğiYers.Add(new GeldiğiYer { YerAdı = "GÜMRÜK BAKANLIĞI" }); dc.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfApp2 { /// <summary> /// Interaction logic for Menu.xaml /// </summary> public partial class Menu : Window { public Menu() { InitializeComponent(); } private void btnSubmit1_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); } private void btnSubmit2_Click(object sender, RoutedEventArgs e) { Oefening3 oefening3 = new Oefening3(); oefening3.Show(); } private void btnSubmit3_Click(object sender, RoutedEventArgs e) { Oefening4 oefening4 = new Oefening4(); oefening4.Show(); } private void btnSubmit4_Click(object sender, RoutedEventArgs e) { Oefening5 oefening5 = new Oefening5(); oefening5.Show(); } private void btnSubmit5_Click(object sender, RoutedEventArgs e) { Oefening6 oefening6 = new Oefening6(); oefening6.Show(); } } }
using SimpleLogin.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleLogin.Application.Interfaces { public interface IUserProfileAppService : IAppServiceBase<UserProfile> { } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using aspnetHosting = Microsoft.AspNetCore.Hosting; namespace ChatR.Server { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorComponents<App.Startup>(); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, aspnetHosting.IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseSignalR(route => { route.MapHub<NotificationHub>("/notificationhub"); }); app.UseRazorComponents<App.Startup>(); } } public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseEnvironment(aspnetHosting.EnvironmentName.Development); }); } }
using MiEscuela.COMMON.Entidades; using MongoDB.Bson; using System; using System.Collections.Generic; using System.Text; namespace MiEscuela.COMMON.Interfaces { public interface ICompanieroManager : IGenericManager<Companiero> { List<Companiero> CompanieroDeUsuario(ObjectId idUsuario); } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Condition of type `Vector2`. Inherits from `AtomCondition&lt;Vector2&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] public abstract class Vector2Condition : AtomCondition<Vector2> { } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace EmberCore.KernelServices.UI.View { public interface ICoreWpfPlugin { void BuildApplication(Application application); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BinPacking { class Program { static void Main(string[] args) { int capacity = 10; int[] w = { 3, 6, 2, 1, 5, 7, 2, 4, 1, 9 }; Bins bins = new Bins(capacity); foreach (var item in w) { bins.AddFF(item); } Console.WriteLine("Numarul de containere folosite este: {0}", bins.Count); foreach (var item in bins.Items) { Console.WriteLine(item); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DSM.ImportData.Resolvers; using DSM.ImportRegions; using XH.Infrastructure.Domain.Models; using XH.Infrastructure.Domain.Repositories; namespace DSM.ImportData.Tasks { public abstract class ImportTaskBase<T> : ITask where T : EntityBase { private readonly IRepository<T> _repository; private readonly IEntityDataSource<T> _entitySource; public ImportTaskBase(IRepository<T> repository, IEntityDataSource<T> source) { _repository = repository; _entitySource = source; } public void Run() { foreach (var entity in _entitySource) { if (entity != null) { this.OnBeforeInsert(entity); var newEntity = _repository.Insert(entity); this.OnAfterInserted(entity); } } } public virtual void OnBeforeInsert(T entity) { } public virtual void OnAfterInserted(T entity) { } } }
using System; using System.Xml.Serialization; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace PersonnelRecord.Integration { public class Output { private IntegrationModel integrationModelCreate() { _D__MYDB_MDFDataSet dataSet = new _D__MYDB_MDFDataSet(); var employeeTableAdapter = new _D__MYDB_MDFDataSetTableAdapters.EmployeeTableAdapter(); employeeTableAdapter.Fill(dataSet.Employee); List<Employee> employees = new List<Employee>(); foreach (_D__MYDB_MDFDataSet.EmployeeRow row in dataSet.Employee) { int? salary = null; salary = row.IssalaryNull() ? salary : row.salary; Employee employee = new Employee(row.id, row.tabelNumber, row.fio, row.birthdate, row.passportData, row.address, salary); employees.Add(employee); } var positionTableAdapter = new _D__MYDB_MDFDataSetTableAdapters.PositionTableAdapter(); positionTableAdapter.Fill(dataSet.Position); List<Position> positions = new List<Position>(); foreach (_D__MYDB_MDFDataSet.PositionRow row in dataSet.Position) { Position position = new Position(row.id, row.name); positions.Add(position); } var salaryTableAdapter = new _D__MYDB_MDFDataSetTableAdapters.SalaryTableAdapter(); salaryTableAdapter.Fill(dataSet.Salary); List<Salary> salaries = new List<Salary>(); foreach (_D__MYDB_MDFDataSet.SalaryRow row in dataSet.Salary) { DateTime? end = null; end = row.IsdateEndNull() ? end : row.dateEnd; Salary salary = new Salary(row.id, row.position, row.sum, row.dateStart, end); salaries.Add(salary); } var startTableAdapter = new _D__MYDB_MDFDataSetTableAdapters.StartWorkTableAdapter(); startTableAdapter.Fill(dataSet.StartWork); var changeTableAdapter = new _D__MYDB_MDFDataSetTableAdapters.ChangePositionTableAdapter(); changeTableAdapter.Fill(dataSet.ChangePosition); List<EmployeesSalary> employeesSalary = new List<EmployeesSalary>(); foreach (_D__MYDB_MDFDataSet.StartWorkRow row in dataSet.StartWork) { EmployeesSalary salary = new EmployeesSalary(row.employee, row.salary); employeesSalary.Add(salary); } foreach (_D__MYDB_MDFDataSet.ChangePositionRow row in dataSet.ChangePosition) { EmployeesSalary salary = new EmployeesSalary(row.employee, row.salary); employeesSalary.Add(salary); } IntegrationModel integrationModel = new IntegrationModel(employees, positions, salaries, employeesSalary); return integrationModel; } public void output() { IntegrationModel integrationModel = integrationModelCreate(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(IntegrationModel)); StreamWriter streamWriter = new StreamWriter("E:\\integration.xml"); xmlSerializer.Serialize(streamWriter, integrationModel); streamWriter.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; // dodato da bi se koristilo SelectList namespace Knjizara.Models { public class StavkaNarudzbenicaZaposleni { // izabrana vrednost u metodi IzaberiArtikal public static int IdArtikla { get; set; } // metoda koja vraca listu stavkanarudzbenicaviewmodel public static List<StavkaNarudzbenicaViewModel> PrikaziSveStavkeNarudzbenice(int sifra) { using (KnjizaraEntities knjizaraEntitet = new KnjizaraEntities()) { List<StavkaNarudzbenicaViewModel> stavkeNarudzbenice = (from s in knjizaraEntitet.StavkaNarudzbenicas where s.Narudzbenica == sifra select new StavkaNarudzbenicaViewModel { Narudzbenica = s.Narudzbenica, RedniBroj = s.RedniBroj, Artikal = s.Artikal1.NazivArtikla, Kolicina = s.Kolicina, Cena = s.Cena }).ToList(); return stavkeNarudzbenice; } } // metoda koja vraca listu artikala public static void ArtikalIzbor(StavkaNarudzbenica stavkaNarudzbenica) { using (KnjizaraEntities knjizaraEntitet = new KnjizaraEntities()) { List<int> artikalStavkaNarudzbenica = (from s in knjizaraEntitet.StavkaNarudzbenicas where s.Narudzbenica == stavkaNarudzbenica.Narudzbenica select s.Artikal).ToList(); stavkaNarudzbenica.ListaArtikal = (from a in knjizaraEntitet.Artikals where a.Aktivan == 1 && !artikalStavkaNarudzbenica.Contains(a.ArtikalID) || a.ArtikalID == stavkaNarudzbenica.Artikal select a).ToList(); } } // metoda koja vraca listu artikala za dropdownlist public static SelectList IzaberiArtikal(int sifra) { KnjizaraEntities knjizaraEntitet = new KnjizaraEntities(); List<int> artikalStavkaNarudzbenica = (from s in knjizaraEntitet.StavkaNarudzbenicas where s.Narudzbenica == sifra select s.Artikal).ToList(); IEnumerable<SelectListItem> naziviArtikala = (from a in knjizaraEntitet.Artikals where a.Aktivan == 1 && !artikalStavkaNarudzbenica.Contains(a.ArtikalID) select a).AsEnumerable().Select(a => new SelectListItem() { Text = a.NazivArtikla, Value = a.ArtikalID.ToString() }); return new SelectList(naziviArtikala, "Value", "Text", IdArtikla); } // metoda koja kreira novu stavku narudzbenice u tabeli StavkaNarudzbenica public static void KreirajStavkaNarudzbenica(StavkaNarudzbenica novaStavkaNarudzbenica) { using (KnjizaraEntities knjizaraEntitet = new KnjizaraEntities()) { try { Artikal cenaStavkaNarudzbenica = (from a in knjizaraEntitet.Artikals where novaStavkaNarudzbenica.Artikal == a.ArtikalID select a).Single(); novaStavkaNarudzbenica.Cena = cenaStavkaNarudzbenica.Cena * novaStavkaNarudzbenica.Kolicina; knjizaraEntitet.StavkaNarudzbenicas.Add(novaStavkaNarudzbenica); knjizaraEntitet.SaveChanges(); Narudzbenica izmenaCenaNarudzbenica = (from n in knjizaraEntitet.Narudzbenicas where n.NarudzbenicaID == novaStavkaNarudzbenica.Narudzbenica select n).Single(); izmenaCenaNarudzbenica.UkupnaCena = izmenaCenaNarudzbenica.UkupnaCena + novaStavkaNarudzbenica.Cena; knjizaraEntitet.SaveChanges(); } catch (Exception) { } } } // metoda koja vraca stavku narudzbenice s konkretnim Narudzbenica i RedniBroj iz tabele StavkaNarudzbenica public static StavkaNarudzbenica IzaberiStavka(int sifraNarudzbenica, int redniBroj) { using (KnjizaraEntities knjizaraEntitet = new KnjizaraEntities()) { try { StavkaNarudzbenica izborStavka = (from s in knjizaraEntitet.StavkaNarudzbenicas where s.Narudzbenica == sifraNarudzbenica && s.RedniBroj == redniBroj select s).Single(); return izborStavka; } catch (Exception) { return null; } } } // metoda koja menja stavku narudzbenice iz tabele StavkaNarudzbenica public static void IzmeniStavkaNarudzbenica(StavkaNarudzbenica staraStavkaNarudzbenica) { using (KnjizaraEntities knjizaraEntitet = new KnjizaraEntities()) { try { StavkaNarudzbenica izmenaStavkaNarudzbenica = (from s in knjizaraEntitet.StavkaNarudzbenicas where s.Narudzbenica == staraStavkaNarudzbenica.Narudzbenica && s.RedniBroj == staraStavkaNarudzbenica.RedniBroj select s).Single(); izmenaStavkaNarudzbenica.Artikal = staraStavkaNarudzbenica.Artikal; izmenaStavkaNarudzbenica.Kolicina = staraStavkaNarudzbenica.Kolicina; knjizaraEntitet.SaveChanges(); izmenaStavkaNarudzbenica.Cena = izmenaStavkaNarudzbenica.Artikal1.Cena * izmenaStavkaNarudzbenica.Kolicina; knjizaraEntitet.SaveChanges(); Narudzbenica izmenaCenaNarudzbenica = (from n in knjizaraEntitet.Narudzbenicas where n.NarudzbenicaID == staraStavkaNarudzbenica.Narudzbenica select n).Single(); izmenaCenaNarudzbenica.UkupnaCena = 0; knjizaraEntitet.SaveChanges(); } catch (Exception) { } } } } }
using UnityEngine; using System.Collections; /// <summary> /// リザルト画面に出てくる爆弾 /// </summary> public class ResultBomb : MonoBehaviour { //爆発のパーティクル、子オブジェクト private ParticleSystem boomParticle; //collision Collider[] bombColl; //rigidbody Rigidbody rb; void Start() { //パーティクル boomParticle = transform.GetChild(1).GetComponent<ParticleSystem>(); //爆弾のコリジョン bombColl = GetComponents<Collider>(); bombColl[1].enabled = false; //rigidbody rb = GetComponent<Rigidbody>(); } private void OnCollisionEnter(Collision collision) { Explosion(); //爆破処理 } private void OnTriggerEnter(Collider other) { //キューブを破壊 if (other.tag == "Cube") { ResultManager.Instance.blockMap.BreakBlock(other.GetComponent<BlockNumber>()); other.gameObject.SetActive(false); } } private void FixedUpdate() { rb.AddForce(Vector3.down * 25.0f); } /// <summary> /// =爆破処理 /// </summary> void Explosion() { SoundManager.Instance.Bomb(); //爆弾の見た目を消す transform.GetChild(0).gameObject.SetActive(false); //爆弾の位置を固定 rb.constraints = RigidbodyConstraints.FreezeAll; //パーティクル再生 boomParticle.Play(); //爆破の判定を出す bombColl[1].enabled = true; StartCoroutine(DestroyCoroutine()); } /// <summary> /// 破棄するコルーチン /// </summary> IEnumerator DestroyCoroutine() { while (boomParticle.isPlaying) yield return null; Destroy(gameObject); } }
using System; using System.Linq; using System.Web.Mvc; using DataAccess; using DataAccess.Repositories; using FirstMvcApp.Elastic; using FirstMvcApp.Models; using FirstMvcApp.Utils; namespace FirstMvcApp.Controllers { public class ProductController : Controller { private readonly IProductRepository m_iProductRepository = new ProductRepository(); private readonly IFactory<IProduct> m_iproductFactory = StrMapContainer.GetInstance.GetContainer.GetInstance<IFactory<IProduct>>(); private readonly ElasticProvider m_elasticProvider = new ElasticProvider(); private readonly IUserProfileRepository m_iUserProfileRepository = new UserProfileRepository(); private readonly CurrencyInfoProvider m_currencyInfoProvider = new CurrencyInfoProvider(CurrencyInfoProvider.Services.Yahoo); // // GET: /Product/ public ActionResult Index() { var products = m_iProductRepository.GetEntities; var prCount = products.Count; if (!User.Identity.IsAuthenticated) { return View(new ProductSearchModel { Title = "Product list", Products = products.Take(6), ProductsAmount = prCount }); } var userCurrencyCode = m_iUserProfileRepository.GetUserProfileByName(User.Identity.Name).CurrencyCode; if (userCurrencyCode == "USD") { return View(new ProductSearchModel { Title = "Product list", Products = products.Take(6), ProductsAmount = prCount }); } //var rate = m_currencyInfoProvider.GetGoogleFinanceRate(userCurrencyCode); var rate = m_currencyInfoProvider.GetYahooFinanceRate(userCurrencyCode); foreach (var product in products.Take(6)) { product.Price = product.Price*rate; } return View(new ProductSearchModel { Title = "Product list", Products = products.Take(6), ProductsAmount = prCount }); } [Authorize(Roles = "Admin")] public ActionResult ReIndex() { m_elasticProvider.RebuildIndex(); return RedirectToAction("Index"); } public ActionResult Search(string q = "", string ps = "", string p = "", bool exact = false) { int pageSize, page = 0; var queryStringParsed = int.TryParse(ps, out pageSize) && int.TryParse(p, out page); var userCurrencyCode = !User.Identity.IsAuthenticated ? "USD" : m_iUserProfileRepository.GetUserProfileByName(User.Identity.Name).CurrencyCode; decimal rate = 1; if (userCurrencyCode != "USD") { //rate = m_currencyInfoProvider.GetGoogleFinanceRate(userCurrencyCode); rate = m_currencyInfoProvider.GetYahooFinanceRate(userCurrencyCode); } if (q == "") // && ps != "" && p != "")//when the concrete page refreshed (F5 in browser) { if (!queryStringParsed) { return View("Index", new ProductSearchModel { Title = "Wrong page number or page size", ProductsAmount = 0 }); } var dbProducts = m_iProductRepository.GetEntities; if (userCurrencyCode == "USD") { return View("Index", new ProductSearchModel { Title = "Product list", Products = dbProducts.Skip((page - 1)*pageSize).Take(pageSize), ProductsAmount = dbProducts.Count }); } foreach (var product in dbProducts.Skip((page - 1) * pageSize).Take(pageSize)) { product.Price = Math.Round(product.Price*rate, 2); } return View("Index", new ProductSearchModel { Title = "Product list", Products = dbProducts.Skip((page - 1) * pageSize).Take(pageSize), ProductsAmount = dbProducts.Count }); } var unescapedQ = Uri.UnescapeDataString(q); var searchDescriptor = m_elasticProvider.GetSearchDescriptor(unescapedQ, page, pageSize, exact); var searchResults = m_elasticProvider.GetSearchResults(searchDescriptor); var products = searchResults .Documents.Select(r => m_iproductFactory.Create(r)).ToList(); var countResults = searchResults.Total; if (userCurrencyCode == "USD") { return View("Index", new ProductSearchModel { Title = "Search results for \"" + unescapedQ + "\"", Products = products, ProductsAmount = countResults }); } foreach (var product in products) { product.Price = Math.Round(product.Price*rate, 2); } return View("Index", new ProductSearchModel { Title = "Search results for \"" + unescapedQ + "\"", Products = products, ProductsAmount = countResults }); } public ActionResult Details(int id = 0) { var iProduct = m_iProductRepository.GetById(id); if (iProduct == null) { return HttpNotFound(); } return View(iProduct); } // // GET: /Product/Create public ActionResult Create() { return View(); } // // POST: /Product/Create //[HttpPost] //[ValidateAntiForgeryToken] //public ActionResult Create(Product product) //{ // //if (!ModelState.IsValid) // //{ // // return View(product); // //} // //var iProduct = m_iproductFactory.Create(product); // //m_iProductRepository.Insert(iProduct); // return RedirectToAction("Index"); //} // // GET: /Product/Edit/5 public ActionResult Edit(int id = 0) { var iProduct = m_iProductRepository.GetById(id); if (iProduct == null) { return HttpNotFound(); } return View(iProduct); } // // POST: /Product/Edit/5 //[HttpPost] ////[ValidateAntiForgeryToken] //public ActionResult Edit(Product product) //{ // if (!ModelState.IsValid) // { // //var iProduct = _iproductFactory.Create(product); // return Json(new { Success = false, Message = "Not valid form" }); // View(); // } // var editedProduct = m_iProductRepository.GetById(product.ProductId); // editedProduct.Category = product.Category; // editedProduct.Name = product.Name; // editedProduct.Description = product.Description; // editedProduct.Price = product.Price; // m_iProductRepository.Save(); // return Json(new { Success = true }); //} // // GET: /Product/Delete/5 public ActionResult Delete(int id = 0) { var iProduct = m_iProductRepository.GetById(id); if (iProduct == null) { return HttpNotFound(); } //var product = new Product //{ // Category = iProduct.Category, // Description = iProduct.Description, // Name = iProduct.Name, // Price = iProduct.Price, // ProductId = iProduct.ProductId //}; return View(iProduct); } // // POST: /Product/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { var iProduct = m_iProductRepository.GetById(id); m_iProductRepository.Delete(iProduct); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { //db.Dispose(); base.Dispose(disposing); } } }
using EduHome.DataContext; using EduHome.Models.Entity; using EduHome.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.Controllers { public class EventController : Controller { private readonly EduhomeDbContext _db; public EventController(EduhomeDbContext db) { _db = db; } public IActionResult Index() { var events = _db.Events.Include(e => e.Course).ThenInclude(c => c.Category).Include(e=>e.TimeInterval).Include(e => e.PostMessages). Include(e => e.EventSpeakers).ThenInclude(es => es.Speaker).Where(e => e.IsDeleted == false).ToList(); return View(events); } public IActionResult Detail(int? id) { if (id == null) { return NotFound(); } Event @event = _db.Events.Include(p => p.Course).ThenInclude(c => c.Category).Include(e => e.TimeInterval).Include(e => e.PostMessages). Include(e => e.EventSpeakers).ThenInclude(es => es.Speaker).Where(p => p.IsDeleted == false).FirstOrDefault(b => b.Id == id); if (@event == null) { return BadRequest(); } EventDetailVM eventDetailVM = new EventDetailVM { Event = @event, PostMessages = _db.PostMessages.Include(pm => pm.Event).Include(pm => pm.Post).Where(pm => pm.EventId == id).ToList() }; return View(eventDetailVM); } [HttpPost] [AutoValidateAntiforgeryToken] public IActionResult Detail(int? id, PostMessage postMessage) { if (id == null) { return NotFound(); } Event @event = _db.Events.Include(p => p.Course).ThenInclude(c => c.Category).Include(e => e.PostMessages).Include(e=>e.TimeInterval). Include(e => e.EventSpeakers).ThenInclude(es => es.Speaker).Where(p => p.IsDeleted == false).FirstOrDefault(b => b.Id == id); if (@event == null) { return BadRequest(); } if (@event.Id != id) { return BadRequest(); } postMessage.EventId = @event.Id; EventDetailVM eventDetailVM = new EventDetailVM { Event = @event, PostMessages = _db.PostMessages.Include(pm => pm.Event).Include(pm => pm.Contact).Include(pm => pm.Course).Include(pm => pm.Post). Where(pm => pm.EventId == id && pm.IsDeleted == false).ToList(), PostMessage = postMessage }; if (!ModelState.IsValid) { return View(eventDetailVM); } eventDetailVM.PostMessages.Add(postMessage); _db.Add(postMessage); _db.SaveChanges(); return View(eventDetailVM); } } }
using System.Collections; using UnityEngine; namespace Assets.Scripts.Service { public class CameraZoomService : MonoBehaviour { public delegate void ZoomedOut(); public ZoomedOut onZoomedOut; [SerializeField] private GameObject _blocksParent; [SerializeField] private Transform _startBlock; private Transform _lastBlock; private const float DEFAULT_SIZE = 20f; private const float EPSILON = 0.1f; private IEnumerator _currentCoroutine; public void ZoomIn() { Camera.main.orthographicSize = DEFAULT_SIZE; } public void ZoomOut() { _lastBlock = _blocksParent.transform.GetChild(0); StartCoroutine(MoveCamera()); } private IEnumerator MoveCamera() { float delta = 0.2f; bool isFirstBlockOnScreen = false; bool isLastBlockOnScreen = false; while (!isFirstBlockOnScreen || !isLastBlockOnScreen) { Vector3 screenPointFirst = Camera.main.WorldToViewportPoint(_startBlock.position); isFirstBlockOnScreen = screenPointFirst.z > 0 && screenPointFirst.x > 0 && screenPointFirst.x < 1 && screenPointFirst.y > 0 && screenPointFirst.y < 1; Vector3 screenPointLast = Camera.main.WorldToViewportPoint(_lastBlock.position); isLastBlockOnScreen = screenPointLast.z > 0 && screenPointLast.x > 0 && screenPointLast.x < 1 && screenPointLast.y > 0 && screenPointLast.y < 1; Camera.main.orthographicSize += delta; yield return null; } yield return new WaitForSeconds(0.5f); onZoomedOut?.Invoke(); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Enemy : MonoBehaviour { public ParticleSystem explosion; public Image healthImage; public float Health; public float MaxHealth; public float Damage; public float Speed; public int Score; public Animation anim; public PlayerController player; public Transform target; Vector3 destination; NavMeshAgent agent; // Use this for initialization public virtual void Start() { target = GameObject.FindGameObjectWithTag("Player").transform; if (target == null) Debug.Log("target null"); agent = gameObject.GetComponent<NavMeshAgent>(); player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>(); anim = GetComponent<Animation>(); } // Update is called once per frame public virtual void Update() { agent.SetDestination(target.position); } public void TakeDamage(float damage) { Health -= damage; healthImage.fillAmount = Health / MaxHealth; if (Health <= 0) { Die(); } } public void Attack() { player.TakeDamage(Damage); } public virtual void Die() { player.score += Score; Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } float timeElapsed = 1.1f; void OnTriggerStay(Collider other) { if (other.tag == "Player") { anim.Play("robot_fallus|attack"); anim.Play("Armature|attack"); if (timeElapsed > 1.0f) { Attack(); timeElapsed = 0; } } timeElapsed += Time.deltaTime; } void OnTriggerExit(Collider other) { anim.Play("robot_fallus|walk.001"); anim.Play("Armature|walk.001"); timeElapsed = 1.1f; } }
using ArquiteturaLimpaMVC.Aplicacao.Produtos.Commands; using ArquiteturaLimpaMVC.Dominio.Entidades; using ArquiteturaLimpaMVC.Dominio.Interfaces; using MediatR; using System; using System.Threading; using System.Threading.Tasks; namespace ArquiteturaLimpaMVC.Aplicacao.Produtos.Handlers { public class RemoverProdutoCommandHandler : IRequestHandler<RemoverProdutoCommand, Produto> { private readonly IProdutoRepository _produtoRepository; public RemoverProdutoCommandHandler(IProdutoRepository produtoRepository) { _produtoRepository = produtoRepository; } public async Task<Produto> Handle(RemoverProdutoCommand request, CancellationToken cancellationToken) { var produto = await _produtoRepository.ProdutoPorIdAsync(request.Id); if (produto is null) throw new ApplicationException("A entidade não foi encontrada!"); return await _produtoRepository.RemoverAsync(produto); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovemet : MonoBehaviour { public GameObject playerCreatPoint; public PlayerJumpMechanism pjm; public SpinMechanisum sm; Vector3 positionAtStart; Quaternion rotationAtstart; Rigidbody selfRigitbody; // Start is called before the first frame update void Start() { playerCreatPoint = GameObject.FindGameObjectWithTag("PlayerCreatpoint"); //get start rotation and position //positionAtStart = transform.position; rotationAtstart = transform.rotation; selfRigitbody = GetComponent<Rigidbody>(); GameObject go = GameObject.FindGameObjectWithTag("PlayerMovementControlar"); pjm = go.GetComponent<PlayerJumpMechanism>(); sm = go.GetComponent<SpinMechanisum>(); } /// <summary> /// if faild to complet task rest player postion at start, and reset player jump Mechanism and spin Mechanism /// </summary> public void Retry() { transform.position = playerCreatPoint.transform.position; transform.rotation = rotationAtstart; selfRigitbody.isKinematic = false; selfRigitbody.useGravity = false; pjm.Retry(); sm.Retry(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using Xamarin.Forms; using KSF_Surf.ViewModels; using KSF_Surf.Models; using System.Collections.ObjectModel; namespace KSF_Surf.Views { [DesignTimeVisible(false)] public partial class RecordsTopCountriesPage : ContentPage { private readonly RecordsViewModel recordsViewModel; private bool hasLoaded = false; private bool isLoading = false; private readonly int CALL_LIMIT = 250; // objects used by "SurfTop" call private List<CountryPoints> topCountriesData; private int list_index = 1; // variables for filters private readonly EFilter_Game defaultGame; private readonly EFilter_Mode defaultMode; private EFilter_Game game; private EFilter_Mode mode; // collection view public ObservableCollection<Tuple<string, string>> recordsTopCountriesCollectionViewItemsSource { get; } = new ObservableCollection<Tuple<string, string>>(); public RecordsTopCountriesPage(EFilter_Game game, EFilter_Mode mode, EFilter_Game defaultGame, EFilter_Mode defaultMode) { this.game = game; this.mode = mode; this.defaultGame = defaultGame; this.defaultMode = defaultMode; recordsViewModel = new RecordsViewModel(); InitializeComponent(); Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]"; RecordsTopCountriesCollectionView.ItemsSource = recordsTopCountriesCollectionViewItemsSource; } // UI ----------------------------------------------------------------------------------------------- #region UI private async Task ChangeTopCountries(bool clearPrev) { var topCountriesDatum = await recordsViewModel.GetTopCountries(game, mode, list_index); topCountriesData = topCountriesDatum?.data; if (topCountriesData is null) return; if (clearPrev) recordsTopCountriesCollectionViewItemsSource.Clear(); LayoutTopCountries(); Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]"; } // Displaying Changes ------------------------------------------------------------------------------- private void LayoutTopCountries() { foreach (CountryPoints datum in topCountriesData) { string countryString = list_index + ". " + String_Formatter.toEmoji_Country(datum.country) + " " + datum.country; string pointsString = String_Formatter.toString_Points(datum.points); recordsTopCountriesCollectionViewItemsSource.Add(new Tuple<string, string>(countryString, pointsString)); list_index++; } } #endregion // Event Handlers ---------------------------------------------------------------------------------- #region events protected override async void OnAppearing() { if (!hasLoaded) { hasLoaded = true; await ChangeTopCountries(false); LoadingAnimation.IsRunning = false; RecordsTopCountriesStack.IsVisible = true; } } private async void RecordsTopCoutries_ThresholdReached(object sender, EventArgs e) { if (isLoading || !BaseViewModel.hasConnection() || list_index == CALL_LIMIT) return; isLoading = true; LoadingAnimation.IsRunning = true; await ChangeTopCountries(false); LoadingAnimation.IsRunning = false; isLoading = false; } private async void Filter_Pressed(object sender, EventArgs e) { if (hasLoaded && BaseViewModel.hasConnection()) { await Navigation.PushAsync(new RecordsFilterPage(ApplyFilters, game, mode, defaultGame, defaultMode)); } else { await DisplayNoConnectionAlert(); } } internal async void ApplyFilters(EFilter_Game newGame, EFilter_Mode newMode) { if (newGame == game && newMode == mode) return; if (BaseViewModel.hasConnection()) { game = newGame; mode = newMode; list_index = 1; LoadingAnimation.IsRunning = true; isLoading = true; await ChangeTopCountries(true); LoadingAnimation.IsRunning = false; isLoading = false; } else { await DisplayNoConnectionAlert(); } } private async Task DisplayNoConnectionAlert() { await DisplayAlert("Could not connect to KSF!", "Please connect to the Internet.", "OK"); } #endregion } }
using System; using System.Collections; // L-System rule class public class rules { public rules(char index, string rule) { this.Index = index; this.Rule = rule; } // The character corresponding to the associated rule. private char _Index; public char Index { set { this._Index = value; } get { return this._Index; } } // The rule at a certain character index. private string _Rule; public string Rule { set { this._Rule = value; } get { return this._Rule; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NPCSimplePatrol : MonoBehaviour { //Dictates whether the agent waits on each node. [SerializeField] bool patrolWaiting; //The total time we wait at each node. [SerializeField] float totalWaitTime = 3f; //The probability of switching direction. //[SerializeField] //float switchProbability = 0.0f; //The list of all patrol nodes to visit. [SerializeField] List<Waypoint> patrolPoints; //Private variables for base behaviour. NavMeshAgent navMeshAgent; int currentPatrolIndex; bool travelling; bool waiting; bool patrolForward = true; float waitTimer; // Use this for initialization public void Start() { navMeshAgent = this.GetComponent<NavMeshAgent>(); if (navMeshAgent == null) { Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name); } else { if (patrolPoints != null && patrolPoints.Count >= 2) { currentPatrolIndex = 0; SetDestination(); } else { Debug.Log("Insufficient patrol points for basic patrolling behaviour."); } } } public void Update() { //Check if we're close to the destination. if (travelling && navMeshAgent.remainingDistance <= 1.0f) { travelling = false; //If we're going to wait, then wait. if (patrolWaiting) { waiting = true; waitTimer = 0f; } else { ChangePatrolPoint(); SetDestination(); } } //Instead if we're waiting. if (waiting) { waitTimer += Time.deltaTime; if (waitTimer >= totalWaitTime) { waiting = false; ChangePatrolPoint(); SetDestination(); } } } private void SetDestination() { if (patrolPoints != null) { Vector3 targetVector = patrolPoints[currentPatrolIndex].transform.position; navMeshAgent.SetDestination(targetVector); travelling = true; } } /// <summary> /// Selects a new patrol point in the available list, but /// also with a small probability allows for us to move forward or backwards. /// </summary> private void ChangePatrolPoint() { //if (UnityEngine.Random.Range(0f, 1f) <= switchProbability) //{ //invert the boolean's current status // patrolForward = !patrolForward; //} if (patrolForward) { currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Count; } else { if (--currentPatrolIndex < 0) { currentPatrolIndex = patrolPoints.Count - 1; } } } }
using System.ComponentModel.DataAnnotations; namespace Alabo.Cloud.School.BookingSignup.Domain.Enums { /// <summary> /// 活动状态 /// </summary> public enum BookingSignupState { /// <summary> /// 预定 /// </summary> [Display(Name = "预定中")] Book = 1, /// <summary> /// 进行中 /// </summary> [Display(Name = "进行中")] processing = 2, /// <summary> /// 结束 /// </summary> [Display(Name = "已结束")] End = 3 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Timeclock.Core.Domain; using TimeClock.Data.Models; namespace TimeClock.Data { public class TimeReportDaily : ITimeReportDaily { public DateTime Date { get; set; } public IEnumerable<TimePunch> TimePunches { get; set; } //TODO: Place holder, we need to calculate time worked for display+ public double TimeWorked { get; set; } } }
using EmberKernel.Plugins; using EmberKernel.Plugins.Models; using EmberKernel.Services.UI.Mvvm.ViewComponent.Window; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Windows.Input; namespace EmberKernel.Services.UI.Mvvm.ViewModel.Plugins { public class PluginManagerViewModel : ObservableCollection<PluginDescriptor>, IPluginManagerViewModel, IDisposable { private readonly IDisposable _onPluginLoad; private readonly IDisposable _onPluginUnload; private readonly IDisposable _onPluginInitialized; private IWindowManager WindowManager { get; } private IPluginsManager PluginsManager { get; } public PluginManagerViewModel(IPluginsManager pluginsManager, IWindowManager windowManager) { WindowManager = windowManager; PluginsManager = pluginsManager; InitializePlugins(); _onPluginLoad = PluginsManager.OnPluginLoad((descriptor) => { AddPlugin(descriptor); WindowManager.BeginUIThreadScope(() => OnPropertyChanged(new PropertyChangedEventArgs(descriptor.ToString()))); }); _onPluginUnload = PluginsManager.OnPluginUnload((descriptor) => { WindowManager.BeginUIThreadScope(() => OnPropertyChanged(new PropertyChangedEventArgs(descriptor.ToString()))); }); _onPluginInitialized = PluginsManager.OnPluginInitialized((descriptor) => { WindowManager.BeginUIThreadScope(() => OnPropertyChanged(new PropertyChangedEventArgs(descriptor.ToString()))); }); } private void InitializePlugins() { foreach (var item in PluginsManager.LoadedPlugins()) { AddPlugin(item); } } public void DisablePlugin(PluginDescriptor item) { if (PluginsManager.GetPluginByDescriptor(item) is IPlugin plugin) { PluginsManager.Unload(plugin); } } public void EnablePlugin(PluginDescriptor item) { if (PluginsManager.GetPluginByDescriptor(item) is IPlugin plugin) { PluginsManager.Load(plugin); PluginsManager.Initialize(plugin); } } public bool IsPluginInitialized(PluginDescriptor item) { if (PluginsManager.GetPluginByDescriptor(item) is IPlugin plugin) { return PluginsManager.IsPluginInitialized(plugin); } return false; } private void AddPlugin(PluginDescriptor item) { WindowManager.BeginUIThreadScope(() => { if (this.Any(desc => desc.ToString() == item.ToString())) return; Add(item); }); } public void Dispose() { _onPluginLoad.Dispose(); _onPluginUnload.Dispose(); _onPluginInitialized.Dispose(); } } }
using UnityEngine; using System.Collections; using UnityEngine.Networking; class MBCRequestLogin : MessageBase { public string networkmsg = ""; } public class GameClient : MonoBehaviour { public NetworkClient Client; public string msg = "test"; public bool connected = false; private string stringport = ""; private int port = 0000; // Variable for Network Message private string text = ""; private string sendtoservertext = ""; private string stringconId = "0"; private string rcvmsg =""; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (NetworkClient.active == true) { Client.RegisterHandler (1000,ReadNetworkMessage); } } void OnGUI() { stringport = GUI.TextField (new Rect(140,10,50,30),stringport,5); if(GUI.RepeatButton (new Rect (20, 10, 100, 30),"Connect") && !connected) { msg = "Client is connected"; connected = true; port = int.Parse (stringport); ConnectToServer (port); } if(GUI.RepeatButton (new Rect (20, 50, 100, 30),"Disconnect") && connected) { msg = "Client is Disconnected"; connected = false; DisconnectToServer (); } if(GUI.RepeatButton (new Rect (20, 90, 100, 30),"Connection")) { msg = Client.connection.ToString(); } GUI.TextArea (new Rect (200,10,150,30),msg); //////////////////////////////////////////Network Message////////////////////////////////////////////// sendtoservertext = GUI.TextField (new Rect(180,150,100,30),sendtoservertext,50); if(GUI.RepeatButton (new Rect (20, 150, 140, 30),"Send to Server")) { var messageb = new MessageBaseClient (); messageb.networkmsg = sendtoservertext; Client.Send (1000,messageb); } GUI.TextArea (new Rect(20,230,260,180),rcvmsg); } public void ReadNetworkMessage (NetworkMessage netmsg){ MessageBaseClient messageb = netmsg.ReadMessage<MessageBaseClient>(); rcvmsg = messageb.networkmsg.ToString (); Debug.Log ("Recieved Network Message" + rcvmsg); } public void ConnectToServer(int port) { string IpAddress = "127.0.0.1"; Client = new NetworkClient (); Client.Connect (IpAddress, port); } public void DisconnectToServer() { Client.Disconnect (); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TCPServer { class Server { static List<ClientHandler> serverCH = new List<ClientHandler>(); static void check() { Console.WriteLine("hello"); } static void pause() { while (true) { } } static void Main(string[] args) { TcpListener listener = new TcpListener(8888); int numberOfC = 0; TcpClient temp; NetworkStream stream; Thread checker = new Thread(checkAll); checker.Start(); //listen while (true) { listener.Start(); temp = listener.AcceptTcpClient(); numberOfC += 1; serverCH.Add(new ClientHandler(temp,numberOfC)); } } static void checkAll() { while (true) { try { foreach (ClientHandler x in serverCH) { if (x.status == "error") serverCH.Remove(x); } } catch (Exception e) { Console.WriteLine("Empty"); } Console.Clear(); Console.WriteLine("number of online clients: " + serverCH.Count); Thread.Sleep(1000); } } } class ClientHandler { TcpClient client = default(TcpClient); int clientID = 0; Thread main; public string status = "ok"; public ClientHandler(TcpClient c,int number) { this.client = c; this.clientID = number; main = new Thread(this.run); main.Start(); } //listen void run() { NetworkStream stream; client.ReceiveBufferSize = 2000; //clientHandle try { while (true) { //recv stream = client.GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; stream.Read(buffer, 0, buffer.Length); //showResult(Encoding.ASCII.GetString(buffer)); //send confirm buffer = Encoding.ASCII.GetBytes("OK\n"); stream.Write(buffer, 0, buffer.Length); stream.Flush(); } } catch (Exception e) { Console.WriteLine(">> UserID "+clientID+" offline..."); Thread.Sleep(1000); status = "error"; } } void showResult(string a) { //Console.Clear(); Console.WriteLine("clientID: "+ clientID+"\n"+a); } } }
using System; using System.Collections.Generic; using System.Linq; namespace UnitTests.Utils { internal static class EnumerableExtensions { public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> action) { // ReSharper disable ReturnValueOfPureMethodIsNotUsed source.Select((item, index) => { action(item, index); return 0; }).ToList(); // ReSharper restore ReturnValueOfPureMethodIsNotUsed } } }
using System.Data.Entity.ModelConfiguration; using Properties.Core.Objects; namespace Properties.Infrastructure.Data.Mapping { public class CertificateMap : EntityTypeConfiguration<Certificate> { public CertificateMap() { Property(x => x.CertificateReference) .HasMaxLength(25); Property(p => p.CertificateUrl) .HasColumnType("nvarchar"); Ignore(p => p.IsDirty); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CapaDatos { public class DOrdenCompra { SqlConnection cn; public DataTable SelectOrdenesCompra() { DataTable miTabla = new DataTable("1_orden_compra"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("SelectOrdenesCompra", cn) { CommandType = CommandType.StoredProcedure }; adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } public DataTable SelectOrdenesCompraSinFactura() { DataTable miTabla = new DataTable("1_orden_compra"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("SelectOrdenesCompraSinFactura", cn) { CommandType = CommandType.StoredProcedure }; adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } public DataTable SelectOrdenCompraSinInforme() { DataTable miTabla = new DataTable("1_orden_compra"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("SelectOrdenCompraSinInforme", cn) { CommandType = CommandType.StoredProcedure }; adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } public DataTable SelectOrdenesCompraByTipo(string tipo) { DataTable miTabla = new DataTable("1_orden_compra"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("SelectOrdenesCompraByTipo", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@tipo", tipo); adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } public DataTable GetStockOrdenCompraPR(int cod_ord_cpr) { DataTable miTabla = new DataTable("1_stock_pr"); SqlDataAdapter adapter; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("GetStockOrdenCompraPR", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", cod_ord_cpr); adapter = new SqlDataAdapter(cmd); adapter.Fill(miTabla); } cn.Close(); return miTabla; } public int InsertOrdenCompra(bool emitido, string tipo) { int resultado; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("InsertOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@emitido", emitido); cmd.Parameters.AddWithValue("@tipo", tipo); resultado = (int)cmd.ExecuteScalar(); cn.Close(); return resultado; } } public string GetTipoOrdenCompra(int codOrdenCompra) { string resultado; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("GetTipoOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", codOrdenCompra); resultado = cmd.ExecuteScalar().ToString(); cn.Close(); return resultado; } } public int GetProveedorEnOrdenCompra(int codOrdenCompra) { int resultado; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("GetProveedorEnOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", codOrdenCompra); resultado = (int)cmd.ExecuteScalar(); cn.Close(); return resultado; } } public string EmitirOrdenCompra(DateTime fecha, int codOrdenCompra) { string respuesta; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("EmitirOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@fecha", fecha); cmd.Parameters.AddWithValue("@cod_ord_cpr", codOrdenCompra); respuesta = cmd.ExecuteNonQuery() == 1 ? "Se emitió la orden de compra correctamente" : "Error al emitir la orden"; cn.Close(); return respuesta; } } public void DeleteOrdenCompra(int cod_ord_cpr) { using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("DeleteOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", cod_ord_cpr); cmd.ExecuteNonQuery(); cn.Close(); } } public string EmitirOrdenCompra(int cod_ord_cpr, DateTime fecha) { string respuesta; using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("EmitirOrdenCompra", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", cod_ord_cpr); cmd.Parameters.AddWithValue("@fecha", fecha); respuesta = cmd.ExecuteNonQuery() == 1 ? "Se emitió la orden de compra correctamente" : "Error al emitir la orden"; cn.Close(); return respuesta; } } public bool OrdenCompraTieneFacturaAsociada(int cod_ord_cpr) { using (cn = Conexion.ConexionDB()) { SqlCommand cmd = new SqlCommand("OrdenCompraTieneFacturaAsociada", cn) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@cod_ord_cpr", cod_ord_cpr); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { cn.Close(); return true; } else { cn.Close(); return false; } } } } }
using System.Drawing; namespace SpreadsheetGUI { public class Client { public Color Color; public string SelectedCell; } }
using System; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Vanara.InteropServices; using static Vanara.PInvoke.Ole32; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { /// <summary>Platform invokable enumerated types, constants and functions from propsys.h</summary> public static partial class PropSys { /// <summary>Values used by the <see cref="PropVariantChangeType"/> function.</summary> [PInvokeData("Propvarutil.h")] [Flags] public enum PROPVAR_CHANGE_FLAGS { /// <summary>The PVCHF default</summary> PVCHF_DEFAULT = 0x00000000, /// <summary>Maps to VARIANT_NOVALUEPROP for VariantChangeType</summary> PVCHF_NOVALUEPROP = 0x00000001, /// <summary>Maps to VARIANT_ALPHABOOL for VariantChangeType</summary> PVCHF_ALPHABOOL = 0x00000002, /// <summary>Maps to VARIANT_NOUSEROVERRIDE for VariantChangeType</summary> PVCHF_NOUSEROVERRIDE = 0x00000004, /// <summary>Maps to VARIANT_LOCALBOOL for VariantChangeType</summary> PVCHF_LOCALBOOL = 0x00000008, /// <summary>Don't convert a string that looks like hexadecimal (0xABCD) to the numerical equivalent.</summary> PVCHF_NOHEXSTRING = 0x00000010 } /// <summary>Values used by the <see cref="PropVariantCompareEx"/> function.</summary> [Flags] [PInvokeData("Propvarutil.h")] public enum PROPVAR_COMPARE_FLAGS { /// <summary>When comparing strings, use StrCmpLogical</summary> PVCF_DEFAULT = 0x00000000, /// <summary>Empty/null values are greater-than non-empty values</summary> PVCF_TREATEMPTYASGREATERTHAN = 0x00000001, /// <summary>When comparing strings, use StrCmp</summary> PVCF_USESTRCMP = 0x00000002, /// <summary>When comparing strings, use StrCmpC</summary> PVCF_USESTRCMPC = 0x00000004, /// <summary>When comparing strings, use StrCmpI</summary> PVCF_USESTRCMPI = 0x00000008, /// <summary>When comparing strings, use StrCmpIC</summary> PVCF_USESTRCMPIC = 0x00000010, /// <summary> /// When comparing strings, use CompareStringEx with LOCALE_NAME_USER_DEFAULT and SORT_DIGITSASNUMBERS. This corresponds to the /// linguistically correct order for UI lists. /// </summary> PVCF_DIGITSASNUMBERS_CASESENSITIVE = 0x00000020, } /// <summary>Values used by the <see cref="PropVariantCompareEx"/> function.</summary> [PInvokeData("Propvarutil.h")] public enum PROPVAR_COMPARE_UNIT { /// <summary>The default unit.</summary> PVCU_DEFAULT = 0, /// <summary>The second comparison unit.</summary> PVCU_SECOND = 1, /// <summary>The minute comparison unit.</summary> PVCU_MINUTE = 2, /// <summary>The hour comparison unit.</summary> PVCU_HOUR = 3, /// <summary>The day comparison unit.</summary> PVCU_DAY = 4, /// <summary>The month comparison unit.</summary> PVCU_MONTH = 5, /// <summary>The year comparison unit.</summary> PVCU_YEAR = 6 } /// <summary>Values used by the <see cref="PropVariantToFileTime"/> function.</summary> [PInvokeData("Propvarutil.h")] public enum PSTIME_FLAGS { /// <summary>Indicates the output will use coordinated universal time.</summary> PSTF_UTC = 0x00000000, /// <summary>Indicates the output will use local time.</summary> PSTF_LOCAL = 0x00000001 } /// <summary> /// <para>Frees the memory and references used by an array of PROPVARIANT structures stored in an array.</para> /// </summary> /// <param name="rgPropVar"> /// <para>Type: <c>PROPVARIANT*</c></para> /// <para>Array of PROPVARIANT structures to free.</para> /// </param> /// <param name="cVars"> /// <para>Type: <c>UINT</c></para> /// <para>The number of elements in the array specified by rgPropVar.</para> /// </param> /// <returns> /// <para>No return value.</para> /// </returns> /// <remarks> /// <para> /// This function releases the memory and references held by each structure in the array before setting the structures to zero. /// </para> /// <para>This function performs the same action as FreePropVariantArray, but <c>FreePropVariantArray</c> returns an <c>HRESULT</c>.</para> /// <para>Examples</para> /// <para>The following example, to be included as part of a larger program, demonstrates how to use ClearPropVariantArray</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-clearpropvariantarray PSSTDAPI_(void) // ClearPropVariantArray( PROPVARIANT *rgPropVar, UINT cVars ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "e8d7f951-8a9e-441b-9fa7-bf21cf08c8ac")] public static extern HRESULT ClearPropVariantArray([In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] PROPVARIANT[] rgPropVar, uint cVars); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure from a specified Boolean vector.</summary> /// <param name="prgf"> /// Pointer to the Boolean vector used to initialize the structure. If this parameter is NULL, the elements pointed to by the /// cabool.pElems structure member are initialized with VARIANT_FALSE. /// </param> /// <param name="cElems">The number of vector elements.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762288")] public static extern HRESULT InitPropVariantFromBooleanVector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.Bool)] bool[] prgf, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure using the contents of a buffer.</summary> /// <param name="pv">Pointer to the buffer.</param> /// <param name="cb">The length of the buffer, in bytes.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762289")] public static extern HRESULT InitPropVariantFromBuffer([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.U1)] byte[] pv, uint cb, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a class identifier (CLSID).</summary> /// <param name="clsid">Reference to the CLSID.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762290")] public static extern HRESULT InitPropVariantFromCLSID(in Guid clsid, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified vector of double values.</summary> /// <param name="prgn"> /// Pointer to a double vector. If this value is NULL, the elements pointed to by the cadbl.pElems structure member are initialized /// with 0.0. /// </param> /// <param name="cElems">The number of vector elements.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762292")] public static extern HRESULT InitPropVariantFromDoubleVector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.R8)] double[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on information stored in a <see cref="FILETIME"/> structure.</summary> /// <param name="pftIn">Pointer to the date and time as a <see cref="FILETIME"/> structure.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762293")] public static extern HRESULT InitPropVariantFromFileTime(in FILETIME pftIn, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure from a specified vector of <see cref="FILETIME"/> values.</summary> /// <param name="prgft"> /// Pointer to the date and time as a <see cref="FILETIME"/> vector. If this value is NULL, the elements pointed to by the /// cafiletime.pElems structure member is initialized with (FILETIME)0. /// </param> /// <param name="cElems">The number of vector elements.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762294")] public static extern HRESULT InitPropVariantFromFileTimeVector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] FILETIME[] prgft, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary> /// <para>Initializes a PROPVARIANT structure based on a <c>GUID</c>. The structure is initialized as VT_LPWSTR.</para> /// </summary> /// <param name="guid"> /// <para>Type: <c>REFGUID</c></para> /// <para>Reference to the source <c>GUID</c>.</para> /// </param> /// <param name="ppropvar"> /// <para>Type: <c>PROPVARIANT*</c></para> /// <para>When this function returns, contains the initialized PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>Creates a VT_LPWSTR PROPVARIANT, which formats the GUID in a form similar to .</para> /// <para>Examples</para> /// <para>The following example, to be included as part of a larger program, demonstrates how to use <c>InitPropVariantFromGUIDAsString</c>.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-initpropvariantfromguidasstring PSSTDAPI // InitPropVariantFromGUIDAsString( REFGUID guid, PROPVARIANT *ppropvar ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "bcc343f7-741f-4cdd-bd2f-ae4786faab0e")] public static extern HRESULT InitPropVariantFromGUIDAsString(in Guid guid, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified vector of 16-bit integer values.</summary> /// <param name="prgn">Pointer to a source vector of SHORT values. If this parameter is NULL, the vector is initialized with zeros.</param> /// <param name="cElems">The number of elements in the vector.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762298")] public static extern HRESULT InitPropVariantFromInt16Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.I2)] short[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified vector of 32-bit integer values.</summary> /// <param name="prgn">Pointer to a source vector of LONG values. If this parameter is NULL, the vector is initialized with zeros.</param> /// <param name="cElems">The number of elements in the vector.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762300")] public static extern HRESULT InitPropVariantFromInt32Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.I4)] int[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified vector of 64-bit integer values.</summary> /// <param name="prgn"> /// Pointer to a source vector of LONGLONG values. If this parameter is NULL, the vector is initialized with zeros. /// </param> /// <param name="cElems">The number of elements in the vector.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762302")] public static extern HRESULT InitPropVariantFromInt64Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.I8)] long[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified <see cref="PROPVARIANT"/> vector element.</summary> /// <remarks> /// This function extracts a single value from the source <see cref="PROPVARIANT"/> structure and uses that value to initialize the /// output <c>PROPVARIANT</c> structure. The calling application must use <see cref="PropVariantClear"/> to free the /// <c>PROPVARIANT</c> referred to by ppropvar when it is no longer needed. /// <para> /// If the source <c>PROPVARIANT</c> is a vector or array, iElem must be less than the number of elements in the vector or array. /// </para> /// <para>If the source <c>PROPVARIANT</c> has a single value, iElem must be 0.</para> /// <para>If the source <c>PROPVARIANT</c> is empty, this function always returns an error code.</para> /// <para>You can use <see cref="PropVariantGetElementCount"/> to obtain the number of elements in the vector or array.</para> /// </remarks> /// <param name="propvarIn">The source <see cref="PROPVARIANT"/> structure.</param> /// <param name="iElem">The index of the source <see cref="PROPVARIANT"/> structure element.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762303")] public static extern HRESULT InitPropVariantFromPropVariantVectorElem([In] PROPVARIANT propvarIn, uint iElem, [In, Out] PROPVARIANT ppropvar); /// <summary> /// <para>Initializes a PROPVARIANT structure based on a string resource embedded in an executable file.</para> /// </summary> /// <param name="hinst"> /// <para>Type: <c>HINSTANCE</c></para> /// <para>Handle to an instance of the module whose executable file contains the string resource.</para> /// </param> /// <param name="id"> /// <para>Type: <c>UINT</c></para> /// <para>Integer identifier of the string to be loaded.</para> /// </param> /// <param name="ppropvar"> /// <para>Type: <c>PROPVARIANT*</c></para> /// <para>When this function returns, contains the initialized PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// This function creates a VT_LPWSTR propvariant. If the specified resource does not exist, it initializes the PROPVARIANT with an /// empty string. Resource strings longer than 1024 characters are truncated and null-terminated. /// </para> /// <para>Examples</para> /// <para>The following example, to be included as part of a larger program, demonstrates how to use InitPropVariantFromResource.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-initpropvariantfromresource PSSTDAPI // InitPropVariantFromResource( HINSTANCE hinst, UINT id, PROPVARIANT *ppropvar ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "c958f823-f820-4b0b-86ed-84ad18befbd1")] public static extern HRESULT InitPropVariantFromResource(HINSTANCE hinst, uint id, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes the property variant from string.</summary> /// <param name="psz">Pointer to a buffer that contains the source Unicode string.</param> /// <param name="ppropvar">When this function returns, contains the initialized PROPVARIANT structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PInvokeData("propvarutil.h", MSDNShortId = "cee95d17-532d-8e34-a392-a04778f9bc00")] public static HRESULT InitPropVariantFromString(string psz, [In, Out] PROPVARIANT ppropvar) { PropVariantClear(ppropvar); if (psz is null) return HRESULT.E_INVALIDARG; ppropvar._ptr = Marshal.StringToCoTaskMemUni(psz); ppropvar.vt = VARTYPE.VT_LPWSTR; return HRESULT.S_OK; } /// <summary> /// <para> /// Initializes a PROPVARIANT structure from a specified string. The string is parsed as a semi-colon delimited list (for example: "A;B;C"). /// </para> /// </summary> /// <param name="psz"> /// <para>Type: <c>PCWSTR</c></para> /// <para>Pointer to a buffer that contains the source Unicode string.</para> /// </param> /// <param name="ppropvar"> /// <para>Type: <c>PROPVARIANT*</c></para> /// <para>When this function returns, contains the initialized PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// Creates a VT_VECTOR | VT_LPWSTR propvariant. It parses the source string as a semicolon list of values. The string "a; b; c" /// creates a vector with three values. Leading and trailing whitespace are removed, and empty values are omitted. /// </para> /// <para>If psz is <c>NULL</c> or contains no values, the PROPVARIANT structure is initialized as VT_EMPTY.</para> /// <para>Examples</para> /// <para>The following example, to be included as part of a larger program, demonstrates how to use InitPropVariantFromStringAsVector.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-initpropvariantfromstringasvector PSSTDAPI // InitPropVariantFromStringAsVector( PCWSTR psz, PROPVARIANT *ppropvar ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "fc48f2e0-ce4a-4f48-a624-202def4bcff0")] public static extern HRESULT InitPropVariantFromStringAsVector([MarshalAs(UnmanagedType.LPWStr)] string psz, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified string vector.</summary> /// <param name="prgsz">Pointer to a buffer that contains the source string vector.</param> /// <param name="cElems">The number of vector elements in <paramref name="prgsz"/>.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762307")] public static extern HRESULT InitPropVariantFromStringVector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.LPWStr)] string[] prgsz, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary> /// <para>Initializes a PROPVARIANT structure based on a string stored in a STRRET structure.</para> /// </summary> /// <param name="pstrret"> /// <para>Type: <c>STRRET*</c></para> /// <para>Pointer to a STRRET structure that contains the string.</para> /// </param> /// <param name="pidl"> /// <para>Type: <c>PCUITEMID_CHILD</c></para> /// <para>PIDL of the item whose details are being retrieved.</para> /// </param> /// <param name="ppropvar"> /// <para>Type: <c>PROPVARIANT*</c></para> /// <para>When this function returns, contains the initialized PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>Creates a VT_LPWSTR propvariant.</para> /// <para><c>Note</c> This function frees the memory used for the STRRET contents.</para> /// <para>Examples</para> /// <para>The following example, to be included as part of a larger program, demonstrates how to use InitPropVariantFromStrRet.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-initpropvariantfromstrret PSSTDAPI // InitPropVariantFromStrRet( STRRET *pstrret, PCUITEMID_CHILD pidl, PROPVARIANT *ppropvar ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "5c02e2ee-14c2-4966-83e7-16dfbf81b879")] public static extern HRESULT InitPropVariantFromStrRet(IntPtr pstrret, IntPtr pidl, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a specified string vector.</summary> /// <param name="prgn">The PRGN.</param> /// <param name="cElems">The number of vector elements in <paramref name="prgn"/>.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762310")] public static extern HRESULT InitPropVariantFromUInt16Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.U2)] ushort[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a vector of 32-bit unsigned integer values.</summary> /// <param name="prgn"> /// Pointer to a source vector of ULONG values. If this parameter is NULL, the <see cref="PROPVARIANT"/> is initialized with zeros. /// </param> /// <param name="cElems">The number of vector elements in <paramref name="prgn"/>.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762312")] public static extern HRESULT InitPropVariantFromUInt32Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.U4)] uint[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a <see cref="PROPVARIANT"/> structure based on a vector of 64-bit unsigned integer values.</summary> /// <param name="prgn"> /// Pointer to a source vector of ULONGLONG values. If this parameter is NULL, the <see cref="PROPVARIANT"/> is initialized with zeros. /// </param> /// <param name="cElems">The number of vector elements in <paramref name="prgn"/>.</param> /// <param name="ppropvar">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762314")] public static extern HRESULT InitPropVariantFromUInt64Vector([In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.U8)] ulong[] prgn, uint cElems, [In, Out] PROPVARIANT ppropvar); /// <summary>Initializes a vector element in a <see cref="PROPVARIANT"/> structure with a value stored in another PROPVARIANT.</summary> /// <param name="propvarSingle">Reference to the source <see cref="PROPVARIANT"/> structure that contains a single value.</param> /// <param name="ppropvarVector">When this function returns, contains the initialized <see cref="PROPVARIANT"/> structure.</param> /// <returns> /// Returns S_OK if successful, or a standard COM error value otherwise. If the requested coercion is not possible, an error is returned. /// </returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb762315")] public static extern HRESULT InitPropVariantVectorFromPropVariant([In] PROPVARIANT propvarSingle, [Out] PROPVARIANT ppropvarVector); /// <summary>Coerces a value stored as a <see cref="PROPVARIANT"/> structure to an equivalent value of a different variant type.</summary> /// <param name="ppropvarDest"> /// A pointer to a <see cref="PROPVARIANT"/> structure that, when this function returns successfully, receives the coerced value and /// its new type. /// </param> /// <param name="propvarSrc"> /// A reference to the source <see cref="PROPVARIANT"/> structure that contains the value expressed as its original type. /// </param> /// <param name="flags">Reserved, must be 0.</param> /// <param name="vt">Specifies the new type for the value. See the tables below for recognized type names.</param> /// <returns> /// Returns S_OK if successful, or a standard COM error value otherwise. If the requested coercion is not possible, an error is returned. /// </returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776514")] public static extern HRESULT PropVariantChangeType([Out] PROPVARIANT ppropvarDest, [In] PROPVARIANT propvarSrc, PROPVAR_CHANGE_FLAGS flags, VARTYPE vt); /// <summary>Compares two <see cref="PROPVARIANT"/> structures, based on default comparison units and settings.</summary> /// <param name="propvar1">Reference to the first <see cref="PROPVARIANT"/> structure.</param> /// <param name="propvar2">Reference to the second <see cref="PROPVARIANT"/> structure.</param> /// <returns> /// <list type="bullet"> /// <item> /// <description>Returns 1 if propvar1 is greater than propvar2</description> /// </item> /// <item> /// <description>Returns 0 if propvar1 equals propvar2</description> /// </item> /// <item> /// <description>Returns -1 if propvar1 is less than propvar2</description> /// </item> /// </list> /// </returns> [PInvokeData("Propvarutil.h", MSDNShortId = "bb776516")] public static int PropVariantCompare(PROPVARIANT propvar1, PROPVARIANT propvar2) { return PropVariantCompareEx(propvar1, propvar2, PROPVAR_COMPARE_UNIT.PVCU_DEFAULT, PROPVAR_COMPARE_FLAGS.PVCF_DEFAULT); } /// <summary>Compares two <see cref="PROPVARIANT"/> structures, based on specified comparison units and flags.</summary> /// <param name="propvar1">Reference to the first <see cref="PROPVARIANT"/> structure.</param> /// <param name="propvar2">Reference to the second <see cref="PROPVARIANT"/> structure.</param> /// <param name="unit">Specifies, where appropriate, one of the comparison units defined in PROPVAR_COMPARE_UNIT.</param> /// <param name="flags">Specifies one of the following:</param> /// <returns> /// <list type="bullet"> /// <item> /// <description>Returns 1 if propvar1 is greater than propvar2</description> /// </item> /// <item> /// <description>Returns 0 if propvar1 equals propvar2</description> /// </item> /// <item> /// <description>Returns -1 if propvar1 is less than propvar2</description> /// </item> /// </list> /// </returns> [DllImport(Lib.PropSys, ExactSpelling = true, PreserveSig = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776517")] public static extern int PropVariantCompareEx(PROPVARIANT propvar1, PROPVARIANT propvar2, PROPVAR_COMPARE_UNIT unit, PROPVAR_COMPARE_FLAGS flags); /// <summary> /// <para>Extracts a single Boolean element from a PROPVARIANT structure of type , , or .</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>A reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>Specifies the vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pfVal"> /// <para>Type: <c>BOOL*</c></para> /// <para>When this function returns, contains the extracted Boolean value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// If the source PROPVARIANT structure has type , iElem must be 0. Otherwise iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>The following example uses this function to loop through the values in a PROPVARIANT structure.</para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetbooleanelem PSSTDAPI // PropVariantGetBooleanElem( REFPROPVARIANT propvar, ULONG iElem, BOOL *pfVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "830dca70-1777-418d-b3ac-78028411700e")] public static extern HRESULT PropVariantGetBooleanElem([In] PROPVARIANT propvar, uint iElem, [MarshalAs(UnmanagedType.Bool)] out bool pfVal); /// <summary> /// <para>Extracts a single <c>double</c> element from a PROPVARIANT structure of type , , or .</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>Specifies vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>DOUBLE*</c></para> /// <para>When this function returns, contains the extracted double value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// If the source PROPVARIANT has type , iElem must be 0. Otherwise iElem must be less than the number of elements in the vector or /// array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>The following example uses this function to loop through the values in a PROPVARIANT structure.</para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetdoubleelem PSSTDAPI // PropVariantGetDoubleElem( REFPROPVARIANT propvar, ULONG iElem, DOUBLE *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "387e23df-bfbd-42c0-adef-dc53ba95a9f2")] public static extern HRESULT PropVariantGetDoubleElem([In] PROPVARIANT propvar, uint iElem, out double pnVal); /// <summary>Retrieves the element count of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <returns> /// Returns the element count of a VT_VECTOR or VT_ARRAY value: for single values, returns 1; for empty structures, returns 0. /// </returns> [DllImport(Lib.PropSys, ExactSpelling = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.I4)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776522")] public static extern int PropVariantGetElementCount([In] PROPVARIANT propVar); /// <summary> /// <para> /// Extracts a single FILETIME element from a PROPVARIANT structure of type VT_FILETIME, VT_VECTOR | VT_FILETIME, or VT_ARRAY | VT_FILETIME. /// </para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>The source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>Specifies vector or array index; otherwise, this value must be 0.</para> /// </param> /// <param name="pftVal"> /// <para>Type: <c>FILETIME*</c></para> /// <para>When this function returns, contains the extracted filetime value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// If the source PROPVARIANT has type VT_FILETIME, iElem must be 0; otherwise, iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following code example, to be included as part of a larger program, demonstrates how to use PropVariantGetFileTimeElem in an /// iteration statement to access the values in PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetfiletimeelem PSSTDAPI // PropVariantGetFileTimeElem( REFPROPVARIANT propvar, ULONG iElem, FILETIME *pftVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "e38b16ed-84cb-4444-bfbd-1165595bc9b5")] public static extern HRESULT PropVariantGetFileTimeElem([In] PROPVARIANT propvar, uint iElem, out FILETIME pftVal); /// <summary> /// <para>Extracts a single Int16 element from a PROPVARIANT structure of type VT_I2, VT_VECTOR | VT_I2, or VT_ARRAY | VT_I2.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, this value must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>SHORT*</c></para> /// <para>When this function returns, contains the extracted Int32 element value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types.</para> /// <list type="bullet"> /// <item> /// <term>VT_I2</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_I2</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_I2</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_I2, iElem must be 0. Otherwise, iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantGetInt16Elem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetint16elem PSSTDAPI // PropVariantGetInt16Elem( REFPROPVARIANT propvar, ULONG iElem, SHORT *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "1dbb6887-81c9-411d-9fce-c9e2f3479a43")] public static extern HRESULT PropVariantGetInt16Elem([In] PROPVARIANT propvar, uint iElem, out short pnVal); /// <summary> /// <para>Extracts a single Int32 element from a PROPVARIANT of type VT_I4, VT_VECTOR | VT_I4, or VT_ARRAY | VT_I4.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>LONG*</c></para> /// <para>When this function, contains the extracted Int32 value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_I4</term> /// </item> /// <item> /// <term>VT_VECTTOR | VT_I4</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_I4</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_I4, iElem must be 0. Otherwise, iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example uses this PropVariantGetInt32Elem with an interation statement to access the values in a PROPVARIANT structure. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetint32elem PSSTDAPI // PropVariantGetInt32Elem( REFPROPVARIANT propvar, ULONG iElem, LONG *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "de7dc6d4-d85a-44cb-8af7-840fd6e68d5c")] public static extern HRESULT PropVariantGetInt32Elem([In] PROPVARIANT propvar, uint iElem, out int pnVal); /// <summary> /// <para>Extracts a single Int64 element from a PROPVARIANT structure of type VT_I8, VT_VECTOR | VT_I8, or VT_ARRAY | VT_I8.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>LONGLONG*</c></para> /// <para>When this function returns, contains the extracted Int64 value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works forPROPVARIANTstructures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_I8</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_I8</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_I8</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_I8, iElem must be 0. Otherwise, iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantGetInt64Elem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetint64elem PSSTDAPI // PropVariantGetInt64Elem( REFPROPVARIANT propvar, ULONG iElem, LONGLONG *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "6dd7212a-587f-4f9e-a2e5-dbd2a9c15a5b")] public static extern HRESULT PropVariantGetInt64Elem([In] PROPVARIANT propvar, uint iElem, out long pnVal); /// <summary> /// <para> /// Extracts a single Unicode string element from a PROPVARIANT structure of type VT_LPWSTR, VT_BSTR, VT_VECTOR | VT_LPWSTR, /// VT_VECTOR | VT_BSTR, or VT_ARRAY | VT_BSTR. /// </para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="ppszVal"> /// <para>Type: <c>PWSTR*</c></para> /// <para> /// When this function returns, contains the extracted string value. The calling application is responsible for freeing this string /// by calling CoTaskMemFree when it is no longer needed. /// </para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_LPWSTR</term> /// </item> /// <item> /// <term>VT_BSTR</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_LPWSTR</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_BSTR</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_BSTR</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_LPWSTR or VT_BSTR, iElem must be 0. Otherwise iElem must be less than the number of /// elements in the vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>If a BSTR element has a <c>NULL</c> pointer, this function allocates an empty string.</para> /// <para>Examples</para> /// <para> /// The following code example, to be included as part of a larger program, demonstrates how to use PropVariantGetStringElem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetstringelem PSSTDAPI // PropVariantGetStringElem( REFPROPVARIANT propvar, ULONG iElem, PWSTR *ppszVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "6e803d93-5b55-4b73-8e23-a584f5f91969")] public static extern HRESULT PropVariantGetStringElem([In] PROPVARIANT propvar, uint iElem, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(CoTaskMemStringMarshaler))] out string ppszVal); /// <summary> /// <para> /// Extracts a single unsigned Int16 element from a PROPVARIANT structure of type VT_U12, VT_VECTOR | VT_U12, or VT_ARRAY | VT_U12. /// </para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to the source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>USHORT*</c></para> /// <para>When this function returns, contains the extracted element value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_UI2</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_UI2</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_UI2</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_UI2, iElem must be 0. Otherwise iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantGetUInt16Elem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetuint16elem PSSTDAPI // PropVariantGetUInt16Elem( REFPROPVARIANT propvar, ULONG iElem, USHORT *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "da50e35b-f17f-4de6-b2e7-5a885e2149e5")] public static extern HRESULT PropVariantGetUInt16Elem([In] PROPVARIANT propvar, uint iElem, out ushort pnVal); /// <summary> /// <para> /// Extracts a single unsigned Int32 element from a PROPVARIANT structure of type VT_UI4, VT_VECTOR | VT_UI4, or VT_ARRAY | VT_UI4. /// </para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>The source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>A vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the extracted unsigned Int32 value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_UI4</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_UI4</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_UI4</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_UI4, iElem must be 0. Otherwise, iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantGetUInt32Elem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetuint32elem PSSTDAPI // PropVariantGetUInt32Elem( REFPROPVARIANT propvar, ULONG iElem, ULONG *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "b31975b6-d717-4e8d-bf5a-2ade96034031")] public static extern HRESULT PropVariantGetUInt32Elem([In] PROPVARIANT propvar, uint iElem, out uint pnVal); /// <summary> /// <para> /// Extracts a single unsigned Int64 element from a PROPVARIANT structure of type VT_UI8, VT_VECTOR | VT_UI8, or VT_ARRAY | VT_UI8. /// </para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>The source PROPVARIANT structure.</para> /// </param> /// <param name="iElem"> /// <para>Type: <c>ULONG</c></para> /// <para>The vector or array index; otherwise, iElem must be 0.</para> /// </param> /// <param name="pnVal"> /// <para>Type: <c>ULONGLONG*</c></para> /// <para>When this function returns, contains the extracted Int64 value.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>This helper function works for PROPVARIANT structures of the following types:</para> /// <list type="bullet"> /// <item> /// <term>VT_UI8</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_UI8</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_UI8</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has type VT_UI8, iElem must be 0. Otherwise iElem must be less than the number of elements in the /// vector or array. You can use PropVariantGetElementCount to obtain the number of elements in the vector or array. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantGetUInt64Elem with an /// iteration statement to access the values in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvariantgetuint64elem PSSTDAPI // PropVariantGetUInt64Elem( REFPROPVARIANT propvar, ULONG iElem, ULONGLONG *pnVal ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "35955104-b567-4c4f-850a-0a4778673ce8")] public static extern HRESULT PropVariantGetUInt64Elem([In] PROPVARIANT propvar, uint iElem, out ulong pnVal); /// <summary> /// Extracts a Boolean property value of a <see cref="PROPVARIANT"/> structure. If no value can be extracted, then a default value is assigned. /// </summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pfRet">When this function returns, contains the extracted property value if one exists; otherwise, contains FALSE.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776531")] public static extern HRESULT PropVariantToBoolean([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.Bool)] out bool pfRet); /// <summary> /// <para>Extracts a Boolean vector from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgf"> /// <para>Type: <c>BOOL*</c></para> /// <para> /// Points to a buffer that contains crgf <c>BOOL</c> values. When this function returns, the buffer has been initialized with pcElem /// Boolean elements extracted from the source PROPVARIANT structure. /// </para> /// </param> /// <param name="crgf"> /// <para>Type: <c>ULONG</c></para> /// <para>Number of elements in the buffer pointed to by prgf.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of Boolean elements extracted from source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgf values. The buffer pointed to by prgf.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used when the calling application expects a PROPVARIANT to hold a Boolean vector value with a fixed /// number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type VT_VECTOR | VT_BOOL or VT_ARRAY | VT_BOOL, this helper function extracts up to crgf Boolean /// values an places them into the buffer pointed to by prgf. If the <c>PROPVARIANT</c> contains more elements than will fit into the /// prgf buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToBooleanVector to access a /// Boolean vector stored in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttobooleanvector PSSTDAPI // PropVariantToBooleanVector( REFPROPVARIANT propvar, BOOL *prgf, ULONG crgf, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "93ccd129-4fa4-40f3-96f3-b87b50414b0a")] public static extern HRESULT PropVariantToBooleanVector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.Bool)] bool[] prgf, uint crgf, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated Boolean vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of Boolean values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of Boolean elements extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns> /// Returns S_OK if successful, or an error value otherwise. E_INVALIDARG indicates that the <see cref="PROPVARIANT"/> was not of the /// appropriate type. /// </returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776533")] public static extern HRESULT PropVariantToBooleanVectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts the Boolean property value of a PROPVARIANT structure. If no value exists, then the specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="fDefault"> /// <para>Type: <c>BOOL</c></para> /// <para>Specifies the default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>BOOL</c></para> /// <para>The extracted Boolean value or the default value.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a Boolean value and would like /// to use a default value if it does not. For instance, an application that obtains values from a property store can use this to /// safely extract the Boolean value for Boolean properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_BOOL</c>, this helper function extracts the Boolean value. Otherwise, it attempts to /// convert the value in the <c>PROPVARIANT</c> structure into a Boolean. If the source <c>PROPVARIANT</c> has type <c>VT_EMPTY</c> /// or a conversion is not possible, then PropVariantToBooleanWithDefault returns the default provided by fDefault. See /// PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToBooleanWithDefault to /// access a Boolean value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttobooleanwithdefault PSSTDAPI_(BOOL) // PropVariantToBooleanWithDefault( REFPROPVARIANT propvarIn, BOOL fDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "223767a7-a4de-4e7e-ad8b-2a6bdcea0a47")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PropVariantToBooleanWithDefault([In] PROPVARIANT propvarIn, [MarshalAs(UnmanagedType.Bool)] bool fDefault); /// <summary>Extracts the BSTR property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pbstrOut">Pointer to the extracted property value if one exists; otherwise, contains an empty string.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776535")] public static extern HRESULT PropVariantToBSTR([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.BStr)] out string pbstrOut); /// <summary>Extracts the buffer value from a <see cref="PROPVARIANT"/> structure of type VT_VECTOR | VT_UI1 or VT_ARRRAY | VT_UI1.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pv"> /// Pointer to a buffer of length cb bytes. When this function returns, contains the first cb bytes of the extracted buffer value. /// </param> /// <param name="cb">The buffer length, in bytes.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776536")] public static extern HRESULT PropVariantToBuffer([In] PROPVARIANT propVar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pv, uint cb); /// <summary>Extracts double value from a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pdblRet"> /// When this function returns, contains the extracted property value if one exists; otherwise, contains 0.0. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776538")] public static extern HRESULT PropVariantToDouble([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.R8)] out double pdblRet); /// <summary> /// <para>Extracts a vector of doubles from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>DOUBLE*</c></para> /// <para> /// Points to a buffer containing crgn DOUBLE values. When this function returns, the buffer has been initialized with pcElem double /// elements extracted from the source PROPVARIANT structure. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size in elements of the buffer pointed to by prgn.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of double elements extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a double vector value with a /// fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type VT_VECTOR | VT_R8 or VT_ARRAY | VT_R8, this helper function extracts up to crgn double values /// and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> contains more elements than will fit into the prgn /// buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttodoublevector PSSTDAPI // PropVariantToDoubleVector( REFPROPVARIANT propvar, DOUBLE *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "2d90bf96-8a3f-4949-8480-bb75f0deeb2e")] public static extern HRESULT PropVariantToDoubleVector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] double[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly-allocated double vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of double values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of double elements extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776540")] public static extern HRESULT PropVariantToDoubleVectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para>Extracts a double property value of a PROPVARIANT structure. If no value exists, then the specified default value is returned.</para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="dblDefault"> /// <para>Type: <c>DOUBLE</c></para> /// <para>Specifies default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>DOUBLE</c></para> /// <para>Returns extracted <c>double</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a double value and would like /// to use a default value if it does not. For instance, an application obtaining values from a property store can use this to safely /// extract the double value for double properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_R8</c>, this helper function extracts the double value. Otherwise, it attempts to /// convert the value in the <c>PROPVARIANT</c> structure into a double. If the source <c>PROPVARIANT</c> has type <c>VT_EMPTY</c> or /// a conversion is not possible, then PropVariantToDoubleWithDefault will return the default provided by dblDefault. See /// PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttodoublewithdefault PSSTDAPI_(DOUBLE) // PropVariantToDoubleWithDefault( REFPROPVARIANT propvarIn, DOUBLE dblDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "81584e13-0ef7-47ce-b78f-b4a79712ff1e")] public static extern double PropVariantToDoubleWithDefault([In] PROPVARIANT propvarIn, double dblDefault); /// <summary>Extracts the <see cref="FILETIME"/> structure from a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pstfOut">Specifies one of the time flags.</param> /// <param name="pftOut">When this function returns, contains the extracted <see cref="FILETIME"/> structure.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776542")] public static extern HRESULT PropVariantToFileTime([In] PROPVARIANT propVar, PSTIME_FLAGS pstfOut, out FILETIME pftOut); /// <summary> /// <para>Extracts data from a PROPVARIANT structure into a FILETIME vector.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgft"> /// <para>Type: <c>FILETIME*</c></para> /// <para> /// Points to a buffer containing crgft FILETIME values. When this function returns, the buffer has been initialized with pcElem /// FILETIME elements extracted from the source PROPVARIANT structure. /// </para> /// </param> /// <param name="crgft"> /// <para>Type: <c>ULONG</c></para> /// <para>Size in elements of the buffer pointed to by prgft.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of FILETIME elements extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>Returns one of the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgft.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a filetime vector value with a /// fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type VT_VECTOR | VT_FILETIME, this helper function extracts up to crgft FILETIME values and places /// them into the buffer pointed to by prgft. If the <c>PROPVARIANT</c> contains more elements than will fit into the prgft buffer, /// this function returns an error and sets pcElem to 0. /// </para> /// <para>The output FILETIMEs will use the same time zone as the source FILETIMEs.</para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToFileTimeVector to access /// a FILETIME vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttofiletimevector PSSTDAPI // PropVariantToFileTimeVector( REFPROPVARIANT propvar, FILETIME *prgft, ULONG crgft, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "ef665f50-3f3b-47db-9133-490305da5341")] public static extern HRESULT PropVariantToFileTimeVector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] FILETIME[] prgft, uint crgft, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly-allocated <see cref="FILETIME"/> vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of <see cref="FILETIME"/> values extracted from the source <see /// cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of <see cref="FILETIME"/> elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776544")] public static extern HRESULT PropVariantToFileTimeVectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary>Extracts a GUID value from a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pguid">When this function returns, contains the extracted property value if one exists.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776545")] public static extern HRESULT PropVariantToGUID([In] PROPVARIANT propVar, out Guid pguid); /// <summary>Extracts an Int16 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="piRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776546")] public static extern HRESULT PropVariantToInt16([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.I2)] out short piRet); /// <summary> /// <para>Extracts a vector of <c>Int16</c> values from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>SHORT*</c></para> /// <para> /// Points to a buffer containing crgn SHORT values. When this function returns, the buffer has been initialized with pcElem SHORT /// elements extracted from the source PROPVARIANT structure. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>Int16</c> elements extracted from source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>ThePROPVARIANTwas not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an <c>Int16</c> vector value /// with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type VT_VECTOR | VT_I2 or VT_ARRAY | VT_I2, this helper function extracts up to crgn Int16 values /// and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> contains more elements than will fit into the prgn /// buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint16vector PSSTDAPI // PropVariantToInt16Vector( REFPROPVARIANT propvar, SHORT *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "33240552-7caa-4114-aad6-7341551b1fbe")] public static extern HRESULT PropVariantToInt16Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] short[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated Int16 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of Int16 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of Int16 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776548")] public static extern HRESULT PropVariantToInt16VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts the Int16 property value of a PROPVARIANT structure. If no value currently exists, then specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="iDefault"> /// <para>Type: <c>SHORT</c></para> /// <para>Specifies default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>SHORT</c></para> /// <para>Returns the extracted <c>short</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an <c>Int16</c> value and /// would like to use a default value if it does not. For instance, an application obtaining values from a property store can use /// this to safely extract the <c>SHORT</c> value for <c>Int16</c> properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_I2</c>, this helper function extracts the <c>Int16</c> value. Otherwise, it attempts to /// convert the value in the <c>PROPVARIANT</c> structure into a <c>SHORT</c>. If the source <c>PROPVARIANT</c> has type /// <c>VT_EMPTY</c> or a conversion is not possible, then PropVariantToInt16WithDefault will return the default provided by iDefault. /// See PropVariantChangeType for a list of possible conversions. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint16withdefault PSSTDAPI_(SHORT) // PropVariantToInt16WithDefault( REFPROPVARIANT propvarIn, SHORT iDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "51221281-6e06-49f4-83c0-7330f2a6d67e")] public static extern short PropVariantToInt16WithDefault([In] PROPVARIANT propvarIn, short iDefault); /// <summary>Extracts an Int32 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="plRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776550")] public static extern HRESULT PropVariantToInt32([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.I4)] out int plRet); /// <summary> /// <para>Extracts a vector of <c>long</c> values from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>LONG*</c></para> /// <para> /// Points to a buffer containing crgn <c>LONG</c> values. When this function returns, the buffer has been initialized with pcElem /// <c>LONG</c> elements extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>LONG</c> elements extracted from source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of <c>LONG</c> /// values with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_VECTOR</c> | <c>VT_I4</c> or <c>VT_ARRAY</c> | <c>VT_I4</c>, this helper function /// extracts up to crgn <c>LONG</c> values and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> contains /// more elements than will fit into the prgn buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToInt32Vector to access an /// Int32 vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint32vector PSSTDAPI // PropVariantToInt32Vector( REFPROPVARIANT propvar, LONG *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "771fa1d7-c648-49d4-a6a2-5aa23f8c20b7")] public static extern HRESULT PropVariantToInt32Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] int[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated Int32 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of Int32 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of Int32 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776552")] public static extern HRESULT PropVariantToInt32VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts an <c>Int32</c> value from a PROPVARIANT structure. If no value currently exists, then the specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="lDefault"> /// <para>Type: <c>LONG</c></para> /// <para>Specifies a default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>LONG</c></para> /// <para>Returns extracted <c>LONG</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a <c>LONG</c> value and would /// like to use a default value if it does not. For instance, an application obtaining values from a property store can use this to /// safely extract the <c>LONG</c> value for <c>Int32</c> properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_I4</c>, this helper function extracts the <c>LONG</c> value. Otherwise, it attempts to /// convert the value in the <c>PROPVARIANT</c> structure into a <c>LONG</c>. If the source <c>PROPVARIANT</c> has type /// <c>VT_EMPTY</c> or a conversion is not possible, then PropVariantToInt32WithDefault will return the default provided by lDefault. /// See PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToInt32WithDefault to /// access a <c>LONG</c> value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint32withdefault PSSTDAPI_(LONG) // PropVariantToInt32WithDefault( REFPROPVARIANT propvarIn, LONG lDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "1d014cad-a9a5-4a58-855e-21c6d3ba6dcd")] public static extern int PropVariantToInt32WithDefault([In] PROPVARIANT propvarIn, int lDefault); /// <summary>Extracts an Int64 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pllRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776554")] public static extern HRESULT PropVariantToInt64([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.I8)] out long pllRet); /// <summary> /// <para>Extracts data from a PROPVARIANT structure into an <c>Int64</c> vector.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>LONGLONG*</c></para> /// <para> /// Points to a buffer containing crgn <c>LONGLONG</c> values. When this function returns, the buffer has been initialized with /// pcElem <c>LONGLONG</c> elements extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>LONGLONG</c> values extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of <c>LONGLONG</c> /// values with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_VECTOR</c> | <c>VT_I8</c> or <c>VT_ARRAY</c> | <c>VT_I8</c>, this helper function /// extracts up to crgn <c>LONGLONG</c> values and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> contains /// more elements than will fit into the prgn buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToInt64Vector to access an /// Int64 vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint64vector PSSTDAPI // PropVariantToInt64Vector( REFPROPVARIANT propvar, LONGLONG *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "cda5589a-726f-4e43-aec4-bb7a7ca62b1a")] public static extern HRESULT PropVariantToInt64Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] long[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated Int64 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of Int64 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of Int64 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776557")] public static extern HRESULT PropVariantToInt64VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts the <c>Int64</c> property value of a PROPVARIANT structure. If no value exists, then specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="llDefault"> /// <para>Type: <c>LONGLONG</c></para> /// <para>Specifies a default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>LONGLONG</c></para> /// <para>Returns the extracted <c>LONGLONG</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a <c>LONGLONG</c> value and /// would like to use a default value if it does not. For instance, an application obtaining values from a property store can use /// this to safely extract the <c>LONGLONG</c> value for Int64 properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_I8</c>, this helper function extracts the <c>LONGLONG</c> value. Otherwise, it attempts /// to convert the value in the <c>PROPVARIANT</c> structure into a <c>LONGLONG</c>. If the source <c>PROPVARIANT</c> has type /// <c>VT_EMPTY</c> or a conversion is not possible, then PropVariantToInt64WithDefault will return the default provided by /// llDefault. See PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToInt64WithDefault to /// access a <c>LONGLONG</c> value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttoint64withdefault PSSTDAPI_(LONGLONG) // PropVariantToInt64WithDefault( REFPROPVARIANT propvarIn, LONGLONG llDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "6a051235-3e32-40d3-a17e-efc571592dae")] public static extern long PropVariantToInt64WithDefault([In] PROPVARIANT propvarIn, long llDefault); /// <summary> /// <para>Extracts a string value from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="psz"> /// <para>Type: <c>PWSTR</c></para> /// <para> /// Points to a string buffer. When this function returns, the buffer is initialized with a <c>NULL</c> terminated Unicode string value. /// </para> /// </param> /// <param name="cch"> /// <para>Type: <c>UINT</c></para> /// <para>Size of the buffer pointed to by psz, in characters.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The value was extracted and the result buffer was NULL terminated.</term> /// </item> /// <item> /// <term>STRSAFE_E_INSUFFICIENT_BUFFER</term> /// <term> /// The copy operation failed due to insufficient buffer space. The destination buffer contains a truncated, null-terminated version /// of the intended result. In situations where truncation is acceptable, this may not necessarily be seen as a failure condition. /// </term> /// </item> /// <item> /// <term>Some other error value</term> /// <term>The extraction failed for some other reason.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a string value. For instance, /// an application obtaining values from a property store can use this to safely extract a string value for string properties. /// </para> /// <para> /// If the source PROPVARIANT has type VT_LPWSTR or <c>VT_BSTR</c>, this function extracts the string and places it into the provided /// buffer. Otherwise, it attempts to convert the value in the <c>PROPVARIANT</c> structure into a string. If a conversion is not /// possible, PropVariantToString will return a failure code and set psz to '\0'. See PropVariantChangeType for a list of possible /// conversions. Of note, <c>VT_EMPTY</c> is successfully converted to "". /// </para> /// <para> /// In addition to the terminating <c>NULL</c>, at most cch-1 characters are written into the buffer pointed to by psz. If the value /// in the source PROPVARIANT is longer than will fit into the buffer, a truncated <c>NULL</c> Terminated copy of the string is /// written to the buffer and this function returns <c>STRSAFE_E_INSUFFICIENT_BUFFER</c>. The resulting string will always be /// <c>NULL</c> terminated. /// </para> /// <para>In addition to the conversions provided by PropVariantChangeType, the following special cases apply to PropVariantToString.</para> /// <list type="bullet"> /// <item> /// <term> /// Vector-valued PROPVARIANTs are converted to strings by separating each element with using "; ". For example, PropVariantToString /// converts a vector of 3 integers, {3, 1, 4}, to the string "3; 1; 4". The semicolon is independent of the current locale. /// </term> /// </item> /// <item> /// <term> /// VT_BLOB, VT_STREAM, VT_STREAMED_OBJECT, and VT_UNKNOWN values are converted to strings using an unsupported encoding. It is not /// possible to decode strings created in this way and the format may change in the future. /// </term> /// </item> /// </list> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToString to access a string /// value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttostring PSSTDAPI PropVariantToString( // REFPROPVARIANT propvar, PWSTR psz, UINT cch ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "d545dc12-a780-4d95-8660-13b3f65725f9")] public static extern HRESULT PropVariantToString([In] PROPVARIANT propvar, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder psz, uint cch); /// <summary>Extracts a string property value from a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="ppszOut">When this function returns, contains a pointer to the extracted property value if one exists.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776560")] public static extern HRESULT PropVariantToStringAlloc([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(CoTaskMemStringMarshaler))] out string ppszOut); /// <summary> /// <para>Extracts a vector of strings from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgsz"> /// <para>Type: <c>PWSTR*</c></para> /// <para> /// Pointer to a vector of string pointers. When this function returns, the buffer has been initialized with pcElem elements pointing /// to newly allocated strings containing the data extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgsz"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgsz, in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of strings extracted from source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The sourcePROPVARIANTcontained more than crgsz values. The buffer pointed to by prgsz.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>ThePROPVARIANTwas not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of string values /// with a fixed number of elements. /// </para> /// <para>This function works for the following PROPVARIANT types:</para> /// <list type="bullet"> /// <item> /// <term>VT_VECTOR | VT_LPWSTR</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_BSTR</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_BSTR</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has a supported type, this helper function extracts up to crgsz string values and places an allocated /// copy of each into the buffer pointed to by prgsz. If the <c>PROPVARIANT</c> contains more elements than will fit into the prgsz /// buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para> /// Since each string in pointed to by the output buffer has been newly allocated, the calling application is responsible for using /// CoTaskMemFree to free each string in the output buffer when they are no longer needed. /// </para> /// <para> /// If a <c>BSTR</c> in the source PROPVARIANT is <c>NULL</c>, it is converted to a newly allocated string containing "" in the output. /// </para> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttostringvector PSSTDAPI // PropVariantToStringVector( REFPROPVARIANT propvar, PWSTR *prgsz, ULONG crgsz, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "6618ee02-1939-4c9c-8690-a8cd5d668cdb")] public static extern HRESULT PropVariantToStringVector([In] PROPVARIANT propvar, IntPtr prgsz, uint crgsz, out uint pcElem); /// <summary> /// <para>Extracts a vector of strings from a PROPVARIANT structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="crgsz"> /// <para>Type: <c>ULONG</c></para> /// <para>The number of strings requested.</para> /// </param> /// <param name="prgsz"> /// <para>Type: <c>PWSTR*</c></para> /// <para>When this function returns, the array of strings containing the data extracted from the source PROPVARIANT.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The sourcePROPVARIANTcontained more than crgsz values. The buffer pointed to by prgsz.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>ThePROPVARIANTwas not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of string values /// with a fixed number of elements. /// </para> /// <para>This function works for the following PROPVARIANT types:</para> /// <list type="bullet"> /// <item> /// <term>VT_VECTOR | VT_LPWSTR</term> /// </item> /// <item> /// <term>VT_VECTOR | VT_BSTR</term> /// </item> /// <item> /// <term>VT_ARRAY | VT_BSTR</term> /// </item> /// </list> /// <para> /// If the source PROPVARIANT has a supported type, this helper function extracts up to crgsz string values and places an allocated /// copy of each into the buffer pointed to by prgsz. If the <c>PROPVARIANT</c> contains more elements than will fit into the prgsz /// buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para> /// Since each string in pointed to by the output buffer has been newly allocated, the calling application is responsible for using /// CoTaskMemFree to free each string in the output buffer when they are no longer needed. /// </para> /// <para> /// If a <c>BSTR</c> in the source PROPVARIANT is <c>NULL</c>, it is converted to a newly allocated string containing "" in the output. /// </para> /// <para>Examples</para> /// </remarks> public static HRESULT PropVariantToStringVector([In] PROPVARIANT propvar, uint crgsz, out string[] prgsz) { SafeCoTaskMemHandle ptr = new SafeCoTaskMemHandle(IntPtr.Size * (int)crgsz); HRESULT hr = PropVariantToStringVector(propvar, (IntPtr)ptr, crgsz, out uint cnt); prgsz = new string[0]; if (hr.Failed) { return hr; } prgsz = ptr.ToEnumerable<IntPtr>((int)cnt).Select(p => ((SafeCoTaskMemHandle)p).ToString(-1)).ToArray(); return hr; } /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated strings in a newly allocated vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of strings extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of string elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776562")] public static extern HRESULT PropVariantToStringVectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// Extracts the string property value of a <see cref="PROPVARIANT"/> structure. If no value exists, then the specified default value /// is returned. /// </summary> /// <param name="propvarIn">Reference to a source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pszDefault">Pointer to a default Unicode string value, for use where no value currently exists. May be NULL.</param> /// <returns>Returns string value or the default.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.LPWStr)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776563")] public static extern string PropVariantToStringWithDefault([In] PROPVARIANT propvarIn, [In, MarshalAs(UnmanagedType.LPWStr)] string pszDefault); /// <summary> /// <para>Extracts a string from a PROPVARIANT structure and places it into a STRRET structure.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="pstrret"> /// <para>Type: <c>STRRET*</c></para> /// <para> /// Points to the STRRET structure. When this function returns, the structure has been initialized to contain a copy of the extracted string. /// </para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in applications that wish to convert a string value in a PROPVARIANT structure into a STRRET /// structure. For instance, an application implementing IShellFolder::GetDisplayNameOf may find this function useful. /// </para> /// <para> /// If the source PROPVARIANT has type VT_LPWSTR or VT_BSTR, this function extracts the string and places it into the STRRET /// structure. Otherwise, it attempts to convert the value in the <c>PROPVARIANT</c> structure into a string. If a conversion is not /// possible, PropVariantToString will return a failure code. See PropVariantChangeType for a list of possible conversions. Of note, /// VT_EMPTY is successfully converted to "". /// </para> /// <para>In addition to the conversions provided by PropVariantChangeType, the following special cases apply to PropVariantToString.</para> /// <list type="bullet"> /// <item> /// <term> /// Vector-valued PROPVARIANTs are converted to strings by separating each element with using "; ". For example, PropVariantToString /// converts a vector of 3 integers, {3, 1, 4}, to the string "3; 1; 4". The semicolon is independent of the current locale. /// </term> /// </item> /// <item> /// <term> /// VT_BLOB, VT_STREAM, VT_STREAMED_OBJECT, and VT_UNKNOWN values are converted to strings using an unsupported encoding. It is not /// possible to decode strings created in this way and the format may change in the future. /// </term> /// </item> /// </list> /// <para> /// If the extraction is successful, the function will initialize uType member of the STRRET structure with STRRET_WSTR and set the /// pOleStr member of that structure to point to an allocated copy of the string. The calling application is responsible for using /// CoTaskMemFree or StrRetToStr to free this string when it is no longer needed. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToString to access a string /// value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttostrret PSSTDAPI PropVariantToStrRet( // REFPROPVARIANT propvar, STRRET *pstrret ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "a1a33606-172d-4ee7-98c9-ffec8eed98bf")] public static extern HRESULT PropVariantToStrRet([In] PROPVARIANT propvar, IntPtr pstrret); /// <summary>Extracts a UInt16 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="puiRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776565")] public static extern HRESULT PropVariantToUInt16([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.U2)] out ushort puiRet); /// <summary> /// <para>Extracts data from a PROPVARIANT structure into an <c>unsigned short</c> vector.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>USHORT*</c></para> /// <para> /// Points to a buffer containing crgn <c>unsigned short</c> values. When this function returns, the buffer has been initialized with /// pcElem <c>unsigned short</c> elements extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>unsigned short</c> values extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of <c>unsigned /// short</c> values with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_VECTOR</c> | <c>VT_UI2</c> or <c>VT_ARRAY</c> | <c>VT_UI2</c>, this helper function /// extracts up to crgn <c>unsigned short</c> values and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> /// contains more elements than will fit into the prgn buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt16Vector to access an /// <c>unsigned short</c> vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint16vector PSSTDAPI // PropVariantToUInt16Vector( REFPROPVARIANT propvar, USHORT *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "34fe404c-cef6-47d9-9eaf-8ab151bd4726")] public static extern HRESULT PropVariantToUInt16Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] ushort[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated UInt16 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of UInt16 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of UInt16 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776567")] public static extern HRESULT PropVariantToUInt16VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts an <c>unsigned short</c> value from a PROPVARIANT structure. If no value exists, then the specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="uiDefault"> /// <para>Type: <c>USHORT</c></para> /// <para>Specifies a default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>unsigned short</c></para> /// <para>Returns extracted <c>unsigned short</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a <c>unsigned short</c> value. /// For instance, an application obtaining values from a property store can use this to safely extract the <c>unsigned short</c> /// value for UInt16 properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_UI2</c>, this helper function extracts the <c>unsigned short</c> value. Otherwise, it /// attempts to convert the value in the <c>PROPVARIANT</c> structure into a <c>unsigned short</c>. If a conversion is not possible, /// PropVariantToUInt16 will return a failure code and set puiRet to 0. See PropVariantChangeType for a list of possible conversions. /// Of note, <c>VT_EMPTY</c> is successfully converted to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt16 to access a /// <c>unsigned short</c> value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint16withdefault PSSTDAPI_(USHORT) // PropVariantToUInt16WithDefault( REFPROPVARIANT propvarIn, USHORT uiDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "4346cef2-5e43-47bf-9bfb-0ede923872fd")] public static extern ushort PropVariantToUInt16WithDefault([In] PROPVARIANT propvarIn, ushort uiDefault); /// <summary>Extracts a UInt32 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pulRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776569")] public static extern HRESULT PropVariantToUInt32([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.U4)] out uint pulRet); /// <summary> /// <para>Extracts data from a PROPVARIANT structure into an <c>ULONG</c> vector.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>ULONG*</c></para> /// <para> /// Points to a buffer containing crgn <c>ULONG</c> values. When this function returns, the buffer has been initialized with pcElem /// <c>ULONG</c> elements extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn, in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>ULONG</c> values extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn is too small.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of <c>ULONG</c> /// values with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_VECTOR</c> | <c>VT_UI4</c> or <c>VT_ARRAY</c> | <c>VT_UI4</c>, this helper function /// extracts up to crgn <c>ULONG</c> values and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> contains /// more elements than will fit into the prgn buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt32Vector to access a /// <c>ULONG</c> vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint32vector PSSTDAPI // PropVariantToUInt32Vector( REFPROPVARIANT propvar, ULONG *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "721a2f67-dfd1-4d95-8290-4457b8954a02")] public static extern HRESULT PropVariantToUInt32Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated UInt32 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of UInt32 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of UInt32 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776571")] public static extern HRESULT PropVariantToUInt32VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para>Extracts a <c>ULONG</c> value from a PROPVARIANT structure. If no value exists, then a specified default value is returned.</para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="ulDefault"> /// <para>Type: <c>ULONG</c></para> /// <para>Specifies a default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>ULONG</c></para> /// <para>Returns extracted <c>ULONG</c> value, or default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a <c>ULONG</c> value and would /// like to use a default value if it does not. For instance, an application obtaining values from a property store can use this to /// safely extract the <c>ULONG</c> value for <c>UInt32</c> properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_UI4</c>, this helper function extracts the <c>ULONG</c> value. Otherwise, it attempts to /// convert the value in the <c>PROPVARIANT</c> structure into a <c>ULONG</c>. If the source <c>PROPVARIANT</c> has type /// <c>VT_EMPTY</c> or a conversion is not possible, then PropVariantToUInt32WithDefault will return the default provided by /// ulDefault. See PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt32WithDefault to /// access a <c>ULONG</c> value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint32withdefault PSSTDAPI_(ULONG) // PropVariantToUInt32WithDefault( REFPROPVARIANT propvarIn, ULONG ulDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "8ace8c3f-fea2-4b20-9e0b-3abfbd569b54")] public static extern uint PropVariantToUInt32WithDefault([In] PROPVARIANT propvarIn, uint ulDefault); /// <summary>Extracts a UInt64 property value of a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pullRet">When this function returns, contains the extracted property value if one exists; otherwise, 0.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776573")] public static extern HRESULT PropVariantToUInt64([In] PROPVARIANT propVar, [MarshalAs(UnmanagedType.U8)] out ulong pullRet); /// <summary> /// <para>Extracts data from a PROPVARIANT structure into a <c>ULONGLONG</c> vector.</para> /// </summary> /// <param name="propvar"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="prgn"> /// <para>Type: <c>ULONGLONG*</c></para> /// <para> /// Points to a buffer containing crgn <c>ULONGLONG</c> values. When this function returns, the buffer has been initialized with /// pcElem <c>ULONGLONG</c> elements extracted from the source PROPVARIANT. /// </para> /// </param> /// <param name="crgn"> /// <para>Type: <c>ULONG</c></para> /// <para>Size of the buffer pointed to by prgn, in elements.</para> /// </param> /// <param name="pcElem"> /// <para>Type: <c>ULONG*</c></para> /// <para>When this function returns, contains the count of <c>ULONGLONG</c> values extracted from the source PROPVARIANT structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Returns S_OK if successful, or an error value otherwise.</term> /// </item> /// <item> /// <term>TYPE_E_BUFFERTOOSMALL</term> /// <term>The source PROPVARIANT contained more than crgn values. The buffer pointed to by prgn.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The PROPVARIANT was not of the appropriate type.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold an vector of <c>ULONGLONG</c> /// values with a fixed number of elements. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_VECTOR</c> | <c>VT_UI8</c> or <c>VT_ARRAY</c> | <c>VT_UI8</c>, this helper function /// extracts up to crgn <c>ULONGLONG</c> values and places them into the buffer pointed to by prgn. If the <c>PROPVARIANT</c> /// contains more elements than will fit into the prgn buffer, this function returns an error and sets pcElem to 0. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt64Vector to access a /// <c>ULONGLONG</c> vector value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint64vector PSSTDAPI // PropVariantToUInt64Vector( REFPROPVARIANT propvar, ULONGLONG *prgn, ULONG crgn, ULONG *pcElem ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "596c7a35-6645-4f66-b924-b71278778776")] public static extern HRESULT PropVariantToUInt64Vector([In] PROPVARIANT propvar, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] ulong[] prgn, uint crgn, out uint pcElem); /// <summary>Extracts data from a <see cref="PROPVARIANT"/> structure into a newly allocated UInt64 vector.</summary> /// <param name="propVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pprgf"> /// When this function returns, contains a pointer to a vector of UInt64 values extracted from the source <see cref="PROPVARIANT"/> structure. /// </param> /// <param name="pcElem"> /// When this function returns, contains the count of UInt64 elements extracted from source <see cref="PROPVARIANT"/> structure. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776575")] public static extern HRESULT PropVariantToUInt64VectorAlloc([In] PROPVARIANT propVar, out SafeCoTaskMemHandle pprgf, out uint pcElem); /// <summary> /// <para> /// Extracts <c>ULONGLONG</c> value from a PROPVARIANT structure. If no value exists, then the specified default value is returned. /// </para> /// </summary> /// <param name="propvarIn"> /// <para>Type: <c>REFPROPVARIANT</c></para> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="ullDefault"> /// <para>Type: <c>ULONGLONG</c></para> /// <para>Specifies a default property value, for use where no value currently exists.</para> /// </param> /// <returns> /// <para>Type: <c>ULONGLONG</c></para> /// <para>Returns the extracted unsigned <c>LONGLONG</c> value, or a default.</para> /// </returns> /// <remarks> /// <para> /// This helper function is used in places where the calling application expects a PROPVARIANT to hold a <c>ULONGLONG</c> value and /// would like to use a default value if it does not. For instance, an application obtaining values from a property store can use /// this to safely extract the <c>ULONGLONG</c> value for <c>UInt64</c> properties. /// </para> /// <para> /// If the source PROPVARIANT has type <c>VT_UI8</c>, this helper function extracts the <c>ULONGLONG</c> value. Otherwise, it /// attempts to convert the value in the <c>PROPVARIANT</c> structure into a <c>ULONGLONG</c>. If the source <c>PROPVARIANT</c> has /// type <c>VT_EMPTY</c> or a conversion is not possible, then PropVariantToUInt64WithDefault will return the default provided by /// ullDefault. See PropVariantChangeType for a list of possible conversions. /// </para> /// <para>Examples</para> /// <para> /// The following example, to be included as part of a larger program, demonstrates how to use PropVariantToUInt64WithDefault to /// access a <c>ULONGLONG</c> value in a PROPVARIANT. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propvarutil/nf-propvarutil-propvarianttouint64withdefault // PSSTDAPI_(ULONGLONG) PropVariantToUInt64WithDefault( REFPROPVARIANT propvarIn, ULONGLONG ullDefault ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propvarutil.h", MSDNShortId = "8ca0e25e-6a3f-41ff-9a4a-7cca9a02d07c")] public static extern ulong PropVariantToUInt64WithDefault([In] PROPVARIANT propvarIn, ulong ullDefault); /// <summary>Converts the contents of a <see cref="PROPVARIANT"/> structure to a VARIANT structure.</summary> /// <param name="pPropVar">Reference to the source <see cref="PROPVARIANT"/> structure.</param> /// <param name="pVar">Pointer to a VARIANT structure. When this function returns, the VARIANT contains the converted information.</param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776577")] public static extern HRESULT PropVariantToVariant([In] PROPVARIANT pPropVar, IntPtr pVar); /// <summary> /// <para> /// Extracts data from a PROPVARIANT structure into a Windows Runtime property value. Note that in some cases more than one /// PROPVARIANT type maps to a single Windows Runtime property type. /// </para> /// </summary> /// <param name="propvar"> /// <para>Reference to a source PROPVARIANT structure.</para> /// </param> /// <param name="riid"> /// <para>A reference to the IID of the interface to retrieve through ppv, typically IID_IPropertyValue (defined in Windows.Foundation.h).</para> /// </param> /// <param name="ppv"> /// <para> /// When this method returns successfully, contains the interface pointer requested in riid. This is typically an IPropertyValue /// pointer. If the call fails, this value is <c>NULL</c>. /// </para> /// </param> /// <returns> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para> /// We recommend that you use the IID_PPV_ARGS macro, defined in Objbase.h, to package the riid and ppv parameters. This macro /// provides the correct IID based on the interface pointed to by the value in ppv, which eliminates the possibility of a coding /// error in riid that could lead to unexpected results. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/propsys/nf-propsys-propvarianttowinrtpropertyvalue PSSTDAPI // PropVariantToWinRTPropertyValue( REFPROPVARIANT propvar, REFIID riid, void **ppv ); [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("propsys.h", MSDNShortId = "38DD3673-17FD-4F2A-BA58-A1A9983B92BF")] public static extern HRESULT PropVariantToWinRTPropertyValue([In] PROPVARIANT propvar, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); /// <summary>Deserializes a specified <c>SERIALIZEDPROPERTYVALUE</c> structure, creating a <c>PROPVARIANT</c> structure.</summary> /// <param name="pprop"> /// <para>Type: <c>const <c>SERIALIZEDPROPERTYVALUE</c>*</c></para> /// <para>Pointer to a <c>SERIALIZEDPROPERTYVALUE</c> structure.</para> /// </param> /// <param name="cbMax"> /// <para>Type: <c>ULONG</c></para> /// <para>The size of the <c>SERIALIZEDPROPERTYVALUE</c> structure, in bytes.</para> /// </param> /// <param name="ppropvar"> /// <para>Type: <c><c>PROPVARIANT</c>*</c></para> /// <para>Pointer to the resulting <c>PROPVARIANT</c> structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> // HRESULT StgDeserializePropVariant( _In_ const SERIALIZEDPROPERTYVALUE *pprop, _In_ ULONG cbMax, _Out_ PROPVARIANT *ppropvar); https://msdn.microsoft.com/en-us/library/windows/desktop/bb776578(v=vs.85).aspx [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776578")] public static extern HRESULT StgDeserializePropVariant([In] IntPtr pprop, [In] uint cbMax, [In, Out] PROPVARIANT ppropvar); /// <summary>Serializes a specified <c>PROPVARIANT</c> structure, creating a <c>SERIALIZEDPROPERTYVALUE</c> structure.</summary> /// <param name="ppropvar"> /// <para>Type: <c>const <c>PROPVARIANT</c>*</c></para> /// <para>A constant pointer to the source <c>PROPVARIANT</c> structure.</para> /// </param> /// <param name="ppProp"> /// <para>Type: <c><c>SERIALIZEDPROPERTYVALUE</c>**</c></para> /// <para>The address of a pointer to the <c>SERIALIZEDPROPERTYVALUE</c> structure.</para> /// </param> /// <param name="pcb"> /// <para>Type: <c>ULONG*</c></para> /// <para>A pointer to the value representing the size of the <c>SERIALIZEDPROPERTYVALUE</c> structure.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> // HRESULT StgSerializePropVariant( _In_ const PROPVARIANT *ppropvar, _Out_ SERIALIZEDPROPERTYVALUE **ppProp, _Out_ ULONG *pcb); https://msdn.microsoft.com/en-us/library/windows/desktop/bb776579(v=vs.85).aspx [DllImport(Lib.PropSys, SetLastError = false, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776579")] public static extern HRESULT StgSerializePropVariant([In] PROPVARIANT ppropvar, out SafeCoTaskMemHandle ppProp, out uint pcb); /// <summary>Copies the contents of a VARIANT structure to a <see cref="PROPVARIANT"/> structure.</summary> /// <param name="pVar">Pointer to a source VARIANT structure.</param> /// <param name="pPropVar"> /// Pointer to a <see cref="PROPVARIANT"/> structure. When this function returns, the <see cref="PROPVARIANT"/> contains the /// converted information. /// </param> /// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [DllImport(Lib.PropSys, ExactSpelling = true)] [PInvokeData("Propvarutil.h", MSDNShortId = "bb776616")] public static extern HRESULT VariantToPropVariant([In] IntPtr pVar, [In, Out] PROPVARIANT pPropVar); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OgrenciTakip.Models.Kullanicilar { public class LoggedInUser { public static string KullaniciAdi { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VJBatangas.LomiHouse.Data; using VJBatangas.LomiHouse.Entity; using VJBatangas.LomiHouse.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace VJBatangas.LomiHouse.Business { public class BSUser { protected DatabaseProviderFactory dbProviderFactory; protected DAUser da; protected UserData data; public UserInfo ValidateLogin(string username, string password) { if (String.IsNullOrEmpty(username.Trim()) || String.IsNullOrEmpty(password.Trim())) { return null; } else { da = new DAUser(dbProviderFactory); data = new UserData(); data = da.ValidateLogin(username, password); if (data.ResultCode == ResultCodes.SUCCESSFUL_TRANSACTION) { if (data.UserInformation != null) { return data.UserInformation; } else { return null; } } else { return null; } } } } }
using System.Collections.Generic; namespace Mio.TileMaster { /// <summary> /// Model class, used to store all data belongs to a game session /// </summary> public class GameStateModel { } }
using System; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace eMAM.Data.Migrations { public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), Inactive = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "Customers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), CustomerEGN = table.Column<int>(nullable: false), CustomerPhoneNumber = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Customers", x => x.Id); }); migrationBuilder.CreateTable( name: "GmailUserData", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccessToken = table.Column<string>(nullable: true), RefreshToken = table.Column<string>(nullable: true), ExpiresAt = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_GmailUserData", x => x.Id); }); migrationBuilder.CreateTable( name: "Senders", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), SenderEmail = table.Column<string>(nullable: true), SenderName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Senders", x => x.Id); }); migrationBuilder.CreateTable( name: "Statuses", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), Text = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Statuses", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Emails", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), GmailIdNumber = table.Column<string>(nullable: true), StatusId = table.Column<int>(nullable: false), Body = table.Column<string>(nullable: true), SenderId = table.Column<int>(nullable: false), DateReceived = table.Column<DateTime>(nullable: false), Subject = table.Column<string>(nullable: true), CustomerId = table.Column<int>(nullable: true), MissingApplication = table.Column<bool>(nullable: false), InitialRegistrationInSystemOn = table.Column<DateTime>(nullable: false), SetInCurrentStatusOn = table.Column<DateTime>(nullable: false), SetInTerminalStatusOn = table.Column<DateTime>(nullable: false), OpenedById = table.Column<string>(nullable: true), ClosedById = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Emails", x => x.Id); table.ForeignKey( name: "FK_Emails_AspNetUsers_ClosedById", column: x => x.ClosedById, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Emails_Customers_CustomerId", column: x => x.CustomerId, principalTable: "Customers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Emails_AspNetUsers_OpenedById", column: x => x.OpenedById, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Emails_Senders_SenderId", column: x => x.SenderId, principalTable: "Senders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Emails_Statuses_StatusId", column: x => x.StatusId, principalTable: "Statuses", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Attachments", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), FileName = table.Column<string>(nullable: true), FileSizeInMb = table.Column<double>(nullable: false), EmailId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Attachments", x => x.Id); table.ForeignKey( name: "FK_Attachments_Emails_EmailId", column: x => x.EmailId, principalTable: "Emails", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); migrationBuilder.CreateIndex( name: "IX_Attachments_EmailId", table: "Attachments", column: "EmailId"); migrationBuilder.CreateIndex( name: "IX_Emails_ClosedById", table: "Emails", column: "ClosedById"); migrationBuilder.CreateIndex( name: "IX_Emails_CustomerId", table: "Emails", column: "CustomerId"); migrationBuilder.CreateIndex( name: "IX_Emails_OpenedById", table: "Emails", column: "OpenedById"); migrationBuilder.CreateIndex( name: "IX_Emails_SenderId", table: "Emails", column: "SenderId"); migrationBuilder.CreateIndex( name: "IX_Emails_StatusId", table: "Emails", column: "StatusId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "Attachments"); migrationBuilder.DropTable( name: "GmailUserData"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "Emails"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "Customers"); migrationBuilder.DropTable( name: "Senders"); migrationBuilder.DropTable( name: "Statuses"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TouchRotate : MonoBehaviour { Vector2 currentPosition = Vector2.zero; Vector2 lastPosition = Vector2.zero; Vector2 deltaPosition = Vector2.zero; public float rotateSpeed = 0.5f; public int axis = 1; // Update is called once per frame void Update () { checkTouch(); checkMouse(); } void checkTouch() { if(Input.touchCount == 1) { Touch touch = Input.GetTouch(0); if(axis == 1) { transform.Rotate(0,-touch.deltaPosition.x*rotateSpeed,0); } else { transform.Rotate(touch.deltaPosition.y*rotateSpeed,0,0); } } } void checkMouse() { if(Input.GetButton("Fire1")) { if(currentPosition != Vector2.zero) lastPosition = currentPosition; currentPosition = Input.mousePosition; if(lastPosition != Vector2.zero) deltaPosition = currentPosition - lastPosition; if(axis == 1) { transform.Rotate(0,-deltaPosition.x*rotateSpeed,0); } else { transform.Rotate(deltaPosition.y*rotateSpeed,0,0); } } if(Input.GetButtonUp("Fire1")) { currentPosition = Vector2.zero; lastPosition = Vector2.zero; deltaPosition = Vector2.zero; } } }
using UnityEngine; using UnityEngine.Networking; using System.Collections; using DFrame; using DAV; namespace DPYM { /// <summary> /// 游戏元素(引擎功能部分定义) /// </summary> public partial class GameElement { /* 功能实现 */ // 引擎功能函数 protected virtual void Awake() { } protected virtual void Start() { } protected virtual void Update() { // 若元素死亡,那么不更新 if (!_alive) return; // 更新技能 if (!skillAbsTime.empty) { foreach (ISkill skill in skillAbsTime) { if (skill.Satisfied(this)) skill.Execute(this); } } } protected virtual void LateUpdate() { // 若元素死亡,那么不更新 if (!_alive) return; } protected virtual void FixedUpdate() { // 若元素死亡,那么不更新 if (!_alive) return; // 更新技能 if (!skills.empty) { foreach (ISkill skill in skills) { if (skill.Satisfied(this)) { skill.Execute(this); } } } // 更新控制器 if(null != ctrls.current) { // 更新运动方面 ctrls.current.controller.FixedOperation(this); // 控制器更新 if (ctrls.current.EndOfCtrl()) { // 结束的控制器,去使能 ctrls.current.enable = false; // 重新获取最优控制器 ctrls.Update(); } } } // 响应 protected virtual void OnDestroy() { if (true == _alive) Kill(); if (null != __destroyCallback) __destroyCallback.Invoke(); } protected virtual void OnEnable() { } // 碰撞检测 protected virtual void OnTriggerEnter2D(Collider2D collision) { Transform parent = collision.transform.parent; if (null == parent) { DLogger.DBGMD(string.Format("[WARNING] {0} do not have GameElement parent.", collision.name)); return; } GameElement gameElement = parent.GetComponent<GameElement>(); if(null == gameElement) { DLogger.DBGMD(string.Format("[WARNING] {0} do not hvae GameElment.", parent.name)); return; } switch (collision.tag) { case TagStringSet.collisionRegion: EnterCollisionComponent(gameElement); break; case TagStringSet.affectAcceptRegion: EnterAffectAcceptRegion(gameElement); break; case TagStringSet.affectRegion: EnterAffectRegion(gameElement); break; case TagStringSet.detectAcceptRegion: EnterDetectAcceptRegion(gameElement); break; case TagStringSet.detectRegion: EnterDetectRegion(gameElement); break; default: break; } } protected virtual void OnTriggerExit2D(Collider2D collision) { Transform parent = collision.transform.parent; if (null == parent) { DLogger.DBGMD(string.Format("[WARNING] {0} do not have GameElement parent.", collision.name)); return; } GameElement gameElement = parent.GetComponent<GameElement>(); if (null == gameElement) { DLogger.DBGMD(string.Format("[WARNING] {0} do not hvae GameElment.", parent.name)); return; } switch (collision.tag) { case TagStringSet.collisionRegion: ExitCollisionComponent(gameElement); break; case TagStringSet.affectAcceptRegion: ExitAffectAcceptRegion(gameElement); break; case TagStringSet.affectRegion: ExitAffectRegion(gameElement); break; case TagStringSet.detectAcceptRegion: ExitDetectAcceptRegion(gameElement); break; case TagStringSet.detectRegion: ExitDetectRegion(gameElement); break; default: break; } } protected virtual void OnTriggerStay2D(Collider2D collision) { Transform parent = collision.transform.parent; if (null == parent) { //DLogger.DBGMD(string.Format("[WARNING] {0} do not have GameElement parent.", collision.name)); return; } GameElement gameElement = parent.GetComponent<GameElement>(); if (null == gameElement) { //DLogger.DBGMD(string.Format("[WARNING] {0} do not hvae GameElment.", parent.name)); return; } switch (collision.tag) { case TagStringSet.collisionRegion: StayCollisionComponent(gameElement); break; case TagStringSet.affectAcceptRegion: StayAffectAcceptRegion(gameElement); break; case TagStringSet.affectRegion: StayAffectRegion(gameElement); break; case TagStringSet.detectAcceptRegion: StayDetectAcceptRegion(gameElement); break; case TagStringSet.detectRegion: StayDetectRegion(gameElement); break; default: break; } } } }
using AkkaOverview.Providers.Models; using System; using System.Collections.Generic; namespace AkkaOverview.Providers.Contracts { public interface IStreamProvider { void GetData(string instrument, Action<IEnumerable<Candle>> callback); } }
using System; using System.Collections.Generic; using System.Linq; using HtmlAgilityPack; namespace Comics.Core.Parsers { public static class DilbertParser { public static ComicParseResult Parse(string html) { if (html == null) throw new ArgumentNullException(nameof(html)); if (html == "") throw new ArgumentException("html must have some contents", nameof(html)); var doc = new HtmlDocument(); doc.LoadHtml(html); var img = doc.QuerySelector(".img-comic"); var src = img?.GetAttributeValue("src", null); var meta = doc.QuerySelector("meta[property='article:publish_date']"); var date = meta?.GetAttributeValue("content", null); if (src == null) return ComicParseResult.Fail("Could not find image src"); if (date == null) return ComicParseResult.Fail("Could not find publish date"); if (src.StartsWith("//")) src = "https:" + src; return ComicParseResult.Succeed(new Uri(src), DateTime.Parse(date)); } } }
using ApiTests.Helpers; using ApiTests.Models; using System.Net; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ApiTests.Test { [TestClass] public class LoginTests { [TestMethod] public void LogInSuccessfully() { var loginData = new UserModel() { username = "testaccount", password = "password123" }; var response = ApiFactory.PostMethod<UserModel>("/login", loginData); Assert.AreEqual(response.StatusCode, HttpStatusCode.OK); } [TestMethod] public void LogInWithIncorrectPassword() { var loginData = new UserModel() { username = "testaccount", password = "password1234" }; var response = ApiFactory.PostMethod<UserModel>("/login", loginData); Assert.AreNotEqual(response.StatusCode, HttpStatusCode.OK); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace WEEK3 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { StackPanel spIDcard = new StackPanel(); spIDcard.VerticalAlignment = VerticalAlignment.Top; spIDcard.Orientation = Orientation.Vertical; spIDcard.SetValue(Grid.ColumnProperty, 0); spIDcard.Margin = new Thickness(40, 0, 20, 0); TextBlock tblNew = new TextBlock(); tblNew.Text = "Hello from C#"; tblNew.Margin = new Thickness(5); spIDcard.Children.Add(tblNew); tblNew.Text = "It actually worked"; tblNew.Margin = new Thickness(5); spIDcard.Children.Add(tblNew); this.InitializeComponent(); } } }
namespace DependencyInjectionTest.NoInjection { /// <summary> /// Class with high coupling, high dependence and highly cohesive. /// </summary> public class Company { public Company(Address pAddress) { _address = pAddress; } private int _cod; public int Cod { get { return _cod; } set { _cod = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } private Address _address; public Address Address { get { return _address; } set { _address = value; } } } }
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace iGarson_App { /// <summary> /// Interaction logic for Login_Form.xaml /// </summary> public partial class Login_Form : Window { public Login_Form() { InitializeComponent(); } System.Windows.Threading.DispatcherTimer timer1 = new System.Windows.Threading.DispatcherTimer(); DatabaseScript.MySQL_Connect MSC = new DatabaseScript.MySQL_Connect(Properties.Resources.HostName, Properties.Resources.DatabasePort, Properties.Resources.DatabaseUsername, Properties.Resources.DatabasePassword); private async void Window_Loaded(object sender, RoutedEventArgs e) { timer1.Tick += Timer1_Tick; timer1.Interval = new TimeSpan(0, 0, 3); timer1.IsEnabled = true; timer1.Start(); //PictrueBox1.Source = null; //PictrueBox1.Source = RandomImage(); errorMessage.Visibility = Visibility.Hidden; DatabaseScript.MySQL_Connect.ConnectingState ConnectionState = await MSC.ConnectToDatabaseAsync(); //if (ConnectionState == DatabaseScript.MySQL_Connect.ConnectingState.Successful) // MessageBox.Show("با موفقیت اتصال انجام شد"); //else // MessageBox.Show("اتصال با شکست مواجه شد"); } private void Timer1_Tick(object sender, EventArgs e) { //PictrueBox1.Source = null; //PictrueBox1.Source = RandomImage(); } public BitmapImage RandomImage() { Random ImageNumberRandom = new Random(); int ImageNumber = ImageNumberRandom.Next(0, 6); return new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Assets\\Login\\image" + ImageNumber.ToString() + ".jpg")); } private void button_Click(object sender, RoutedEventArgs e) { errorMessage.Visibility = Visibility.Hidden; } private void label_MouseDown(object sender, MouseButtonEventArgs e) { System.Diagnostics.Process.Start("http://www.mohada.ir"); } private async void LoginBtn_Click(object sender, RoutedEventArgs e) { try { IList<Models.Users> user = await DatabaseScript.MySQL_ReadQuery.Login(UsernameTXT.Text, PasswordTXT.Password, MSC); if (user.Count == 1) { switch (user.FirstOrDefault().Role) { case "0": await MSC.DisConnectFromDatabaseAsync(); Module.Cache.Role = "6a8f147fbdacd1b1a1d381a1f0810b465784c8f6a3c933aca70fe0ecce1debba"; Main_Form ff1 = new Main_Form(); ff1.Show(); this.Close(); timer1.Stop(); break; case "1": await MSC.DisConnectFromDatabaseAsync(); Module.Cache.Role = "0bebf3efd635851b74a6fa860bb2b091a43d536cd35b2f8a9e3e2d020673fa98"; AdminMain_Form AMF = new AdminMain_Form(); AMF.Show(); this.Close(); timer1.Stop(); break; case "2": await MSC.DisConnectFromDatabaseAsync(); Module.Cache.Role = "12c6d98703e4abe4c175f91ad69e3d61e0d704e25079c5ee156fa22cd00affd5"; AccountantMain_Form AcMF = new AccountantMain_Form(); AcMF.Show(); this.Close(); timer1.Stop(); break; } } else { textBlock.Text = "نام کاربری و یا رمز عبور وارد شده اشتباه می باشد."; textBlock.FontSize = 23; errorMessage.Visibility = Visibility.Visible; } } catch(Exception ex) { //MessageBox.Show("خطا شماره 10025\n لطفا با پشتیبانی نرم‌افزار تماس بگیرید\n\n" + ex, "خطا", MessageBoxButton.OK, MessageBoxImage.Error); textBlock.Text = "خطا شماره : 10025\n لطفا با پشتیبانی نرم‌افزار تماس بگیرید\n\n" + ex; textBlock.FontSize = 18; errorMessage.Visibility = Visibility.Visible; } } } }
using System; namespace Phenix.Security.Business { /// <summary> /// 用户可授权角色 /// </summary> [Serializable] [Phenix.Core.Mapping.ReadOnly] public class UserGrantRoleReadOnly : UserGrantRole<UserGrantRoleReadOnly> { } /// <summary> /// 用户可授权角色清单 /// </summary> [Serializable] public class UserGrantRoleReadOnlyList : Phenix.Business.BusinessListBase<UserGrantRoleReadOnlyList, UserGrantRoleReadOnly> { } /// <summary> /// 用户可授权角色 /// </summary> [Serializable] public class UserGrantRole : UserGrantRole<UserGrantRole> { } /// <summary> /// 用户可授权角色清单 /// </summary> [Serializable] public class UserGrantRoleList : Phenix.Business.BusinessListBase<UserGrantRoleList, UserGrantRole> { } /// <summary> /// 用户可授权角色 /// </summary> [Phenix.Core.Mapping.ClassAttribute("PH_USER_GRANT_ROLE", FriendlyName = "用户可授权角色"), System.SerializableAttribute(), System.ComponentModel.DisplayNameAttribute("用户可授权角色")] public abstract class UserGrantRole<T> : Phenix.Business.BusinessBase<T> where T : UserGrantRole<T> { /// <summary> /// GR_ID /// </summary> public static readonly Phenix.Business.PropertyInfo<long?> GR_IDProperty = RegisterProperty<long?>(c => c.GR_ID); [Phenix.Core.Mapping.Field(FriendlyName = "GR_ID", TableName = "PH_USER_GRANT_ROLE", ColumnName = "GR_ID", IsPrimaryKey = true, NeedUpdate = true)] private long? _GR_ID; /// <summary> /// GR_ID /// </summary> [System.ComponentModel.DisplayName("GR_ID")] public long? GR_ID { get { return GetProperty(GR_IDProperty, _GR_ID); } internal set { SetProperty(GR_IDProperty, ref _GR_ID, value); } } [System.ComponentModel.Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] public override string PrimaryKey { get { return GR_ID.ToString(); } } /// <summary> /// 用户 /// </summary> public static readonly Phenix.Business.PropertyInfo<long?> GR_US_IDProperty = RegisterProperty<long?>(c => c.GR_US_ID); [Phenix.Core.Mapping.Field(FriendlyName = "用户", TableName = "PH_USER_GRANT_ROLE", ColumnName = "GR_US_ID", NeedUpdate = true)] [Phenix.Core.Mapping.FieldLink("PH_USER", "US_ID")] private long? _GR_US_ID; /// <summary> /// 用户 /// </summary> [System.ComponentModel.DisplayName("用户")] public long? GR_US_ID { get { return GetProperty(GR_US_IDProperty, _GR_US_ID); } set { SetProperty(GR_US_IDProperty, ref _GR_US_ID, value); } } /// <summary> /// 角色 /// </summary> public static readonly Phenix.Business.PropertyInfo<long?> GR_RL_IDProperty = RegisterProperty<long?>(c => c.GR_RL_ID); [Phenix.Core.Mapping.Field(FriendlyName = "角色", TableName = "PH_USER_GRANT_ROLE", ColumnName = "GR_RL_ID", NeedUpdate = true)] [Phenix.Core.Mapping.FieldLink("PH_ROLE", "RL_ID")] private long? _GR_RL_ID; /// <summary> /// 角色 /// </summary> [System.ComponentModel.DisplayName("角色")] public long? GR_RL_ID { get { return GetProperty(GR_RL_IDProperty, _GR_RL_ID); } set { SetProperty(GR_RL_IDProperty, ref _GR_RL_ID, value); } } /// <summary> /// 录入人 /// </summary> public static readonly Phenix.Business.PropertyInfo<string> InputerProperty = RegisterProperty<string>(c => c.Inputer); [Phenix.Core.Mapping.Field(FriendlyName = "录入人", Alias = "GR_INPUTER", TableName = "PH_USER_GRANT_ROLE", ColumnName = "GR_INPUTER", NeedUpdate = true, OverwritingOnUpdate = true, IsInputerColumn = true)] private string _inputer; /// <summary> /// 录入人 /// </summary> [System.ComponentModel.DisplayName("录入人")] public string Inputer { get { return GetProperty(InputerProperty, _inputer); } } /// <summary> /// 录入时间 /// </summary> public static readonly Phenix.Business.PropertyInfo<DateTime?> InputTimeProperty = RegisterProperty<DateTime?>(c => c.InputTime); [Phenix.Core.Mapping.Field(FriendlyName = "录入时间", Alias = "GR_INPUTTIME", TableName = "PH_USER_GRANT_ROLE", ColumnName = "GR_INPUTTIME", NeedUpdate = true, OverwritingOnUpdate = true, IsInputTimeColumn = true)] private DateTime? _inputTime; /// <summary> /// 录入时间 /// </summary> [System.ComponentModel.DisplayName("录入时间")] public DateTime? InputTime { get { return GetProperty(InputTimeProperty, _inputTime); } } } }
namespace TwitCreds { public class SettingsConstants { public const string CONSUMER_KEY = nameof(CONSUMER_KEY); public const string CONSUMER_SECRET = nameof(CONSUMER_SECRET); public const string ACCESS_TOKEN = nameof(ACCESS_TOKEN); public const string ACCESS_TOKEN_SECRET = nameof(ACCESS_TOKEN_SECRET); } }
using System; using System.Collections.Generic; using System.Text; namespace gView.Drawing.Pro { static class Extensions { } }
using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; namespace CORE.Многомерные { public class HookeJeevesPs : OptimisationMethod { private readonly double _rho; public HookeJeevesPs(double rho = 0.5): base("Хук-Дживс [Pattern Search]", 1e-5, null, null) { _rho = rho; } public override void Execute() { var nvars = Fh.Point.Count; var x0 = Fh.Point; //Стартовая точка IterationCount = 0; var delta = new DenseVector(nvars); for (var i = 0; i < nvars; i++) { delta[i] = _rho; } DenseVector originalDelta = delta; while (delta.AbsoluteMinimum() > Eps && IterationCount < MaxIterations) { Vector<double> x1 = ExplanotorySearch(x0, delta); if (Fh.Y(x1) < Fh.Y(x0)) { //x1 лучше чем x0 delta = originalDelta; while (true) { Vector<double> x2 = x0 + 2* (x1 - x0); x2 = ExplanotorySearch(x2, delta); if (Fh.Y(x2) < Fh.Y(x1)) { //х2 лучше чем х1 x0 = x1; x1 = x2; } else { //x2 хуже чем х1 x0 = x1; break; } } } else { // x1 хуже чем х0 delta /= 2; } IterationCount++; } Answer = x0; } /// <summary> /// Передаются ссылки, point и delta будут изменены /// </summary> /// <param name="delta"></param> /// <param name="point"></param> /// <returns></returns> private Vector<double> ExplanotorySearch( Vector<double> point, Vector<double> delta) { var nvars = delta.Count; var prevbest = Fh.Y(point); var z = new DenseVector(nvars); point.CopyTo(z); int i; var minf = prevbest; for (i = 0; i < nvars; i++) { z[i] = point[i] + delta[i]; var ftmp = Fh.Y(z); if (ftmp < minf) minf = ftmp; else { z[i] = point[i] -delta[i]; ftmp = Fh.Y(z); if (ftmp < minf) minf = ftmp; else { z[i] = point[i]; } } } return z; } } }
using EngineLibrary.Collisions; using EngineLibrary.Components; using EngineLibrary.Graphics; using System.Collections.Generic; namespace GameLibrary.Components { /// <summary> /// Компонент коллайдера /// </summary> public class ColliderComponent : ObjectComponent { private static List<ObjectCollision> _collisions = new List<ObjectCollision>(); /// <summary> /// Добавление коллайдера на сцену /// </summary> public void AddCollisionOnScene() { _collisions.Add(GameObject.Collision); } /// <summary> /// Удаление коллайдера на сцене /// </summary> public void RemoveCollisionFromScene() { _collisions.Remove(GameObject.Collision); } /// <summary> /// Проверка столкновения коллайдера с другими объектами с тегам /// </summary> /// <param name="gameObject">Пересекаемый объект или NULL</param> /// <param name="tag">Тэг объкта, с которым проверяется пересечение</param> /// <returns>Результат пересечения</returns> public bool CheckIntersects(out Game3DObject gameObject, string tag = "") { foreach(var collision in _collisions) { if (tag == "" || collision.GameObject.Tag != tag) continue; if(collision != GameObject.Collision) { var result = ObjectCollision.Intersects(GameObject.Collision, collision); if(result) { gameObject = collision.GameObject; return result; } } } gameObject = null; return false; } } }
using System; namespace Delegates { public class ResizeEffect : IEffect { public void Apply(IPicture pic) { Console.WriteLine("Applies resize"); } } }
using System; using System.Collections.Generic; using System.Text; namespace Domain.Interfaces { public interface IGenericRepository<T> where T : class { void Add(T entity); } }
using System.Collections.Generic; namespace AzureAI.CognitiveSearch.CustomSkills.Infrastructure.Model { public class WebApiSkillRequest { public List<WebApiRequestRecord> Values { get; set; } = new List<WebApiRequestRecord>(); } }
using System.Net; namespace WebApi.Responses { public class WebApiNotFoundResponse : WebApiResponse { public WebApiNotFoundResponse(string message = null) : base(HttpStatusCode.NotFound, message) { } } }
namespace TripDestination.Common.Infrastructure.Constants { public class AssembliesConstants { public const string Services = "TripDestination.Services"; } }
using System.Threading; using System.Web.Query.Dynamic; using Framework.Core.Common; using Framework.Core.Config; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Oberon.Dashboard { public class Dashboard : DashboardBasePage { #region Page Objects public IWebElement ProfileName { get { return _driver.FindElement(By.CssSelector(".profileName>a")); } } public IWebElement TenantName { get { return _driver.FindElement(By.CssSelector(".campaignName")); } } public IWebElement DashboardLink { get { return _driver.FindElement(By.LinkText("Dashboard")); } } public IWebElement SwitchAccountLink { get { return _driver.FindElement(By.LinkText("Switch Account")); } } public IWebElement LogoutLink { get { return _driver.FindElement(By.LinkText("Logout")); } } public IWebElement ContactsNav { get { return _driver.FindElement(By.CssSelector(".mega.contact")); } } public IWebElement FinanceNav { get { return _driver.FindElement(By.CssSelector(".mega.finance")); } } public IWebElement CreateSearchLink { get { return _driver.FindElement(By.CssSelector("//a[@title='Create Search]")); } } public IWebElement ContactNav { get { return _driver.FindElement(By.CssSelector("#contactNav")); } } public IWebElement ManageUsersLink { get { return _driver.FindElement(By.LinkText("Manage Users")); } } public IWebElement OnlinePageManagerLink { get { return _driver.FindElement(By.LinkText("Online Page Manager")); } } public IWebElement ImportContactsLink { get { return _driver.FindElement(By.LinkText("Import Contacts")); } } #endregion public Dashboard(Driver driver) : base(driver) { } #region Methods /// <summary> /// returns tenant name from text field /// </summary> public string GetTenantName() { _driver.GoToPage(AppConfig.OberonBaseUrl); return TenantName.Text; } public long GetTenantId() { HoverOverAdminDropDown(); string url = _driver.FindElement(By.LinkText("Manage Users")).GetAttribute("href").ToString(); url = url.Substring(url.IndexOf("=") + 1); return long.Parse(url); } /// <summary> /// clicks online page manager link /// </summary> public void ClickOnlinePageManager() { _driver.Click(OnlinePageManagerLink); } /// <summary> /// clicks financial batch manager link /// </summary> public void FBMLink() { _driver.MoveToElement(FinanceNav); Thread.Sleep(3500); var link = FinanceNav.FindElement(By.LinkText("Batch Manager")); _driver.JavascriptClick(link); } public void ClickImportContactsLink() { _driver.Click(ImportContactsLink); } #endregion } }
using Xunit; namespace Anagram { public class AnagramTest { [Fact] public void AnagramTest_StringsMatchTrue() { var testAnagram = new Anagram(); Assert.Equal(true, testAnagram.IsAnagram("n", "n")); } [Fact] public void AnagramTest_StringsMatchFalse() { var testAnagram = new Anagram(); Assert.Equal(false, testAnagram.IsAnagram("n", "a")); } [Fact] public void AnagramTest_StringIsAnagramTrue() { var testAnagram = new Anagram(); Assert.Equal(true, testAnagram.IsAnagram("read", "dear")); } [Fact] public void AnagramTest_StringIsAnagramFalse() { var testAnagram = new Anagram(); Assert.Equal(false, testAnagram.IsAnagram("read", "reed")); } [Fact] public void AnagramTest_MultipleAreAnagramsTrue() { var testAnagram = new Anagram(); Assert.Equal(true, testAnagram.IsAnagram("read", "dare dear")); } [Fact] public void AnagramTest_MultipleAreAnagramsFalse() { var testAnagram = new Anagram(); Assert.Equal(false, testAnagram.IsAnagram("read", "zare zear")); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CurrentValueScript : MonoBehaviour { private Text text; private IEnumerator changingValueDisplayedCoroutine; private SliderScript sliderScript; void Awake() { text = GetComponent<Text>(); } public void setValueDisplayed(int newValueDisplayed) { text.text = newValueDisplayed.ToString(); } public void BeginChangingValueDisplayed(SliderScript newSliderScript) { if (changingValueDisplayedCoroutine == null) { sliderScript = newSliderScript; changingValueDisplayedCoroutine = ChangingValueDisplayedCoroutine(); StartCoroutine(changingValueDisplayedCoroutine); } } public void StopChangingValueDisplayed() { if (changingValueDisplayedCoroutine != null) { StopCoroutine(changingValueDisplayedCoroutine); } changingValueDisplayedCoroutine = null; } private IEnumerator ChangingValueDisplayedCoroutine() { while (true) { yield return null; text.text = ((int) sliderScript.getCurrentValue()).ToString(); } } }
using AsyncClasses; using Contracts.Callback; using Contracts.ContentOps; using System.Collections.Generic; using System.IO; using System.ServiceModel; using System.Threading; using System.Threading.Tasks; namespace Services.ContentOps { [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession, AutomaticSessionShutdown = true)] public class ContentOpsAsyncService : IContentOpsAsyncService { #region Private Fields /// <summary> /// The callback instance, which runs in its own channel. /// </summary> private IAsyncServiceCallback mCallback = OperationContext.Current.GetCallbackChannel<IAsyncServiceCallback>(); private ContentOpsTableLoader mClient = null; private List<int> mIds = new List<int>(); private object mLock = new object(); #endregion #region Constructors public ContentOpsAsyncService() { } #endregion #region Public Methods public Task<MemoryStream> AddSapphireRejectionsAsync(object userState) { TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>(); //Set the UserState object to our member variable for cancellation. using (mClient = userState as ContentOpsTableLoader) { mClient.Ids.Clear(); mClient.Ids.AddRange(mIds); //Attach the Completed event. mClient.GetDataCompleted += (o, p) => { if (p.Error != null) tcs.TrySetException(p.Error); else if (p.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(p.Data); //I have added this delay because the cancellation request does not get passed through //when running without a breakpoint. Adding this Sleep() here seems to help. Thread.Sleep(750); mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled); }; //Attach the ProgressChanged event. mClient.GetDataProgressChanged += (o, p) => { mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState); }; mClient.AddSapphireRejectionsAsync(); } return tcs.Task; } public void CancelAddRejectionsAsync() { mClient.CancelAddRejectionsAsync(); } public void CancelGetProductionDataAsync() { mClient.GetProductionDataAsyncCancel(); } public void CancelGetSpecialProjectsDataAsync() { mClient.GetSpecialProjectsDataAsyncCancel(); } public Task<MemoryStream> GetProductionDataAsync(object userState) { TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>(); //Set the UserState object to our member variable for cancellation. using (mClient = userState as ContentOpsTableLoader) { //Attach the Completed event. mClient.GetDataCompleted += (o, p) => { if (p.Error != null) tcs.TrySetException(p.Error); else if (p.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(p.Data); //I have added this delay because the cancellation request does not get passed through //when running without a breakpoint. Adding this Sleep() here seems to help. Thread.Sleep(750); mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled); }; //Attach the ProgressChanged event. mClient.GetDataProgressChanged += (o, p) => { mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState); }; mClient.GetProductionDataAsync(); } return tcs.Task; } public Task<MemoryStream> GetSpecialProjectsDataAsync(object userState) { TaskCompletionSource<MemoryStream> tcs = new TaskCompletionSource<MemoryStream>(); //Set the UserState object to our member variable for cancellation. using (mClient = userState as ContentOpsTableLoader) { if (mIds.Count > 0) mClient.Ids = mIds; //Attach the Completed event. mClient.GetDataCompleted += (o, p) => { if (p.Error != null) tcs.TrySetException(p.Error); else if (p.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(p.Data); //I have added this delay because the cancellation request does not get passed through //when running without a breakpoint. Adding this Sleep() here seems to help. Thread.Sleep(750); mCallback.Completed(p.Data, p.Instance, p.Error, p.Cancelled); }; //Attach the ProgressChanged event. mClient.GetDataProgressChanged += (o, p) => { mCallback.ReportProgress(p.TotalCount, p.CurrentCount, p.Message, p.Instance, p.Data, userState); }; mClient.GetSpecialProjectsDataAsync(); } return tcs.Task; } public void SendNextChunk(List<int> ids) { //Load up the IDs before processing. //Lock this update to prevent the system from throwing an ArgumentException relating to array length. lock (mLock) { mIds.AddRange(ids); } } #endregion } }
using Microsoft.Extensions.Logging; using Yalla_Notlob_Akl.DB; using Yalla_Notlob_Akl.Models; namespace Yalla_Notlob_Akl.Controllers { public class ItemsController : BaseController<Item,ItemDao> { private readonly ILogger<ItemsController> _logger; public ItemsController(ILogger<ItemsController> logger): base(new ItemDao()) { _logger = logger; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Utilities; namespace PersonalSafetyOptions { public partial class PistolMain : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } protected string GetMetaKeywords { get { return SharedTools.GetMetaTag("PistolMain"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Clinica_Odontologica.Dados; using Clinica_Odontologica.Models; using Microsoft.AspNetCore.Mvc; namespace Clinica_Odontologica.Controllers { public class PacienteController : Controller { public IActionResult Cadastrar() { return View(); } [HttpPost] public IActionResult Cadastrar(Paciente paciente) { int id = BancoDeDados.Instance().GetPacientes().Count + 1; paciente.Id = id; BancoDeDados.Instance().Add(paciente); ViewData["exibirAlert"] = true; ModelState.Clear(); return View("Cadastrar"); } public IActionResult Deletar(int id) { BancoDeDados.Instance().Remover(id); return RedirectToAction("Index", "Home"); } } }
namespace Sitecore.AntiPackageWizard.Util { using Sitecore.Data; using Sitecore.Data.Managers; using Sitecore.Diagnostics; using Sitecore.Install; using Sitecore.Install.Files; using Sitecore.Install.Framework; using Sitecore.Install.Items; using Sitecore.Install.Zip; using Sitecore.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; public class ZipPackageBuilder : PackageBuilderBase { public ZipPackageBuilder([NotNull] string fileName) : base(fileName) { Assert.ArgumentNotNull(fileName, nameof(fileName)); } protected override string BuildPackage() { var project = new PackageProject(); var sourceCollection = new SourceCollection<PackageEntry>(); var itemSource = new ExplicitItemSource { SkipVersions = false }; sourceCollection.Add(itemSource); var list = new List<ID>(); foreach (var item in Items) { var i = item; if (list.Any(id => id == i.ID)) { continue; } list.Add(item.ID); var reference = new ItemReference(item.Database.Name, item.Paths.Path, item.ID, LanguageManager.DefaultLanguage, Data.Version.Latest).Reduce(); itemSource.Entries.Add(reference.ToString()); } var fileSource = new ExplicitFileSource(); sourceCollection.Add(fileSource); foreach (var fileName in Files) { if (FileUtil.IsFolder(fileName)) { foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories)) { var fileInfo = new FileInfo(file); if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { continue; } if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } fileSource.Entries.Add(file); } } else { fileSource.Entries.Add(fileName); } } project.Sources.Add(sourceCollection); project.Name = "Sitecore Package"; project.Metadata.PackageName = PackageName; project.Metadata.Author = Author; project.Metadata.Version = Version; project.Metadata.Publisher = Publisher; project.Metadata.License = License; project.Metadata.Comment = Comment; project.Metadata.Readme = Readme; project.Metadata.PostStep = PostStep; var context = new SimpleProcessingContext(); var intermediateFile = GetIntermediateFileName(FileName); try { using (var writer = new PackageWriter(PathUtils.MapPath(intermediateFile))) { writer.Initialize(context); PackageGenerator.GeneratePackage(project, writer); } Commit(intermediateFile, FileName); } catch { Cleanup(intermediateFile); throw; } return FileName; } private static void Cleanup([NotNull] string tempFile) { Debug.ArgumentNotNull(tempFile, nameof(tempFile)); try { File.Delete(tempFile); } catch { return; } } private static void Commit([NotNull] string tempFile, [NotNull] string filename) { Debug.ArgumentNotNull(filename, nameof(filename)); Debug.ArgumentNotNull(tempFile, nameof(tempFile)); if (filename != tempFile) { try { File.Delete(filename); } catch (Exception e) { Log.Error(e.Message, typeof(PackageGenerator)); } try { File.Move(tempFile, filename); } catch (Exception e) { Log.Error(e.Message, typeof(PackageGenerator)); } } } [NotNull] private static string GetIntermediateFileName([NotNull] string filename) { Debug.ArgumentNotNull(filename, nameof(filename)); var result = filename; while (File.Exists(result)) { result = Path.Combine(Path.GetDirectoryName(filename) ?? string.Empty, Path.GetRandomFileName() + Install.Constants.PackageExtension); } return result; } } }
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL: svn://utopia/projects/GXDeviceEditor/Development/AddIns/DLMS/UIPropertyEditor.cs $ // // Version: $Revision: 870 $, // $Date: 2009-09-29 17:21:48 +0300 (ti, 29 syys 2009) $ // $Author: airija $ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source software; you can redistribute it // and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 of the License. // Gurux Device Framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- using System; using System.Windows.Forms; using System.Drawing.Design; using System.Windows.Forms.Design; namespace DLMS { /// <summary> /// Summary description for UIPropertyEditor. /// </summary> public class UIPropertyEditor : UITypeEditor { IWindowsFormsEditorService edSvc = null; TreeView m_tree = null; /// <summary> /// Shows a dropdown icon in the property editor /// </summary> /// <param name="context">The context of the editing control</param> /// <returns>Returns <c>UITypeEditorEditStyle.DropDown</c></returns> public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } /// <summary> /// Load default images for device tree. /// </summary> /// <param name="Images"></param> void LoadDefaultImages(ImageList.ImageCollection Images) { System.Drawing.Bitmap bm = null; //Load device categories image System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceCategories.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } //Load device category image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceCategory.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(System.Drawing.Color.FromArgb(255, 0, 255)); Images.Add(bm); } //Load device tables image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceTables.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } //Load device table image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceTable.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } //Load device properties image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceProperties.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } //Load device property image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DeviceProperty.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } //Load None image stream = this.GetType().Assembly.GetManifestResourceStream("DLMS.Resources.DatabaseNone.bmp"); if (stream != null) { bm = new System.Drawing.Bitmap(stream); bm.MakeTransparent(); Images.Add(bm); } } /// <summary> /// Overrides the method used to provide basic behaviour for selecting editor. /// Shows our custom control for editing the value. /// </summary> /// <param name="context">The context of the editing control</param> /// <param name="provider">A valid service provider</param> /// <param name="value">The current value of the object to edit</param> /// <returns>The new value of the object</returns> public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) { if (context == null || context.Instance == null || provider == null) { return base.EditValue(context, provider, value); } if (m_tree == null) { m_tree = new TreeView(); m_tree.BorderStyle = BorderStyle.None; m_tree.ImageList = new ImageList(); LoadDefaultImages(m_tree.ImageList.Images); } m_tree.Nodes.Clear(); GuruxDeviceEditor.GXDevice device = (GuruxDeviceEditor.GXDevice) context.Instance; //IGXComponent Comp = (IGXComponent) type.Parent; //GuruxDeviceEditor.GXDevice device = (GuruxDeviceEditor.GXDevice) ((System.Drawing.Design.DesignerHost) context.Container).GetService(typeof(GuruxDeviceEditor.GXDevice)); if ((edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService))) == null) { return value; } // Create a CheckedListBox and populate it with all the propertylist values TreeNode NoneNode = new TreeNode("None"); NoneNode.ImageIndex = NoneNode.SelectedImageIndex = 6; m_tree.Nodes.Add(NoneNode); TreeNode parent = m_tree.Nodes.Add("Tables"); parent.Tag = device.Tables; parent.ImageIndex = 2; foreach(GuruxDeviceEditor.GXTable table in device.Tables) { TreeNode node = parent.Nodes.Add(table.Name); node.SelectedImageIndex = node.ImageIndex = 3; node.Tag = table; foreach(GuruxDeviceEditor.GXProperty prop in table.Properties) { TreeNode item = node.Nodes.Add(prop.Name); item.SelectedImageIndex = item.ImageIndex = 5; item.Tag = prop; if (value == prop) { m_tree.SelectedNode = item; item.EnsureVisible(); } } } parent = m_tree.Nodes.Add("Categories"); parent.ImageIndex = 0; parent.Tag = device.Categories; foreach(GuruxDeviceEditor.GXCategory cat in device.Categories) { TreeNode node = parent.Nodes.Add(cat.Name); node.SelectedImageIndex = node.ImageIndex = 1; node.Tag = cat; foreach(GuruxDeviceEditor.GXProperty prop in cat.Properties) { TreeNode item = node.Nodes.Add(prop.Name); item.Tag = prop; item.SelectedImageIndex = item.ImageIndex = 5; if (value == prop) { m_tree.SelectedNode = item; item.EnsureVisible(); } } } m_tree.DoubleClick += new System.EventHandler(this.DoubleClick); // Show Listbox as a DropDownControl. This methods returns only when the dropdowncontrol is closed edSvc.DropDownControl(m_tree); if (m_tree.SelectedNode != null) { if (m_tree.SelectedNode.Tag is GuruxDeviceEditor.GXProperty) { return m_tree.SelectedNode.Tag; } if (m_tree.SelectedNode.Tag == null) { return null; } } return value; } /// <summary> /// Close wnd when user selects new item. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DoubleClick(object sender, System.EventArgs e) { //Do nothing If property or empty item is not selected. if (m_tree.SelectedNode != null && !(m_tree.SelectedNode.Tag == null || (m_tree.SelectedNode.Tag is GuruxDeviceEditor.GXProperty))) { return; } if (edSvc != null) { edSvc.CloseDropDown(); } } } }
using FeedbackAndSurveyService.SurveyService.Model; namespace FeedbackAndSurveyService.SurveyService.Service { public interface ISurveyReportService { SurveyReport GetDoctorSurveyReport(string jmbg); SurveyReport GetHospitalSurveyReport(); SurveyReport GetMedicalStaffSurveyReport(); } }
namespace NHibernate.DependencyInjection.Tests.Model { public class CatBehavior { public string Meow() { return "meow"; } public string Purr() { return "purrrrr.......purrrrr......"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using AnyTest.ClientAuthentication; using Microsoft.AspNetCore.Identity; using AnyTest.IDataRepository; using AnyTest.Model; using Microsoft.AspNetCore.Http; using System.Web; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using Microsoft.EntityFrameworkCore; using Microsoft.Data.SqlClient; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace AnyTest.DataService.Controllers { /// <summary> /// \~english A controller for managing user accounts /// \~ukrainia Контроллер для керуввання аккаунтами користувачі /// </summary> [Route("api/[controller]")] [ApiController] public class AccountsController : ControllerBase { private readonly UserManager<IdentityUser> _userManager; private readonly AnyTestIdentityDbContext _idb; private readonly IPersonRepository _people; /// <summary> /// \~english Creates new instance of <c>AccountsController</c> /// \~ukrainian Створює новий екземляр <c>AccountsController</c> /// </summary> /// <param name="userManager"> /// \~english <c>UserManager{IdentitityUser}</c> instance. Dependency. /// \~ukrainian Екземпляр <c>UserManager{IdentitityUser}</c>. Залежність. /// </param> /// <param name="idb"> /// \~english An identity database context instance. Dependency/ /// \~ukrainian Екземпляр контексту бази даних користувачів. Залежність. /// </param> /// <param name="people"> /// \~english The class <c>IPersonRepository</c> instance. Dependency. /// \~ukrainian Екземпляр класу, який втілює <c>IPersonRepository</c>. Залежність /// </param> public AccountsController(UserManager<IdentityUser> userManager, IPersonRepository people, AnyTestIdentityDbContext idb) { _userManager = userManager; _people = people; _idb = idb; } /// <summary> /// \~english Creates a new user account /// \~ukrainian Створює нового користувача /// </summary> /// <param name="model"> /// \~english An instance of a <c>RegisterModel</c>, conatining new user acccount data /// \~ukrainian Екземпляр класу <c>RegisterModel</c>, якій місить дані нового користувача /// </param> /// <returns> /// \~english A result of an account creation /// \~ukrainian Результат створення нового користувача /// </returns> /// <example> /// \~english An example of HTTP request to create a person /// \~ukrainian Приклад HTTP запиту створення особистих даних користувача /// <code> /// POST: api/Accounts /// </code> /// </example> [HttpPost] public async Task<IActionResult> Post([FromBody] RegisterModel model) { var newUser = new IdentityUser { UserName = model.UserName, Email = model.Email }; var result = await _userManager.CreateAsync(newUser, model.Password); if(!result.Succeeded) { var errors = result.Errors.Select(x => x.Description); return Ok(new RegisterResult { Successful = false, Errors = errors }); } foreach(var role in model.Roles) { if(AuthService.Roles.Contains(role)) await _userManager.AddToRoleAsync(newUser, role); } return Ok(new RegisterResult { Successful = true }); } /// <summary> /// \~english Returns a <c>Person</c> correspoinding current registered user /// \~ukrainian Повертає особисті дані разреєстрованого користувача /// </summary> /// <returns> /// \~english A <c>Person</c> object with user data /// \~ukrainian Об'єкт класу <c>Person</c> з особистими даними користувача /// </returns> /// /// <example> /// \~english An example of HTTP request to get registered user data /// \~ukrainian Приклад HTTP запиту особистих даних зареєстрованого користувача /// <code> /// GET: api/Accounts/Person /// </code> /// </example> [HttpGet("person")] [Authorize] public async Task<Person> Person () { Person person = new Person(); if (HttpContext.User.Identity is ClaimsIdentity identity) { var email = identity.FindFirst(ClaimTypes.Email).Value; person = await _people.FindByEmail(email) ?? new Person { Email = email}; } return person; } /// <summary> /// \~english Returns an info about all registered users /// \~ukrainian Пвертає дані усіх зареєстрованих користувачів /// </summary> /// <returns> /// \~english A collection of user info /// \~ukrainian Колекцію даних всіх зареєстрованих користувачів /// </returns> /// /// <example> /// \~english An example of HTTP request to get all registered user's info /// \~ukrainian Приклад HTTP запиту даних усіх зареєстроваих користувачів /// <code> /// GET: api/Accounts/Users /// </code> /// </example> [HttpGet("users")] [Authorize(Roles = "Administrator")] public async Task<IEnumerable<UserInfo>> Users() { var identityUserInfo = await _idb.UserInfos(); var personalInfo = await _people.Get(); var result = from user in identityUserInfo join person in personalInfo on user.Email equals person.Email into grp from pordef in grp.DefaultIfEmpty() select new UserInfo { User = user.User, Email = user.Email, Name = $"{pordef?.FamilyName ?? ""} {pordef?.FirstName ?? ""} {pordef?.Patronimic ?? ""}".Trim(), UserPersonId = pordef?.Id, Roles = user.Roles }; return result; } } }
//using gView.DataSources.Fdb.MSAccess; //using gView.DataSources.Fdb.MSSql; //using gView.Framework.Data; //using gView.Framework.FDB; //using gView.Framework.system; //using System; //using System.Collections.Generic; //using System.Data; //using System.IO; //using System.Threading.Tasks; //namespace gView.DataSources.Fdb.UI //{ // public class FDBImageDataset // { // public delegate void ReportActionEvent(FDBImageDataset sender, string action); // public delegate void ReportProgressEvent(FDBImageDataset sender, int progress); // public delegate void ReportRequestEvent(FDBImageDataset sender, RequestArgs args); // public event ReportActionEvent ReportAction = null; // public event ReportProgressEvent ReportProgress = null; // public event ReportRequestEvent ReportRequest = null; // private gView.Framework.Db.ICommonDbConnection _conn = null; // private string _errMsg = String.Empty, _dsname = ""; // private IImageDB _fdb = null; // private CancelTracker _cancelTracker; // public FDBImageDataset(IImageDB fdb, string dsname) // { // _fdb = fdb; // _dsname = dsname; // if (_fdb is AccessFDB) // { // _conn = ((AccessFDB)_fdb)._conn; // } // _cancelTracker = new CancelTracker(); // } // public string lastErrorMessage // { // get { return _errMsg; } // } // public ICancelTracker CancelTracker // { // get { return _cancelTracker; } // } // #region ImageDataset // async public Task<bool> InsertImageDatasetBitmap(int image_id, IRasterLayer layer, int levels, System.Drawing.Imaging.ImageFormat format) // { // if (_conn == null) // { // _errMsg = "Not Connected (use Open...)"; // return false; // } // if (layer.RasterClass == null) // { // _errMsg = "No Rasterclass..."; // return false; // } // DataTable tab = await _conn.Select("*", "FDB_Datasets", "Name='" + _dsname + "' AND ImageDataset=1"); // if (tab == null) // { // _errMsg = _conn.errorMessage; // return false; // } // if (tab.Rows.Count == 0) // { // _errMsg = "Can't find ImageDataset"; // return false; // } // string imageSpace = tab.Rows[0]["ImageSpace"].ToString(); // if (imageSpace.Equals("unmanaged")) // { // return true; // } // if (imageSpace.Equals(System.DBNull.Value) || imageSpace.Equals("database") || imageSpace.Equals("")) // { // _errMsg = "Not implemented (imageSpace==database)"; // } // else // { // _errMsg = "Not implemented (imageSpace!=unmanaged)"; // } // return false; // } // public Task<bool> UpdateImageDatasetBitmap(int image_id) // { // /* // try // { // string filename = (string)await _conn.QuerySingleField("SELECT PATH FROM FC_" + _dsname + "_IMAGE_POLYGONS WHERE FDB_OID=" + image_id, "PATH"); // if (filename == null) // { // _errMsg = "Can't find File with OID=" + image_id; // return false; // } // RasterFileLayer rLayer = new RasterFileLayer(null, filename); // if (!rLayer.isValid) // { // _errMsg = "No valid image file:" + filename; // return false; // } // // Geometrie updaten // QueryFilter filter = new QueryFilter(); // filter.AddField("*"); // filter.WhereClause = "FDB_OID=" + image_id; // IFeatureCursor cursor = ((IFDB)_fdb).Query(_dsname + "_IMAGE_POLYGONS", filter); // if (cursor == null) // { // _errMsg = "Can't query for polygon feature with OID=" + image_id; // return false; // } // IFeature feature = cursor.NextFeature; // cursor.Release(); // if (feature == null) // { // _errMsg = "No polygon feature in featureclass " + _dsname + "_IMAGE_POLYGONS with OID=" + image_id; // return false; // } // feature.Shape = rLayer.Polygon; // FileInfo fi = new FileInfo(filename); // feature["LAST_MODIFIED"] = fi.LastWriteTime; // if (rLayer is IRasterFile && ((IRasterFile)rLayer).WorldFile != null) // { // IRasterWorldFile world = ((IRasterFile)rLayer).WorldFile; // fi = new FileInfo(world.Filename); // if (fi.Exists) // { // feature["LAST_MODIFIED2"] = fi.LastWriteTime; // feature["PATH2"] = fi.FullName; // } // feature["CELLX"] = world.cellX; // feature["CELLY"] = world.cellY; // } // if (!((IFeatureUpdater)_fdb).Update(_dsname + "_IMAGE_POLYGONS", feature)) // { // _errMsg = ((IFDB)_fdb).lastErrorMsg; // return false; // } // ImageFormat format = ImageFormat.Jpeg; // switch (feature["FORMAT"].ToString().ToLower()) // { // case "png": // format = ImageFormat.Png; // break; // case "tif": // case "tiff": // format = ImageFormat.Tiff; // break; // } // if (!DeleteImageDatasetItem(image_id, true)) // { // return false; // } // if (!InsertImageDatasetBitmap(image_id, rLayer, (int)feature["LEVELS"], format)) // { // return false; // } // return true; // } // catch (Exception ex) // { // _errMsg = ex.Message; // return false; // } // */ // _errMsg = "This method is not implemented any more..."; // return Task.FromResult(false); // } // async public Task<bool> DeleteImageDatasetItem(int image_id, bool bitmapOnly) // { // if (image_id == -1) // { // return false; // } // var isImageDatasetResult = await _fdb.IsImageDataset(_dsname); // string imageSpace = isImageDatasetResult.imageSpace; // if (!isImageDatasetResult.isImageDataset) // { // return false; // } // if (imageSpace.Equals(System.DBNull.Value)) // { // imageSpace = "database"; // } // DataTable tab = await _conn.Select("*", "FC_" + _dsname + "_IMAGE_POLYGONS", "FDB_OID=" + image_id, ""/*, ((bitmapOnly) ? false : true)*/); // if (tab == null) // { // _errMsg = _conn.errorMessage; // return false; // } // if (tab.Rows.Count != 1) // { // _errMsg = "Can't find Record with OID=" + image_id; // return false; // } // DataRow row = tab.Rows[0]; // bool managed = (bool)row["MANAGED"]; // string managed_file = row["MANAGED_FILE"].ToString(); // if (!bitmapOnly) // { // row.Delete(); // if(!_conn.ExecuteNoneQuery($"DELETE FROM FC_{ _dsname }_IMAGE_POLYGONS WHERE FDB_OID={ image_id }")) // //if (!_conn.Update(tab)) // { // _errMsg = _conn.errorMessage; // return false; // } // } // if (!managed) // { // return true; // } // switch (imageSpace.ToLower()) // { // case "": // case "database": // if (!_conn.ExecuteNoneQuery($"DELETE FROM { _dsname }_IMAGE_DATA WHERE IMAGE_ID={ image_id }")) // { // _errMsg = _conn.errorMessage; // return false; // } // //DataTable images = await _conn.Select("ID", _dsname + "_IMAGE_DATA", "IMAGE_ID=" + image_id, ""); // //if (images == null) // //{ // // _errMsg = _conn.errorMessage; // // return false; // //} // //if (images.Rows.Count > 0) // //{ // // foreach (DataRow r in images.Rows) // // { // // r.Delete(); // // } // // if (_conn.Update(images)) // // { // // _errMsg = _conn.errorMessage; // // return false; // // } // //} // break; // default: // try // { // FileInfo fi = new FileInfo(imageSpace + @"/" + managed_file); // if (!fi.Exists) // { // _errMsg = "Can't find file '" + fi.FullName + "'"; // return false; // } // fi.Delete(); // } // catch (Exception ex) // { // _errMsg = ex.Message; // return false; // } // break; // } // return true; // } // async public Task<int> GetImageDatasetItemID(string image_path) // { // if (_conn == null) // { // return -1; // } // object ID = await _conn.QuerySingleField("SELECT FDB_OID FROM FC_" + _dsname + "_IMAGE_POLYGONS WHERE PATH='" + image_path + "'", "FDB_OID"); // if (ID == null) // { // return -1; // } // return Convert.ToInt32(ID); // } // #endregion // #region Import // private string[] _formats = "jpg|png|tif|tiff|sid|jp2".Split('|'); // private int _levels = 4; // private bool _managed = false; // async public Task<bool> Import(string path, Dictionary<string, Guid> providers) // { // //_cancelTracker.Reset(); // if (!_cancelTracker.Continue) // { // _errMsg = "Canceled by user..."; // return false; // } // if (!(_fdb is AccessFDB)) // { // _errMsg = "Database in not a FeatureDatabase..."; // return false; // } // AccessFDB fdb = (AccessFDB)_fdb; // if (ReportAction != null) // { // ReportAction(this, "Open Raster Polygon Class..."); // } // IFeatureClass rasterFC = await fdb.GetFeatureclass(_dsname, _dsname + "_IMAGE_POLYGONS"); // if (rasterFC == null) // { // if (rasterFC == null) // { // Console.WriteLine("\n\nERROR: Open Featureclass - Can't init featureclass " + _dsname + "_IMAGE_POLYGONS"); // return false; // } // } // DirectoryInfo di = new DirectoryInfo(path); // FileInfo fi = new FileInfo(path); // if (di.Exists) // { // await SearchImages(fdb, rasterFC, di, providers); // //if (_recalculateExtent) fdb.CalculateSpatialIndex(rasterFC, 100); // } // else if (fi.Exists) // { // if (!await InsertImage(fdb, rasterFC, fi, providers)) // { // return false; // } // //if (_recalculateExtent) fdb.CalculateSpatialIndex(rasterFC, 100); // } // if (!_cancelTracker.Continue) // { // _errMsg = "Canceled by user..."; // return false; // } // return true; // } // async private Task SearchImages(IFeatureUpdater fdb, IFeatureClass rasterFC, DirectoryInfo di, Dictionary<string, Guid> providers) // { // if (!_cancelTracker.Continue) // { // return; // } // if (ReportAction != null) // { // ReportAction(this, "Scan Directory: " + di.FullName); // } // foreach (string filter in _formats) // { // int count = 0; // foreach (FileInfo fi in di.GetFiles("*." + filter)) // { // if (_cancelTracker != null && !_cancelTracker.Continue) // { // return; // } // if (await InsertImage(fdb, rasterFC, fi, providers)) // { // count++; // } // if (!_cancelTracker.Continue) // { // return; // } // } // } // foreach (DirectoryInfo sub in di.GetDirectories()) // { // await SearchImages(fdb, rasterFC, sub, providers); // } // } // async private Task<bool> InsertImage(IFeatureUpdater fdb, IFeatureClass rasterFC, FileInfo fi, Dictionary<string, Guid> providers) // { // if (!_cancelTracker.Continue) // { // _errMsg = "Canceled by user..."; // return false; // } // if (ReportAction != null) // { // ReportAction(this, "Insert Image: " + fi.FullName); // } // if (ReportProgress != null) // { // ReportProgress(this, 1); // } // System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg; // switch (fi.Extension.ToLower()) // { // case ".png": // format = System.Drawing.Imaging.ImageFormat.Png; // break; // case ".tif": // case ".tiff": // format = System.Drawing.Imaging.ImageFormat.Tiff; // break; // } // #region RasterFileDataset bestimmen // List<IRasterFileDataset> rFileDatasets = new List<IRasterFileDataset>(); // IRasterFileDataset rFileDataset = null; // IRasterLayer rasterLayer = null; // PlugInManager compMan = new PlugInManager(); // foreach (var dsType in compMan.GetPlugins(Plugins.Type.IDataset)) // { // IRasterFileDataset rds = compMan.CreateInstance<IDataset>(dsType) as IRasterFileDataset; // if (rds == null) // { // continue; // } // if (rds.SupportsFormat(fi.Extension) < 0) // { // continue; // } // if (providers != null && providers.ContainsKey(fi.Extension.ToLower())) // { // if (!providers[fi.Extension.ToLower()].Equals(PlugInManager.PlugInID(rds))) // { // continue; // } // } // rFileDatasets.Add(rds); // } // if (rFileDatasets.Count == 0) // { // _errMsg = "No Rasterfile Provider for " + fi.Extension; // return false; // } // // RasterFileDataset nach priorität sortieren // rFileDatasets.Sort(new RasterFileDatasetComparer(fi.Extension)); // // RasterFileDataset suchen, mit dem sich Bild öffnen läßt // foreach (IRasterFileDataset rfd in rFileDatasets) // { // rfd.AddRasterFile(fi.FullName); // if ((await rfd.Elements()).Count == 0) // { // //Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster File..."); // continue; // } // IDatasetElement element = (await rfd.Elements())[0]; // if (!(element is IRasterLayer)) // { // //Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster Layer..."); // rFileDataset.Dispose(); // continue; // } // // gefunden... // rasterLayer = (IRasterLayer)element; // rFileDataset = rfd; // break; // } // if (rasterLayer == null || rFileDataset == null) // { // Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster Layer..."); // return false; // } // #endregion // FileInfo fiWorld = null; // double cellX = 1; // double cellY = 1; // IRasterFile rasterFile = null; // if (rasterLayer is IRasterFile) // { // rasterFile = (IRasterFile)rasterLayer; // } // if (rasterLayer.RasterClass != null) // { // if (rasterLayer.RasterClass is IRasterFile && // ((IRasterFile)rasterLayer.RasterClass).WorldFile != null) // { // rasterFile = (IRasterFile)rasterLayer.RasterClass; // } // else // { // IRasterClass c = rasterLayer.RasterClass; // cellX = Math.Sqrt(c.dx1 * c.dx1 + c.dx2 * c.dx2); // cellY = Math.Sqrt(c.dy1 * c.dy1 + c.dy2 * c.dy2); // } // } // if (rasterFile != null) // { // try // { // IRasterWorldFile world = rasterFile.WorldFile; // if (world != null) // { // if (!world.isGeoReferenced) // { // if (handleNonGeorefAsError) // { // _errMsg = "Can't add non georeferenced images: " + fi.FullName; // return false; // } // else // { // return true; // } // } // cellX = Math.Sqrt(world.dx_X * world.dx_X + world.dx_Y * world.dx_Y); // cellY = Math.Sqrt(world.dy_X * world.dy_X + world.dy_Y * world.dy_Y); // fiWorld = new FileInfo(rasterFile.WorldFile.Filename); // if (!fiWorld.Exists) // { // fiWorld = null; // } // } // } // catch // { // fiWorld = null; // } // } // #region Check if already Exits // // // // Suchen, ob Image mit gleichen Pfad schon vorhanden ist, wenn ja // // nur weitermachen, wenn sich das änderungsdatum unterscheidet... // // // QueryFilter filter = new QueryFilter(); // filter.AddField("FDB_OID"); // filter.AddField("PATH"); // filter.AddField("LAST_MODIFIED"); // filter.AddField("PATH2"); // filter.AddField("LAST_MODIFIED2"); // string fullName = fi.FullName.Replace(@"\", @"\\"); // if (_fdb is AccessFDB) // { // filter.WhereClause = ((AccessFDB)_fdb).DbColName("PATH") + "='" + fullName + "'"; // } // else // { // filter.WhereClause = "PATH='" + fullName + "'"; // } // int deleteOID = -1; // using (IFeatureCursor cursor = await rasterFC.GetFeatures(filter)) // { // IFeature existingFeature = await cursor.NextFeature(); // if (existingFeature != null) // { // DateTime dt1 = (DateTime)existingFeature["LAST_MODIFIED"]; // if (Math.Abs((dt1 - fi.LastWriteTimeUtc).TotalSeconds) > 1.0) // { // deleteOID = existingFeature.OID; // } // else if (fiWorld != null && // existingFeature["PATH2"] != System.DBNull.Value && // existingFeature["PATH2"].ToString() != String.Empty) // { // DateTime dt2 = (DateTime)existingFeature["LAST_MODIFIED2"]; // if (existingFeature["PATH2"].ToString().ToLower() != fiWorld.FullName.ToLower() || // Math.Abs((dt2 - fiWorld.LastWriteTimeUtc).TotalSeconds) > 1.0) // { // deleteOID = existingFeature.OID; // } // } // if (deleteOID == -1) // { // Console.Write("."); // //Console.WriteLine(fi.FullName + " already exists..."); // return true; // } // } // } // if (deleteOID != -1) // { // if (!await fdb.Delete(rasterFC, deleteOID)) // { // Console.WriteLine(_errMsg = "Can't delete old record " + fi.FullName + "\n" + fdb.LastErrorMessage); // return false; // } // } // // // /////////////////////////////////////////////////////////////////// // // // #endregion // Feature feature = new Feature(); // feature.Shape = rasterLayer.RasterClass.Polygon; // feature.Fields.Add(new FieldValue("PATH", fi.FullName)); // feature.Fields.Add(new FieldValue("LAST_MODIFIED", fi.LastWriteTimeUtc)); // if (fiWorld != null) // { // feature.Fields.Add(new FieldValue("PATH2", fiWorld.FullName)); // feature.Fields.Add(new FieldValue("LAST_MODIFIED2", fiWorld.LastWriteTimeUtc)); // } // else // { // feature.Fields.Add(new FieldValue("PATH2", "")); // } // feature.Fields.Add(new FieldValue("RF_PROVIDER", PlugInManager.PlugInID(rFileDataset).ToString())); // feature.Fields.Add(new FieldValue("MANAGED", _managed && (rasterLayer is IBitmap))); // feature.Fields.Add(new FieldValue("FORMAT", fi.Extension.Replace(".", ""))); // feature.Fields.Add(new FieldValue("CELLX", cellX)); // feature.Fields.Add(new FieldValue("CELLY", cellY)); // feature.Fields.Add(new FieldValue("LEVELS", (_managed) ? Math.Max(_levels, 1) : 0)); // if (!await fdb.Insert(rasterFC, feature)) // { // Console.WriteLine("\nERROR@" + fi.FullName + ": " + fdb.LastErrorMessage); // } // else // { // if (_managed && (rasterLayer is IBitmap) && (fdb is SqlFDB)) // { // QueryFilter qfilter = new QueryFilter(); // qfilter.SubFields = "FDB_OID"; // if (_fdb is AccessFDB) // { // filter.WhereClause = ((AccessFDB)_fdb).DbColName("PATH") + "='" + fi.FullName + "'"; // } // else // { // qfilter.WhereClause = "PATH='" + fi.FullName + "'"; // } // IFeatureCursor cursor = await ((SqlFDB)fdb).Query(rasterFC, qfilter); // if (cursor != null) // { // IFeature feat = await cursor.NextFeature(); // if (feat != null) // { // await InsertImageDatasetBitmap(feat.OID, rasterLayer, _levels, format); // } // cursor.Dispose(); // } // } // Console.WriteLine(">" + fi.FullName + " added..."); // } // rFileDataset.Dispose(); // return true; // } // #endregion // #region Remove Unexisting // async public Task<bool> RemoveUnexisting() // { // if (!(_fdb is AccessFDB)) // { // return false; // } // IFeatureClass rasterFC = await ((AccessFDB)_fdb).GetFeatureclass(_dsname, _dsname + "_IMAGE_POLYGONS"); // if (rasterFC == null) // { // if (rasterFC == null) // { // Console.WriteLine("\n\nERROR: Open Featureclass - Can't init featureclass " + _dsname + "_IMAGE_POLYGONS"); // return false; // } // } // if (ReportAction != null) // { // ReportAction(this, "Remove unexisting"); // } // if (ReportProgress != null) // { // ReportProgress(this, 1); // } // QueryFilter filter = new QueryFilter(); // filter.AddField("FDB_OID"); // filter.AddField("PATH"); // filter.AddField("LAST_MODIFIED"); // filter.AddField("PATH2"); // filter.AddField("LAST_MODIFIED2"); // List<int> Oids = new List<int>(); // using (IFeatureCursor cursor = await rasterFC.GetFeatures(filter)) // { // IFeature feature; // while ((feature = await cursor.NextFeature()) != null) // { // string path = (string)feature["PATH"]; // string path2 = (string)feature["PATH2"]; // try // { // if (!String.IsNullOrEmpty(path)) // { // FileInfo fi = new FileInfo(path); // if (!fi.Exists) // { // Console.Write("*"); // Oids.Add(feature.OID); // continue; // } // } // if (!String.IsNullOrEmpty(path2)) // { // FileInfo fi = new FileInfo(path2); // if (!fi.Exists) // { // Console.Write("*"); // Oids.Add(feature.OID); // continue; // } // } // Console.Write("."); // } // catch (Exception ex) // { // Console.WriteLine(_errMsg = "Exception: " + ex.Message); // } // } // foreach (int oid in Oids) // { // if (!await ((AccessFDB)_fdb).Delete(rasterFC, oid)) // { // Console.WriteLine(_errMsg = "Can't delete record OID=" + oid); // return false; // } // } // return true; // } // } // #endregion // #region Helper // private class RasterFileDatasetComparer : IComparer<IRasterFileDataset> // { // private string _extension; // public RasterFileDatasetComparer(string extension) // { // _extension = extension; // } // #region IComparer<IRasterFileDataset> Member // public int Compare(IRasterFileDataset x, IRasterFileDataset y) // { // int xx = x.SupportsFormat(_extension); // int yy = y.SupportsFormat(_extension); // if (xx > yy) // { // return -1; // } // if (xx < yy) // { // return 1; // } // return 0; // } // #endregion // } // #endregion // #region Errorhandling // public bool handleNonGeorefAsError = true; // #endregion // } //}
using UnityEngine; namespace PJEI.Lanes { [RequireComponent(typeof(InputControl))] public class LaneCreator : MonoBehaviour { /// <summary> /// Position used as reference to create the others from. /// </summary> public Transform originLane; /// <summary> /// Distance between lanes. /// </summary> public Vector2 laneGaps = new Vector2(1, 1.94f); /// <summary> /// Number of lanes per row. /// </summary> public int lanesX = 3; /// <summary> /// Number of lanes per column. /// </summary> public int lanesY = 2; /// <summary> /// Lanes generated. /// </summary> private Transform[][] lanes = null; /// <summary> /// Current column. /// </summary> private int currentX = 0; /// <summary> /// Current row. /// </summary> private int currentY = 0; private InputControl control; void Start() { control = GetComponent<InputControl>(); // Create the new lanes, adding to the origin position lanes = new Transform[lanesX][]; for (int x = 0; x < lanesX; x++) { lanes[x] = new Transform[lanesY]; for (int y = 0; y < lanesY; y++) { // Create a new object to use as a lane Transform newLane = new GameObject("Lane" + x + "" + y).transform; newLane.position = originLane.position + new Vector3(laneGaps.x * x, laneGaps.y * y, 0); // Making them the origin's children keeps the scene much tidier newLane.transform.parent = originLane.transform; // Add the new lane to the matrix lanes[x][y] = newLane; } } currentX = lanesX / 2; currentY = lanesY / 2; } // Update is called once per frame void Update() { // Move around the matrix, but never going out of its bounds if (control.GetRightJustPressed()) { currentX = Mathf.Min(currentX + 1, lanesX - 1); animation.Play("right"); } else if (control.GetLeftJustPressed()) { currentX = Mathf.Max(currentX - 1, 0); animation.Play("left"); } else if (control.GetUpJustPressed()) { currentY = Mathf.Min(currentY + 1, lanesY - 1); animation.Play("up"); } else if (control.GetDownJustPressed()) { currentY = Mathf.Max(currentY - 1, 0); animation.Play("down"); } } private Vector3 CurrentPosition() { return lanes[currentX][currentY].position; } /// <summary> /// Visual aid to debug and verify the lanes are where we want them. /// The current one is painted solid, instead of in wireframe. /// </summary> void OnDrawGizmosSelected() { if (lanes == null) return; Color color = Gizmos.color; Gizmos.color = Color.magenta; for (int x = 0; x < lanesX; x++) { for (int y = 0; y < lanesY; y++) { Transform lane = lanes[x][y]; Gizmos.DrawRay(lane.position, lane.forward); if (x == currentX && y == currentY) Gizmos.DrawSphere(lane.position, .5f); else Gizmos.DrawWireSphere(lane.position, .5f); } } Gizmos.color = color; } } }
using System.Collections.Generic; using Fingo.Auth.Domain.Models.UserModels; namespace Fingo.Auth.Domain.Users.Interfaces { public interface IGetAllFromProjectUser { IEnumerable<UserModel> Invoke(int projectId); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public const string _httpServerAdrees = "https://localhost:44338/"; public string HttpServerAdrees { get { return _httpServerAdrees; } } public string _token; public string Token { get { return _token; } set { _token = value; } } public string _id; public string Id { get { return _id; } set { _id = value; } } public string _name; public string Name { get { return _name; } set { _name = value; } } public DateTime _dateBirth; public DateTime DateBirth { get { return _dateBirth; } set { _dateBirth = value; } } private void Awake() { int count = FindObjectsOfType<Player>().Length; if (count > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } }
using DPI.Model; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace XUnitTestBusinnesLayer { public class DPITestUnit { [Fact] void TestFactory() { } } }
 using System; using System.Collections.Generic; using System.IO.IsolatedStorage; using System.Linq; using System.Text; using System.Threading.Tasks; using Lottery.Entities; using Lottery.Interfaces.Analyzer; namespace Lottery.Service.Analyzer { public class SequenceOrderAnalyzer : IAnalyzer { public async Task<List<AnalyzeResult>> Analyze(List<LotteryRecord> records, int period, int variableTwo) { records = records.OrderByDescending(r => r.ID).Take(period).OrderBy(o => o.ID).ToList(); var result = new List<AnalyzeResult>(); var first = records.FirstOrDefault(); var maxNumber = first?.MaxNumber; var maxNumberSp = first?.MaxSpecialNumber; var normals = new Dictionary<int, int>(); var specials = new Dictionary<int, int>(); for (int i = 1; i <= maxNumber; i++) normals.Add(i, 0); for (int i = 1; i <= maxNumberSp; i++) specials.Add(i, 0); foreach (var record in records) { normals[record.First] += 6; normals[record.Second] += 5; normals[record.Third] += 4; normals[record.Fourth] += 3; normals[record.Fifth] += 2; normals[record.Sixth] += 1; specials[record.Special]++; } result.AddRange(normals.OrderByDescending(n => n.Value).Select(n => new AnalyzeResult { IsSpecial = false, Number = n.Key, Point = n.Value })); result.AddRange(specials.OrderByDescending(n => n.Value).Select(n => new AnalyzeResult { IsSpecial = true, Number = n.Key, Point = n.Value })); return result; } } }
using System; namespace EcoCombustivel.Modelo { public class Controle { public double CalcularEtanol(Combustivel combustivel) { //etanol return combustivel.Etanol(combustivel.CustoEtanol, combustivel.KmEtanol); } public Double CalcularGasolina(Combustivel combustivel) { //Gasolina return combustivel.Gasolina(combustivel.CustoGasolina, combustivel.KmGasolina); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CellsSimulation.Abstact { abstract class KeyControl { public virtual bool React(ref int x, ref int y, PressEvent press) => false; public virtual bool StartEvent(PressEvent key, ref int x, ref int y) => false; } }
using System; using System.Linq; using MultiplayerEmotes.Framework.Patches; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; namespace MultiplayerEmotes.Framework.Network { public class MultiplayerModMessage { private readonly IModHelper helper; public MultiplayerModMessage(IModHelper helper) { this.helper = helper; SubscribeEvents(); } public void SubscribeEvents() { this.helper.Events.Multiplayer.ModMessageReceived += this.OnModMessageReceived; } public void UnsubscribeEvents() { this.helper.Events.Multiplayer.ModMessageReceived -= this.OnModMessageReceived; } public void Send(EmoteMessage message) { Type messageType = typeof(EmoteMessage); #if DEBUG ModEntry.ModMonitor.Log($"Sending message.\n\tFromPlayer: \"{Game1.player.UniqueMultiplayerID}\"\n\tFromMod: \"{helper.ModRegistry.ModID}\"\n\tType: \"{messageType}\"", LogLevel.Trace); #endif helper.Multiplayer.SendMessage(message, messageType.ToString(), new[] { helper.ModRegistry.ModID }); } public void OnModMessageReceived(object sender, ModMessageReceivedEventArgs e) { #if DEBUG ModEntry.ModMonitor.Log($"Received message.\n\tFromPlayer: \"{e.FromPlayerID}\"\n\tFromMod: \"{e.FromModID}\"\n\tType: \"{e.Type}\"", LogLevel.Trace); #endif Type messageType = typeof(EmoteMessage); if(e.FromModID != helper.ModRegistry.ModID || e.Type != messageType.ToString()) { return; } EmoteMessage message = e.ReadAs<EmoteMessage>(); switch(message.EmoteSourceType) { case CharacterType.Farmer: if(long.TryParse(message.EmoteSourceId, out long farmerId)) { Farmer farmer = Game1.getFarmer(farmerId); if(farmer != null) { FarmerPatch.DoEmotePatch.Instance.PostfixEnabled = false; farmer.IsEmoting = false; farmer.doEmote(message.EmoteIndex); FarmerPatch.DoEmotePatch.Instance.PostfixEnabled = true; } } break; case CharacterType.NPC: NPC npc = Game1.getCharacterFromName(message.EmoteSourceId); if(npc != null && !npc.IsEmoting) { CharacterPatch.DoEmotePatch.Instance.PostfixEnabled = false; npc.IsEmoting = false; npc.doEmote(message.EmoteIndex); CharacterPatch.DoEmotePatch.Instance.PostfixEnabled = true; } break; case CharacterType.FarmAnimal: if(long.TryParse(message.EmoteSourceId, out long farmAnimalId)) { FarmAnimal farmAnimal = Game1.getFarm().getAllFarmAnimals().FirstOrDefault(x => x?.myID.Value == farmAnimalId); if(farmAnimal != null && !farmAnimal.IsEmoting) { CharacterPatch.DoEmotePatch.Instance.PostfixEnabled = false; farmAnimal.IsEmoting = false; farmAnimal.doEmote(message.EmoteIndex); CharacterPatch.DoEmotePatch.Instance.PostfixEnabled = true; } } break; case CharacterType.Unknown: default: break; } } } }
using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Web; namespace BingusBot { internal static class Program { private static async Task Main(string[] args) { var services = new ServiceCollection(); ConfigureServices(services); await using (var serviceProvider = services.BuildServiceProvider()) { var bot = serviceProvider.GetService<DiscordBot>(); if (bot != null) await bot.Run(args); } } private static void ConfigureServices(IServiceCollection services) { services.AddSingleton<DiscordBot>(); services.AddLogging ( builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddNLog("nlog.config"); } ); services.AddMemoryCache(); } } }
using System; using System.Windows.Forms; using Microsoft.Win32; namespace SetLockScreenForAllUser { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void setLockScreen(string imgPath) { RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP"); key.SetValue("LockScreenImagePath", @imgPath, RegistryValueKind.String); key.SetValue("LockScreenImageUrl", @imgPath, RegistryValueKind.String); key.SetValue("LockScreenImageStatus", 1, RegistryValueKind.DWord); key.Close(); MessageBox.Show("Lockscreen set to "+ @imgPath +". Please restart your computer to see changes.", "Universal Lockscreen Setter"); } private string getImagePath() { string path = ""; OpenFileDialog getPath = new OpenFileDialog(); getPath.Title = "Select your lockscreen:"; getPath.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"; if (getPath.ShowDialog() == DialogResult.OK) { path = getPath.FileName; } return path; } private void SelectBtn_Click(object sender, EventArgs e) { ImageView.ImageLocation = getImagePath(); SetLockScreenBtn.Visible = true; } private void SetLockScreenBtn_Click(object sender, EventArgs e) { setLockScreen(ImageView.ImageLocation); ImageView.ImageLocation = ""; SetLockScreenBtn.Visible = false; } } }
using System; using AutoMapper; using Microsoft.Practices.Unity; using OrgMan.Data.UnitOfWork; using OrgMan.Domain.Handler.HandlerBase; using OrgMan.DomainContracts.Session; namespace OrgMan.Domain.Handler.Session { public class CreateSessionQueryHandler : QueryHandlerBase { private readonly CreateSessionQuery _query; public CreateSessionQueryHandler(CreateSessionQuery query, IUnityContainer unityContainer) : base(unityContainer) { _query = query; } public Guid Handle() { DataModel.Session session = Mapper.Map<DataModel.Session>(_query.Session); session.UID = Guid.NewGuid(); session.SysInsertTime = DateTimeOffset.Now; session.SysInsertAccountUID = Guid.NewGuid(); OrgManUnitOfWork uow = new OrgManUnitOfWork(); uow.SessionRepository.Insert(session); uow.Commit(); return session.UID; } } }
namespace Template { using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class Template : IDisposable { private const string CodeExpressionOpenBracket = "[%"; private const string CodeExpressionCloseBracket = "%]"; private const string OutputVariableName = "output"; private readonly IScript script; public Template(IProgrammingLanguage language, string templateCode, string[] usings, params Variable[] variables) { if (!IsBracketsCorresponding(templateCode)) { throw new BracketsNotCorrespondsException(); } if (IsTemplateCodeLanguageIndependent(templateCode)) { this.script = new PlainTextOutputScript(templateCode); return; } if (language == null) { throw new ArgumentNullException("language"); } { var vars = variables.ToList(); vars.Add(new Variable("output", ArgumentType.Output)); variables = vars.ToArray(); } var code = new TemplateCodeBuilder(language.GetCodeBuilder(), templateCode, usings, variables).BuildCode(); this.script = language.Compile(code); } public void Render(TextWriter output, params object[] values) { this.script.Run(values.Concat(new[] { output }).ToArray()); } public void Dispose() { this.script.Dispose(); } private class TemplateCodeBuilder { private readonly ICodeBuilder codeBuilder; private string templateCode; private readonly string[] usings; private readonly Variable[] variables; public TemplateCodeBuilder(ICodeBuilder codeBuilder, string templateCode, string[] usings, params Variable[] variables) { this.codeBuilder = codeBuilder; this.templateCode = templateCode; this.usings = usings; this.variables = variables; } public override string ToString() { return this.BuildCode(); } public string BuildCode() { ProcessTextOutputs(); ProcessExpressionOutputs(); ProcessRepeatExpressions(); ProcessConditionExpressions(); RemoveCodeBrackets(); AsMethod(); AsProgram(); return this.templateCode; } private void ProcessTextOutputs() { this.templateCode = Regex.Replace( this.templateCode, @"(?:(?<=\A).*?(?=\[%))|(?:(?<=%\]).*?(?=\[%))|(?:(?!.*%\])(?!\]).*(?=\Z))", match => String.IsNullOrEmpty(match.Value) ? String.Empty : String.Format("[%{0}%]", this.codeBuilder.WrapAsPlainTextOutputStatement(match.Value, OutputVariableName)), RegexOptions.Singleline); } private void ProcessExpressionOutputs() { this.templateCode = Regex.Replace( this.templateCode, @"\[%=(.*?)%\]", match => String.IsNullOrEmpty(match.Groups[1].Value) ? String.Empty : codeBuilder.WrapAsExpressionOutput(match.Groups[1].Value, OutputVariableName), RegexOptions.Singleline); } private void ProcessRepeatExpressions() { this.templateCode = Regex.Replace( this.templateCode, @"\[%\@(?!%)(.*?)%\]", match => this.codeBuilder.OpenRepeatExpression(match.Groups[1].Value), RegexOptions.Singleline); this.templateCode = Regex.Replace( this.templateCode, @"\[%\@%\]", match => this.codeBuilder.CloseRepeatExpression(), RegexOptions.Singleline); } private void ProcessConditionExpressions() { this.templateCode = Regex.Replace( this.templateCode, @"\[%\?(?!%)(.*?)%\]", match => this.codeBuilder.OpenConditionExpression(match.Groups[1].Value), RegexOptions.Singleline); this.templateCode = Regex.Replace( this.templateCode, @"\[%\?%\]", match => this.codeBuilder.CloseConditionExpression(), RegexOptions.Singleline); } private void RemoveCodeBrackets() { this.templateCode = this.templateCode.Replace("[%", String.Empty).Replace("%]", String.Empty); } private void AsMethod() { this.templateCode = this.codeBuilder.WrapAsMethod(this.templateCode, variables); } private void AsProgram() { this.templateCode = this.codeBuilder.WrapAsProgram(this.templateCode, usings); } } private static bool IsBracketsCorresponding(string templateCode) { var openBrackets = Regex.Matches( templateCode, Regex.Escape(CodeExpressionOpenBracket), RegexOptions.Singleline); var closeBrackets = Regex.Matches( templateCode, Regex.Escape(CodeExpressionCloseBracket), RegexOptions.Singleline); if (openBrackets.Count != closeBrackets.Count) { return false; } var allBrackets = openBrackets.Cast<Match>() .Concat(closeBrackets.Cast<Match>()) .OrderBy(match => match.Index); for (var bracketIndex = 0; bracketIndex < allBrackets.Count(); bracketIndex++) { var bracket = allBrackets.ElementAt(bracketIndex).Value; var correctBracket = bracketIndex % 2 == 0 ? CodeExpressionOpenBracket : CodeExpressionCloseBracket; if (bracket != correctBracket) { return false; } } return true; } private static bool IsTemplateCodeLanguageIndependent(string templateCode) { return !templateCode.Contains(CodeExpressionOpenBracket); } } }
using System.Collections.Generic; namespace NetDDD.Core.Contracts { /// <summary> /// Represents a domain entity. /// </summary> /// <typeparam name="TId">Unique identifier of the entity.</typeparam> public interface IEntity<TId> { /// <summary> /// Gets the identity of the entity. /// </summary> TId Id { get; } /// <summary> /// Gets the domain events within the entity. /// </summary> /// <returns>A collection of domain events.</returns> IEnumerable<IDomainEvent> GetDomainEvents(); } }
using System.Net.Http; using System.Web.Http; using ExpenseBucket.Core; using ExpenseBucket.Core.Entities; namespace ExpenseBucket.WebApi.Controllers { [RoutePrefix("expensebucketapi/category")] public class CategoryController : ApiController { private readonly IUnitOfWork _unitOfWork; public CategoryController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unidade8.ExercicioSlides { class _4forWhile { static void Main11(string[] args) { Console.Write("Informe um valor a ser divido pelo maior valor inteiro do visual studio: "); int y = Convert.ToInt32(Console.ReadLine()); int v = 2147483647; do { v /= 2; int h = v /= y; Console.WriteLine("Com o valor informado: "+h); Console.WriteLine("Dividido por 2: "+v); } while (v >= 100); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using appglobal.models; using Newtonsoft.Json; using Microsoft.EntityFrameworkCore; namespace appglobal { public class loginModel : PageModel { gls_model _context = new gls_model(AppGlobal.get_db_option()); //simplifying context initializer by override public void OnGet() { } /// <summary> /// Handle onPost Login AJAX based dengan return value JsonResult /// </summary> /// <param name="request_parameter"></param> /// <param name="returnURL"></param> /// <returns></returns> public JsonResult OnPost(string request_parameter, string returnURL = null) { dynamic login_object = JsonConvert.DeserializeObject(request_parameter); string user_name = login_object["username"]; string password = login_object["password"]; //Console.WriteLine("user_name>> " + user_name); //Console.WriteLine("password >> " + password); AppResponseMessage arm = new AppResponseMessage(); if (!string.IsNullOrWhiteSpace(user_name) && !string.IsNullOrWhiteSpace(password)) { //jika masukan username & password valid if (IsValidLogin(user_name, password)) { //jika username & password dikenali string user_id = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().m_user_id + ""; string Role = _context.m_user.Include(f => f.m_user_group).Where(f => f.user_name == user_name).FirstOrDefault().m_user_group.user_group_name; string user_category_id = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().m_user_group_id + ""; bool status_aktif = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().user_active; if (status_aktif != true) { //jika user tidak aktif arm.fail(); arm.message = "user tidak aktif"; } else { //jika user valid & aktif var claims = new[] { new Claim(ClaimTypes.Name, user_name), new Claim(ClaimTypes.Role, Role), new Claim("user_id", user_id), new Claim("user_category_id", user_category_id), new Claim("user_name", user_name), }; ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal); arm.success(); arm.message = "login berhasil"; } } else { arm.fail(); arm.message = "login gagal"; } } else { arm.fail(); arm.message = "login gagal"; } return new JsonResult(arm); } /// <summary> /// Handle pencocokan identity login di database /// </summary> /// <param name="user_name"></param> /// <param name="password"></param> /// <returns></returns> internal bool IsValidLogin(string user_name, string password) { bool hasil = false; try { string passInDB = _context.m_user.Where(u => u.user_name == user_name).FirstOrDefault().user_password; hasil = PasswordStorage.VerifyPassword(password, passInDB) ? true : false; } catch (Exception e) { Console.WriteLine(e); } return hasil; } /// <summary> /// Get all feature user has access to /// </summary> /// <param name="m_user_group_id"></param> /// <returns></returns> private string getFeatureMap(int m_user_group_id) { string result = ""; List<feature_map> feature_map_list; feature_map_list = _context.feature_map.Where(a => a.m_user_group_id == m_user_group_id).ToList(); result = Newtonsoft.Json.JsonConvert.SerializeObject(feature_map_list); Console.WriteLine(result); return result; } } }
using System.Runtime.Serialization; namespace EpisodeRenaming { [DataContract] public class TraktTvShow { [DataMember( Name = "title" )] public string Title { get; set; } [DataMember( Name = "overview" )] public string Overview { get; set; } [DataMember( Name = "year" )] public int? Year { get; set; } [DataMember( Name = "images" )] public TraktTvShowImages Images { get; set; } [DataMember( Name = "ids" )] public TraktTvShowIDs Ids { get; set; } } }
using AbiokaScrum.Api.Data; using AbiokaScrum.Api.Entities; using AbiokaScrum.Api.Exceptions; using AbiokaScrum.Api.Helper; using System; using System.Net; using System.Net.Http; using System.Web.Http; namespace AbiokaScrum.Api.Contollers { [RoutePrefix("api/Board")] public class BoardController : BaseRepositoryController<Board> { private readonly IBoardOperation boardOperation; private readonly IListOperation listOperation; public BoardController(IBoardOperation boardoperation, IListOperation listOperation) : base(boardoperation) { this.boardOperation = boardoperation; this.listOperation = listOperation; } public override HttpResponseMessage Get() { var result = boardOperation.GetAll(); return Request.CreateResponse(HttpStatusCode.OK, result); } public override HttpResponseMessage Get([FromUri] Guid id) { var result = boardOperation.Get(id); if (result == null) { throw new DenialException(HttpStatusCode.NotFound, ErrorMessage.NotFound); } return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] [Route("Add")] public override HttpResponseMessage Add(Board entity) { if (entity == null) { throw new ArgumentNullException("entity"); } boardOperation.Add(entity); var response = Request.CreateResponse(HttpStatusCode.Created, entity); response.Headers.Location = new Uri(Request.RequestUri, entity.Id.ToString()); return response; } [HttpGet] [Route("{boardId}/User")] public HttpResponseMessage GetUser([FromUri] Guid boardId) { var users = boardOperation.GetBoardUsers(boardId); var response = Request.CreateResponse(HttpStatusCode.Created, users); return response; } [HttpPost] [Route("{boardId}/User/{userId}")] public HttpResponseMessage AddUser([FromUri] Guid boardId, [FromUri]Guid userId) { var boardUser = boardOperation.AddUser(boardId, userId); return Request.CreateResponse(HttpStatusCode.Created, boardUser); } [HttpDelete] [Route("{boardId}/User/{userId}")] public HttpResponseMessage DeleteUser([FromUri] Guid boardId, [FromUri]Guid userId) { if (userId == CurrentUser.Id) { throw new DenialException(ErrorMessage.YouCannotRemoveYourselfFromBoard); } boardOperation.RemoveUser(boardId, userId); return Request.CreateResponse(HttpStatusCode.OK); } [HttpGet] [Route("{boardId}/List")] public HttpResponseMessage GetLists([FromUri] Guid boardId) { var result = listOperation.GetByBoardId(boardId); var response = Request.CreateResponse(HttpStatusCode.OK, result); return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DbConnector.Core.Extensions { public static class TypeExtensions { public static bool IsNumeric(this Type tType) { return (tType.IsPrimitive && !( tType == typeof(bool) || tType == typeof(char) || tType == typeof(IntPtr) || tType == typeof(UIntPtr))) || (tType == typeof(decimal)); } public static bool IsNullable(this Type tType) { return !tType.IsValueType || (Nullable.GetUnderlyingType(tType) != null); } public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute; if (att != null) { return valueSelector(att); } return default(TValue); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading.Tasks; using AltinnIntegrator.Functions.Config; using AltinnIntegrator.Functions.Models; using Azure.Storage.Queues; using Microsoft.Extensions.Options; namespace AltinnIntegrator.Functions.Services.Implementation { /// <summary> /// The queue service that handles actions related to the queue storage. /// </summary> [ExcludeFromCodeCoverage] public class QueueService : IQueueService { private readonly QueueStorageSettings _settings; private QueueClient _inboundQueueClient; private QueueClient _confirmationQueueClient; /// <summary> /// Initializes a new instance of the <see cref="QueueService"/> class. /// </summary> /// <param name="settings">The queue storage settings</param> public QueueService(IOptions<QueueStorageSettings> settings) { _settings = settings.Value; } /// <inheritdoc/> public async Task<PushQueueReceipt> PushToInboundQueue(string content) { if (!_settings.EnablePushToQueue) { return new PushQueueReceipt { Success = true }; } try { QueueClient client = await GetInboundQueueClient(); await client.SendMessageAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(content))); } catch (Exception e) { return new PushQueueReceipt { Success = false, Exception = e }; } return new PushQueueReceipt { Success = true }; } public async Task<PushQueueReceipt> PushToConfirmationQueue(string content) { if (!_settings.EnablePushToQueue) { return new PushQueueReceipt { Success = true }; } try { QueueClient client = await GetConfirmationQueueClient(); await client.SendMessageAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(content))); } catch (Exception e) { return new PushQueueReceipt { Success = false, Exception = e }; } return new PushQueueReceipt { Success = true }; } private async Task<QueueClient> GetInboundQueueClient() { if (_inboundQueueClient == null) { _inboundQueueClient = new QueueClient(_settings.ConnectionString, _settings.InboundQueueName); await _inboundQueueClient.CreateIfNotExistsAsync(); } return _inboundQueueClient; } private async Task<QueueClient> GetConfirmationQueueClient() { if (_confirmationQueueClient == null) { _confirmationQueueClient = new QueueClient(_settings.ConnectionString, _settings.ConfirmationQueueName); await _confirmationQueueClient.CreateIfNotExistsAsync(); } return _confirmationQueueClient; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlTypes; namespace SNORM { /// <summary>Represnts a column in a SQL table.</summary> public class SqlColumnInfo { #region Properties /// <summary>Gets or sets the name.</summary> public string Name { get; set; } /// <summary>Gets or sets the position of the column in the table (index).</summary> public int OrdinalPosition { get; set; } /// <summary>Gets or sets the default value.</summary> public object DefaultValue { get; set; } /// <summary>Gets or sets whether or not the column is nullable.</summary> public bool IsNullable { get; set; } /// <summary>Gets or sets the SQL type.</summary> public SqlDbType Type { get; set; } /// <summary>Gets or sets the length. Default is -1 as not all data types utilize a length.</summary> public int Length { get; set; } = -1; /// <summary>Gets or sets whether or not the column is auto incremented.</summary> public bool AutoIncrement { get; set; } /// <summary>Gets or sets the auto increment step.</summary> public int AutoIncrementStep { get; set; } /// <summary>Gets or sets the auto increment seep.</summary> public int AutoIncrementSeed { get; set; } /// <summary>Gets or sets whether or not the column is a primary key (or part of a multi-column primary key).</summary> public bool IsPrimaryKey { get; set; } /// <summary>Gets or sets the collection of foreign key information, if any or mulitple. Default is null.</summary> public List<ForeignKey> ForeignKeys { get; set; } /// <summary>Gets the .NET type based off the <see cref="Type"/>.</summary> public Type DotNetType { get { if (Type == SqlDbType.BigInt) return typeof(long); else if (Type == SqlDbType.Binary) return typeof(byte[]); else if (Type == SqlDbType.Bit) return typeof(bool); else if (Type == SqlDbType.Char) return typeof(string); else if (Type == SqlDbType.Date) return typeof(DateTime); else if (Type == SqlDbType.DateTime) return typeof(DateTime); else if (Type == SqlDbType.DateTime2) return typeof(DateTime); else if (Type == SqlDbType.DateTimeOffset) return typeof(DateTimeOffset); else if (Type == SqlDbType.Decimal) return typeof(decimal); else if (Type == SqlDbType.Float) return typeof(double); else if (Type == SqlDbType.Image) return typeof(byte[]); else if (Type == SqlDbType.Int) return typeof(int); else if (Type == SqlDbType.Money) return typeof(decimal); else if (Type == SqlDbType.NChar) return typeof(string); else if (Type == SqlDbType.NText) return typeof(string); else if (Type == SqlDbType.NVarChar) return typeof(string); else if (Type == SqlDbType.Real) return typeof(float); else if (Type == SqlDbType.SmallDateTime) return typeof(DateTime); else if (Type == SqlDbType.SmallInt) return typeof(short); else if (Type == SqlDbType.SmallMoney) return typeof(decimal); else if (Type == SqlDbType.Text) return typeof(string); else if (Type == SqlDbType.Time) return typeof(TimeSpan); else if (Type == SqlDbType.Timestamp) return typeof(byte[]); else if (Type == SqlDbType.TinyInt) return typeof(byte); else if (Type == SqlDbType.UniqueIdentifier) return typeof(Guid); else if (Type == SqlDbType.VarBinary) return typeof(byte[]); else if (Type == SqlDbType.VarChar) return typeof(string); else if (Type == SqlDbType.Xml) return typeof(SqlXml); else throw new NotSupportedException("The Type (SqlDbType) property could parsed into a .NET type."); } } #endregion #region Constructors /// <summary>Initializes a new instance of <see cref="SqlColumnInfo"/>.</summary> public SqlColumnInfo() { ForeignKeys = new List<ForeignKey>(); } #endregion } }