Пример #1
0
        public void Cleanup(SavedState s)
        {
            if (closureStackPosition > s.blockInitialClosureStackPosition)
            {
                bytecodes.Add(VirtualMachine.OpCodes.MakePOPCLOSED(closureStackPosition - s.blockInitialClosureStackPosition));
            }

            if (stackPosition != s.initialStackPosition)
            {
                bytecodes.Add(VirtualMachine.OpCodes.MakePOPSTACK(stackPosition - s.initialStackPosition));
            }
        }
Пример #2
0
        public void RestoreState(SavedState s)
        {
            Cleanup(s);

            if (closureStackPosition > s.blockInitialClosureStackPosition)
            {
                closureStackPosition = s.blockInitialClosureStackPosition;
                newClosedVars = s.oldClosedVars;
            }

            if (stackPosition != s.initialStackPosition)
            {
                stackPosition = s.initialStackPosition;
                stackVars = s.oldStackVars;
            }
        }
		protected override IParcelable OnSaveInstanceState ()
		{
			IParcelable superState = base.OnSaveInstanceState();

			// Create instance of custom BaseSavedState
			SavedState myState = new SavedState(superState);
			// Set the state's value with the class member that holds current setting value


			if(Dialog != null && mColorPickerView != null) {
				myState.currentColor = mColorPickerView.getColor();
			}
			else {
				myState.currentColor = 0;
			}

			return myState;
 		}
Пример #4
0
        public void Init()
        {
            Utils.Logger.Info("****HealthMonitor:Init()");
            // 1. Get the Current Parameter state from the AzureTable (in case this WebJob was unloaded and restarted)
            PersistedState = new SavedState().CreateOrOpenEx();

            m_dailyMarketOpenTimer = new System.Threading.Timer(OnDailyMarketOpenTimerCallBack);
            SetupNotRepeatingDailyMarketOpenTimer();

            m_dailyReportTimer = new System.Threading.Timer(SendDailySummaryReportEmail);
            SetupNotRepeatingDailyReportTimer();    // usually MarketOpenTimer re-set it, but if App is started intraday, this will set the timer

            // 2. Start Watcher Timers
            m_rtpsTimer = new System.Threading.Timer(OnRtpsTimerCallBack, null, TimeSpan.FromMinutes(0.6), TimeSpan.FromMinutes(cRtpsTimerFrequencyMinutes));
            #if DEBUG_LOCAL_DEVELOPMENT
            //OnRtpsTimerCallBack(null);
            //OnDailyMarketOpenTimerCallBack(null);
            #endif
        }
Пример #5
0
		public void Execute() {
			Debug.Assert(savedStates == null);
			if (savedStates != null)
				throw new InvalidOperationException();
			this.savedStates = new SavedState[this.nodes.Length];
			for (int i = 0; i < nodes.Length; i++) {
				var node = nodes[i];
				savedStates[i] = new SavedState();
				var savedState = savedStates[i];

				int index = node.TreeNode.Parent.Children.IndexOf(node.TreeNode);
				bool b = index >= 0;
				Debug.Assert(b);
				if (!b)
					throw new InvalidOperationException();
				savedState.ModuleNode = (IModuleFileNode)node.TreeNode.Children.First(a => a.Data is IModuleFileNode).Data;
				node.TreeNode.Children.Remove(savedState.ModuleNode.TreeNode);
				node.TreeNode.Parent.Children[index] = savedState.ModuleNode.TreeNode;

				var module = node.DnSpyFile.ModuleDef;
				b = module != null && module.Assembly != null &&
					module.Assembly.Modules.Count == 1 &&
					module.Assembly.ManifestModule == module;
				Debug.Assert(b);
				if (!b)
					throw new InvalidOperationException();
				node.TreeNode.EnsureChildrenLoaded();
				savedState.AssemblyDef = module.Assembly;
				module.Assembly.Modules.Remove(module);
				savedState.ModuleKind = module.Kind;
				ModuleUtils.WriteNewModuleKind(module, ModuleKind.NetModule, out savedState.Characteristics);
			}
		}
Пример #6
0
 public void SetGroupBoxState(GroupBox groupBox, SavedState state)
 {
     groupBox.Tag  = state;
     groupBox.Text = SetTextState(groupBox.Text, state);
 }
Пример #7
0
        /// <summary>
        /// Called when a groupBox has been individually reverted.
        /// </summary>
        private void SetGroupBoxIsSaved(GroupBox groupBox, Button confirmButton, Button revertToSavedButton,
                        SavedState otherGroupBox1State, SavedState otherGroupBox2State)
        {
            _fsf.SetGroupBoxState(groupBox, SavedState.saved);
            _fsf.SetSettingsAreSaved(this, M.HasError(_allTextBoxes), confirmButton, revertToSavedButton);

            if(otherGroupBox1State == SavedState.unconfirmed || otherGroupBox2State == SavedState.unconfirmed
                   || OtherFormStateIs(SavedState.unconfirmed))
            {
                SetMainFormIsUnconfirmed();
            }
            else if(otherGroupBox1State == SavedState.confirmed || otherGroupBox2State == SavedState.confirmed
                || OtherFormStateIs(SavedState.confirmed))
            {
                SetMainFormIsConfirmed();
            }
            else
            {
                SetMainFormIsSaved();
            }
        }
Пример #8
0
 private bool ThereArePalettesOfType(SavedState state)
 {
     bool rval = false;
     foreach(PaletteForm paletteForm in this.PalettesListBox.Items)
     {
         if(((SavedState)paletteForm.Tag == state)
         || (paletteForm.OrnamentsForm != null && ((SavedState)paletteForm.OrnamentsForm.Tag == state)))
         {
             rval = true;
             break;
         }
     }
     return rval;
 }
		protected override IParcelable OnSaveInstanceState()
		{
			IParcelable superState = base.OnSaveInstanceState();

			SavedState ss = new SavedState(superState)
			{
				Settings = Settings,
				YOffset = MaterialViewPagerHelper.GetAnimator(Context).LastYOffset
			};
			//end

			return ss;
		}
Пример #10
0
 public Utf32Reader(IByteReader stream, bool bigEndian, bool errorThrow)
 {
     this.stream = stream;
     this.bigEndian = bigEndian;
     this.state = new SavedState();
     this.errorThrow = errorThrow;
 }
Пример #11
0
    public void SaveToFile(SavedState state)
    {
        string serialized = JsonConvert.SerializeObject(state);

        File.WriteAllText(filePath, serialized);
    }
Пример #12
0
    public bool isDifferentTo(SavedState otherState, Object2PropertiesMapping o2m)
    {
        bool changed = false;

        if (!changed && isActive != otherState.isActive)
            changed = true;

        if (o2m.isParentObj && o2m.getGameObject().transform.parent != null) {
            if (!changed && position.isDifferentTo(otherState.position) )
                changed = true;

            if (!changed && rotation.isDifferentTo(otherState.rotation) )
                changed = true;
        }

        if (!changed && localPosition.isDifferentTo( otherState.localPosition) )
            changed = true;

        if (!changed && localRotation.isDifferentTo( otherState.localRotation) )
            changed = true;

        if (!changed && emittingParticles != otherState.emittingParticles)
            changed = true;

        return changed;
    }
Пример #13
0
 public void ReloadState(SavedState savedState)
 {
     MvxTrace.Trace("ReloadState called with {0}",
                    savedState.PlayerId);
     _playerId = savedState.PlayerId;
 }
Пример #14
0
 /// <summary>
 /// Tries to save the state.
 /// </summary>
 private void TrySaveState(LoanContext state)
 {
     lock (applicationSaveStateLock) {
         try {
             string savegameFilename = Path.Combine (Application.persistentDataPath, SaveStateFilename);
             SavedState saveState = new SavedState ();
             saveState.SavedDate = DateTime.Now;
             saveState.Context = state;
             BinaryFormatter formatter = new BinaryFormatter ();
             using (FileStream fs = File.Open (savegameFilename, FileMode.OpenOrCreate)) {
                 fs.SetLength (0);
                 formatter.Serialize (fs, saveState);
                 fs.Close ();
             }
         } catch (Exception ex) {
             MessagePanelController.SetMessage (string.Format ("Failed to save state: {0}", ex.Message));
             MessagePanelController.ShowMessagePanel ();
         }
     }
 }
 public void ApplyStateEarly(SavedState state)
 {
 }
Пример #16
0
 public void SaveState(SavedState state)
 {
     state.Seed = seed;
 }
Пример #17
0
		ConvertNetModuleToAssemblyCommand(DocumentTreeNodeData[] nodes) {
			this.nodes = nodes.Cast<ModuleDocumentNode>().ToArray();
			savedStates = new SavedState[this.nodes.Length];
			for (int i = 0; i < savedStates.Length; i++)
				savedStates[i] = new SavedState();
		}
Пример #18
0
 public void SetState(SavedState _savedState)// string[] _imgList, TaskState _stateTask)
 {
     m_originator.SetState(_savedState);
     m_carTaker.Add(m_originator.SaveToMemento());
 }
		/// <summary>
		/// Hook allowing a view to generate a representation of its internal state
		/// that can later be used to create a new instance with that same state.
		/// </summary>
		/// <returns>
		/// To be added.
		/// </returns>
		/// <since version="Added in API level 1" />
		///   <altmember cref="M:Android.Views.View.OnRestoreInstanceState(Android.OS.IParcelable)" />
		///   <altmember cref="P:Android.Views.View.SaveEnabled" />
		/// <remarks>
		///   <para tool="javadoc-to-mdoc">Hook allowing a view to generate a representation of its internal state
		/// that can later be used to create a new instance with that same state.
		/// This state should only contain information that is not persistent or can
		/// not be reconstructed later. For example, you will never store your
		/// current position on screen because that will be computed again when a
		/// new instance of the view is placed in its view hierarchy.
		///   </para>
		///   <para tool="javadoc-to-mdoc">
		/// Some examples of things you may store here: the current cursor position
		/// in a text view (but usually not the text itself since that is stored in a
		/// content provider or other persistent storage), the currently selected
		/// item in a list view.</para>
		///   <para tool="javadoc-to-mdoc">
		///   <format type="text/html">
		///   <a href="http://developer.android.com/reference/android/view/View.html#onSaveInstanceState()" target="_blank">[Android Documentation]</a>
		///   </format>
		///   </para>
		/// </remarks>
		protected override IParcelable OnSaveInstanceState()
		{
			IParcelable superState = base.OnSaveInstanceState();
			SavedState savedState = new SavedState(superState) { CurrentPosition = _currentPosition };
			return savedState;
		}
Пример #20
0
 public void RestoreToMemento(Memento _m)
 {
     m_state = _m.GetSavedState();
 }
Пример #21
0
 public void SaveState()
 {
     saveData = new SavedState();
     saveData.SetData(circlesList, countFirstTeam, countSecondTeam, tempTime, time, spawning);
     PlayerPrefs.SetString("state", JsonUtility.ToJson(saveData));
 }
Пример #22
0
 public void Execute()
 {
     Debug.Assert(savedStates == null);
     if (savedStates != null)
         throw new InvalidOperationException();
     this.savedStates = new SavedState[this.nodes.Length];
     for (int i = 0; i < nodes.Length; i++) {
         var node = nodes[i];
         savedStates[i] = new SavedState();
         var savedState = savedStates[i];
         var module = node.LoadedAssembly.ModuleDefinition;
         bool b = module != null && module.Assembly != null &&
                 module.Assembly.Modules.Count == 1 &&
                 module.Assembly.ManifestModule == module;
         Debug.Assert(b);
         if (!b)
             throw new InvalidOperationException();
         node.EnsureChildrenFiltered();
         savedState.AssemblyDef = module.Assembly;
         module.Assembly.Modules.Remove(module);
         savedState.ModuleKind = module.Kind;
         ModuleUtils.WriteNewModuleKind(module, ModuleKind.NetModule, out savedState.Characteristics);
         savedState.ModuleNode = node.OnConvertedToNetModule();
     }
 }
Пример #23
0
 private bool OtherFormStateIs(SavedState state)
 {
     bool rval = false;
     if((SavedState)_dimensionsAndMetadataForm.Tag == state)
         rval = true;
     else
     {
         foreach(PaletteForm paletteForm in PalettesListBox.Items)
         {
             if(((SavedState)paletteForm.Tag == state)
             || (paletteForm.OrnamentsForm != null && (SavedState)paletteForm.OrnamentsForm.Tag == state))
             {
                 rval = true;
                 break;
             }
         }
     }
     return rval;
 }
Пример #24
0
 public void SaveState(SavedState state)
 {
     state.RemainingTurnTime = remainingTime;
 }
Пример #25
0
 public Utf8Reader(IByteReader stream, bool errorThrow)
 {
     this.stream = stream;
     this.lastChar = -1;
     this.state = new SavedState();
     this.errorThrow = errorThrow;
 }
Пример #26
0
        internal override IEnumerable <ParseStep> Parse(IRegexEngine engine)
        {
            yield return(ParseStep.BeginParse(this, engine.State));

            var        savedStates = new Stack <SavedState>();
            SavedState savedState  = null;

            // Attempt the regex at every location in the input, starting at the beginning and going until just past the last position.
            while (engine.State.Index <= engine.Input.Length)
            {
                var   initialState      = engine.State;
                var   matchSuccess      = true;
                State failedState       = null;
                var   skipAdvanceOnFail = false;

                // For this location in the input, try every child node.
                for (var item = savedState == null ? Children.First : savedState.Item; item != null;)
                {
                    var node = item.Value;
                    var nodeResultEnumerator = savedState == null?node.Parse(engine).GetEnumerator() : savedState.Enumerator;

                    savedState = null;

                    var nodeSuccess = false;

                    // Get all the reported results from this child node.
                    while (nodeResultEnumerator.MoveNext())
                    {
                        var result = nodeResultEnumerator.Current;

                        if (result.Type == ParseStepType.StateSaved)
                        {
                            // If decendent said it's saved its state - we need to do the same.
                            var state = new SavedState(nodeResultEnumerator, item, result.CurrentState);
                            engine.AddSavedState(state);
                            savedStates.Push(state);
                        }

                        if (ReferenceEquals(node, result.Node)) // We only pay attention to our children's results
                        {
                            if (result.Type == ParseStepType.Pass)
                            {
                                // If our child told us it was successful, note it.
                                nodeSuccess = true;
                            }
                            else if (result.Type == ParseStepType.Break)
                            {
                                // If our child told us to break, do so. (this indicates that the child was done, regardless of success or failure
                                break;
                            }
                            else if (result.Type == ParseStepType.Fail)
                            {
                                failedState       = result.CurrentState;
                                skipAdvanceOnFail = result.SkipAdvanceOnFail;
                            }
                        }

                        // Pass our children's results up.
                        yield return(result);
                    }

                    if (!nodeSuccess)
                    {
                        if (savedStates.Count > 0)
                        {
                            // If our child told us that it backtracked, begin backtracking.
                            savedState = savedStates.Pop();
                            foreach (var capture in savedState.PopCaptures(engine))
                            {
                                yield return(ParseStep.CaptureDiscarded(savedState.Item.Value, capture.Value, capture.Number));
                            }
                            item = savedState.Item;
                        }
                        else
                        {
                            // If we're here, we either ran out of saved states, or didn't have any to begin with. Our current
                            // node had no way of passing, so we'll fail at this index location in the input string.
                            matchSuccess = false;
                            break;
                        }
                    }
                    else
                    {
                        item = item.Next;
                    }
                }

                if (matchSuccess)
                {
                    // Yay! We've matched the whole group!
                    // However, we want to know if we're yielding an actual 'Match' - if we are, we need to clear our saved states.
                    bool isMatch = false;
                    foreach (var successStep in GetSuccessParseStep(engine, initialState))
                    {
                        if (successStep.Type == ParseStepType.Match)
                        {
                            isMatch = true;
                        }

                        yield return(successStep);
                    }

                    if (isMatch)
                    {
                        savedStates.Clear();
                    }

                    // ...but if we're here, our enumerator has been started up again, indicating that we're backtracking. Oblige.
                    if (savedStates.Count > 0)
                    {
                        // If our child told us that it backtracked, begin backtracking.
                        savedState = savedStates.Pop();
                        foreach (var capture in savedState.PopCaptures(engine))
                        {
                            yield return(ParseStep.CaptureDiscarded(savedState.Item.Value, capture.Value, capture.Number));
                        }
                        engine.State = savedState.CurrentState;
                    }
                }
                else
                {
                    // We failed at this index location. Advance the engine and start all over again.
                    Debug.Assert(failedState != null);
                    foreach (var failStep in GetFailParseSteps(engine, initialState, failedState, skipAdvanceOnFail))
                    {
                        yield return(failStep);
                    }
                }
            }

            // We always get here, regardless of success or failure.
            foreach (var endOfStringStep in GetEndOfStringSteps(engine))
            {
                yield return(endOfStringStep);
            }
        }
Пример #27
0
 public void ApplyStateLate(SavedState state)
 {
 }
Пример #28
0
        internal override IEnumerable<ParseStep> Parse(IRegexEngine engine)
        {
            yield return ParseStep.BeginParse(this, engine.State);

            var savedStates = new Stack<SavedState>();
            SavedState savedState = null;

            // Attempt the regex at every location in the input, starting at the beginning and going until just past the last position.
            while (engine.State.Index <= engine.Input.Length)
            {
                var initialState = engine.State;
                var matchSuccess = true;
                State failedState = null;
                var skipAdvanceOnFail = false;

                // For this location in the input, try every child node.
                for (var item = savedState == null ? Children.First : savedState.Item; item != null;)
                {
                    var node = item.Value;
                    var nodeResultEnumerator = savedState == null ? node.Parse(engine).GetEnumerator() : savedState.Enumerator;
                    savedState = null;

                    var nodeSuccess = false;

                    // Get all the reported results from this child node.
                    while (nodeResultEnumerator.MoveNext())
                    {
                        var result = nodeResultEnumerator.Current;

                        if (result.Type == ParseStepType.StateSaved)
                        {
                            // If decendent said it's saved its state - we need to do the same.
                            var state = new SavedState(nodeResultEnumerator, item, result.CurrentState);
                            engine.AddSavedState(state);
                            savedStates.Push(state);
                        }

                        if (ReferenceEquals(node, result.Node)) // We only pay attention to our children's results
                        {
                            if (result.Type == ParseStepType.Pass)
                            {
                                // If our child told us it was successful, note it.
                                nodeSuccess = true;
                            }
                            else if (result.Type == ParseStepType.Break)
                            {
                                // If our child told us to break, do so. (this indicates that the child was done, regardless of success or failure
                                break;
                            }
                            else if (result.Type == ParseStepType.Fail)
                            {
                                failedState = result.CurrentState;
                                skipAdvanceOnFail = result.SkipAdvanceOnFail;
                            }
                        }

                        // Pass our children's results up.
                        yield return result;
                    }

                    if (!nodeSuccess)
                    {
                        if (savedStates.Count > 0)
                        {
                            // If our child told us that it backtracked, begin backtracking.
                            savedState = savedStates.Pop();
                            foreach (var capture in savedState.PopCaptures(engine))
                            {
                                yield return ParseStep.CaptureDiscarded(savedState.Item.Value, capture.Value, capture.Number);
                            }
                            item = savedState.Item;
                        }
                        else
                        {
                            // If we're here, we either ran out of saved states, or didn't have any to begin with. Our current
                            // node had no way of passing, so we'll fail at this index location in the input string.
                            matchSuccess = false;
                            break;
                        }
                    }
                    else
                    {
                        item = item.Next;
                    }
                }

                if (matchSuccess)
                {
                    // Yay! We've matched the whole group!
                    // However, we want to know if we're yielding an actual 'Match' - if we are, we need to clear our saved states.
                    bool isMatch = false;
                    foreach (var successStep in GetSuccessParseStep(engine, initialState))
                    {
                        if (successStep.Type == ParseStepType.Match)
                        {
                            isMatch = true;
                        }

                        yield return successStep;
                    }

                    if (isMatch)
                    {
                        savedStates.Clear();
                    }

                    // ...but if we're here, our enumerator has been started up again, indicating that we're backtracking. Oblige.
                    if (savedStates.Count > 0)
                    {
                        // If our child told us that it backtracked, begin backtracking.
                        savedState = savedStates.Pop();
                        foreach (var capture in savedState.PopCaptures(engine))
                        {
                            yield return ParseStep.CaptureDiscarded(savedState.Item.Value, capture.Value, capture.Number);
                        }
                        engine.State = savedState.CurrentState;
                    }
                }
                else
                {
                    // We failed at this index location. Advance the engine and start all over again.
                    Debug.Assert(failedState != null);
                    foreach (var failStep in GetFailParseSteps(engine, initialState, failedState, skipAdvanceOnFail))
                    {
                        yield return failStep;
                    }
                }
            }

            // We always get here, regardless of success or failure.
            foreach (var endOfStringStep in GetEndOfStringSteps(engine))
            {
                yield return endOfStringStep;
            }
        }
Пример #29
0
    //executed before each replay
    public void prepareObjectForReplay()
    {
        //spawn super object which gets all replay manager objects as children
        GameObject superParent = GameObject.Find(EZReplayManager.S_PARENT_NAME);

        //create super parent if has not happened. The super parent keeps the scene clean
        if (superParent == null)
        {
            superParent = new GameObject(EZReplayManager.S_PARENT_NAME);
            superParent.transform.position   = Vector3.zero;
            superParent.transform.rotation   = Quaternion.identity;
            superParent.transform.localScale = Vector3.one;
        }

        if (isParentObj)           //if is a parent gameObject mapping

        {
            if (prefabLoadPath == "")
            {
                gameObjectClone = (GameObject)GameObject.Instantiate(gameObject, gameObject.transform.position, gameObject.transform.rotation);
            }
            else
            {
                gameObjectClone = (GameObject)GameObject.Instantiate(Resources.Load(prefabLoadPath));
            }

            gameObjectClone.transform.parent = superParent.transform;
        }
        else             // if is a child (can also be a parent in game scene hierachy but "EZReplayManager.mark4recording()" has not been called for this object specifically, so we handle it as a child

        {
            GameObject  myParentClone = parentMapping.getGameObjectClone();
            Transform[] allChildren   = myParentClone.GetComponentsInChildren <Transform>(true);

            for (int i = 0; i < allChildren.Length; i++)
            {
                GameObject child = allChildren[i].gameObject;
                //map child to order number or go-name
                if ((childIdentificationMode == ChildIdentificationMode.IDENTIFY_BY_ORDER && i == childNo) ||
                    (childIdentificationMode == ChildIdentificationMode.IDENTIFY_BY_NAME && gameObjectName == child.name))
                {
                    gameObjectClone = child;
                    break;
                }
            }

            if (gameObjectClone == null)               //child was destroyed along the way while recording
            {
                if (EZReplayManager.get.precacheGameobjects)
                {
                    gameObjectClone = (GameObject)GameObject.Instantiate(Resources.Load(EZReplayManager.get.generateCachePath(gameObjectName, "")));
                }
            }
        }

        gameObjectClone.name = gameObjectInstanceID + "_" + gameObjectClone.GetInstanceID() + "_" + gameObjectClone.name;

        if (gameObjectInstanceID > -1)         // can happen when file was loaded. obviously this doesn't work with loaded files yet.
        {
            EZReplayManager.get.instanceIDtoGO.Add(gameObjectInstanceID, gameObject);
        }

        // kill all unneccessary scripts on gameObjectClone
        Component[] allComps = gameObjectClone.GetComponentsInChildren <Component>(true);

        List <Component> componentsToKill = new List <Component>();

        foreach (Component comp in allComps)
        {
            //Exclude scripts and components from removal: (this is done to preserve basic functionality and renderers)
            if (comp != comp.GetComponent <Transform>() &&
                comp != comp.GetComponent <MeshFilter>() &&
                comp != comp.GetComponent <MeshRenderer>() &&
                comp != comp.GetComponent <SkinnedMeshRenderer>() &&
                comp != comp.GetComponent <ParticleEmitter>() &&
                comp != comp.GetComponent <ParticleAnimator>() &&
                comp != comp.GetComponent <ParticleRenderer>() &&
                comp != comp.GetComponent <Camera>() &&
                comp != comp.GetComponent <GUILayer>() &&
                comp != comp.GetComponent <AudioListener>() &&
                comp != comp.GetComponent("FlareLayer")
                )
            {
                bool found = false;
                // take exceptions from public array "EZReplayManager.componentsAndScriptsToKeepAtReplay"
                for (int i = 0; i < EZReplayManager.get.componentsAndScriptsToKeepAtReplay.Count; i++)
                {
                    if (comp == comp.GetComponent(EZReplayManager.get.componentsAndScriptsToKeepAtReplay[i]))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    componentsToKill.Add(comp);
                }
            }
        }
        //uses multiple cycles to kill components which are required by others
        int cycles = 0;

        do
        {
            List <Component> componentsToKillNew = componentsToKill;
            for (int i = 0; i < componentsToKill.Count; i++)
            {
                Component comp = componentsToKill[i];

                try {
                    GameObject.DestroyImmediate(comp);
                } finally {
                    if (comp == null)
                    {
                        componentsToKillNew.RemoveAt(i);
                    }
                    else                         //change order
                    {
                        componentsToKillNew.Remove(comp);
                        componentsToKillNew.Add(comp);
                    }
                }
            }

            componentsToKill = componentsToKillNew;
            cycles++;
        } while (componentsToKill.Count > 0 && cycles <= 10);

        EZR_Clone thisCloneScript = gameObjectClone.AddComponent <EZR_Clone>();

        thisCloneScript.origInstanceID  = gameObjectInstanceID;
        thisCloneScript.cloneInstanceID = gameObjectClone.GetInstanceID();

        if (EZReplayManager.get.autoDeactivateLiveObjectsOnReplay && gameObject != null)
        {
            /*if (gameObject.rigidbody) { //if needed, please do this yourself (i.e. via callback __EZR_replay_prepare)
             *      gameObject.rigidbody.Sleep();
             * }*/

            gameObject.SetActive(false);
        }

        SavedState mostRecent = null;

        for (int i = firstChangedFrame; i <= lastChangedFrame; i++)
        {
            if (savedStates.ContainsKey(i))
            {
                mostRecent = savedStates[i];
            }
            else
            {
                savedStates.Add(i, mostRecent);
            }
        }
    }
Пример #30
0
        /// <summary>
        /// Called when one of the groupBox Confirm buttons is clicked.
        /// </summary>
        private void SetGroupBoxIsConfirmed(GroupBox groupBox, Button confirmGroupBoxButton,
            SavedState otherGroupBox1State, SavedState otherGroupBox2State)
        {
            _fsf.SetGroupBoxState(groupBox, SavedState.confirmed);
            _fsf.SetSettingsAreConfirmed(this, M.HasError(_allTextBoxes), confirmGroupBoxButton);

            NotationGroupBox.Enabled = true;
            KrystalsGroupBox.Enabled = true;
            PalettesGroupBox.Enabled = true;

            if(otherGroupBox1State == SavedState.unconfirmed
            || otherGroupBox2State == SavedState.unconfirmed
            || OtherFormStateIs(SavedState.unconfirmed))
                SetMainFormIsUnconfirmed();
            else
                SetMainFormIsConfirmed();
        }
Пример #31
0
 public void ReloadState(SavedState savedState)
 {
     MvxTrace.Trace("ReloadState called with {0}",
                    savedState.JourneyId);
     _journeyId = savedState.JourneyId;
 }
Пример #32
0
        private void SetMainFormSaveCreateRevertButtons(SavedState state)
        {
            SetMainFormSaveCreateButtonText(_fsf.UnconfirmedFormsExist() || _fsf.ConfirmedFormsExist());

            SaveSettingsCreateScoreButton.Enabled = !(state == SavedState.unconfirmed);
            RevertEverythingButton.Enabled = (_fsf.UnconfirmedFormsExist() || _fsf.ConfirmedFormsExist());
        }
    // insert a new state at certain position
    public void insertStateAtPos(int recorderPosition)
    {
        SavedState newState = new SavedState(gameObject);
        bool insertFrame = true;
        if (lastChangedFrame > -1) {

            if (savedStates.ContainsKey(lastChangedFrame) && !newState.isDifferentTo(savedStates[lastChangedFrame])) {

                insertFrame = false;
            }
        }
        try {
            if (insertFrame) {

                savedStates.Add(recorderPosition,newState);

                lastChangedFrame = recorderPosition;

                if (firstChangedFrame == -1)
                    firstChangedFrame = recorderPosition;
            }
        } catch {
            if (EZReplayManager.showErrors)
                MonoBehaviour.print("EZReplayManager ERROR: You probably already inserted at position '"+recorderPosition+"' for game object '"+gameObject+"'.");
        }
    }
 public void ReloadState(SavedState savedState)
 {
     Name = savedState.Name;
 }
Пример #35
0
 public override State?SavedAchievementState(string key) =>
 SavedState.TryGetValue(key, out var s) ? s : (State?)null;
 public void ReloadState(SavedState savedState)
 {
     MvxTrace.Trace("ReloadState called with {0}",
                    savedState.BeneficiaryId);
     _beneficiaryId = savedState.BeneficiaryId;
 }
 public void ReloadState(SavedState savedState)
 {
     MvxTrace.Trace("ReloadState called with {0}",
                    savedState.RemittanceId);
     _remittanceId = savedState.RemittanceId;
 }
 protected override IParcelable OnSaveInstanceState ()
 {
     var superState = base.OnSaveInstanceState ();
     var savedState = new SavedState(superState)
     {
         CurrentPage = mCurrentPage
     };
     return savedState;
 }
		public override IParcelable OnSaveInstanceState ()
		{
			IParcelable superState = base.OnSaveInstanceState();
			SavedState savedState = new SavedState(superState);
			savedState.mProgress = mProgress;

			return base.OnSaveInstanceState ();
		}
Пример #40
0
 public void SetState(SavedState _state)
 {
     m_state = _state;
 }
Пример #41
0
        private void Save()
        {
            SavedState state = new SavedState(this);

            m_SaveManager.Save(_graphfileextensions, state, state.getName());
        }
Пример #42
0
    public bool isDifferentTo(SavedState otherState)
    {
        bool changed = false;

        if (!changed && isActive != otherState.isActive)
            changed = true;

        /*if (!changed && position.isDifferentTo(otherState.position) )
            changed = true;

        if (!changed && rotation.isDifferentTo(otherState.rotation) )
            changed = true;*/

        if (!changed && localPosition.isDifferentTo( otherState.localPosition) )
            changed = true;

        if (!changed && localRotation.isDifferentTo( otherState.localRotation) )
            changed = true;

        if (!changed && emittingParticles != otherState.emittingParticles)
            changed = true;

        /**********************************************************************
         *  New Addition
         **********************************************************************/
        if (!changed && isMainCameraChild != otherState.isMainCameraChild)
        {

            changed = true;
        }
        if (!changed && tag != otherState.tag)
        {

            changed = true;
        }
        if (!changed && convoTitle != otherState.convoTitle)
        {

            changed = true;
        }
        if (!changed && dialogueNum != otherState.dialogueNum)
        {

            changed = true;
        }
        if (!changed && dialogueType != otherState.dialogueType)
        {

            changed = true;
        }
        //*********************************************************************

        return changed;
    }
Пример #43
0
 public Utf32Reader(IByteReader stream, bool bigEndian, bool errorThrow) {
   this.stream = stream;
   this.bigEndian = bigEndian;
   this.state = new SavedState();
   this.errorThrow = errorThrow;
 }
Пример #44
0
 protected override IParcelable OnSaveInstanceState()
 {
     var superState = base.OnSaveInstanceState();
     var savedState = new SavedState(superState, _viewAbove.GetCurrentItem());
     return savedState;
 }
Пример #45
0
 public Utf8Reader(IByteReader stream, bool errorThrow) {
   this.stream = stream;
   this.lastChar = -1;
   this.state = new SavedState();
   this.errorThrow = errorThrow;
 }
Пример #46
0
 public override object Read(ES2Reader reader)
 {
     SavedState data = new SavedState();
     Read(reader, data);
     return data;
 }
 public override void SetInitialSavedState(SavedState state)
 {
     // Prevent set saved state
 }
Пример #48
0
 /* (non-Javadoc)
  * @see android.view.View#onSaveInstanceState()
  */
 //@Override
 protected override IParcelable OnSaveInstanceState()
 {
     IParcelable superState = base.OnSaveInstanceState();
     SavedState ss = new SavedState(superState, mViewAbove.getCurrentItem());
     return ss;
 }
Пример #49
0
        /// <summary>
        /// Open session window
        /// </summary>
        public void OpenSessionWindow()
        {
            if (_group == null || _group.Length < 1 ||
                _indiv == null || _indiv.Length < 1 ||
                _eval == null || _eval.Length < 1 ||
                _cond == null || _cond.Length < 1 ||
                _keys == null || _keys.Length < 1 ||
                _sessionNumber == null || _sessionNumber.Length < 1 ||
                _ther == null || _ther.Length < 1 ||
                _collect == null || _collect.Length < 1 ||
                _dataRole == null || _dataRole.Length < 1 ||
                _sessionTime == null || _sessionTime.Length < 1)
            {
                return;
            }

            int session;

            if (!int.TryParse(_sessionNumber, out session))
            {
                return;
            }

            try
            {
                string savedStatePath = Path.Combine(Properties.Settings.Default.SaveLocation, "SavedState.json");
                var    savedState     = new SavedState();
                savedState.Group         = _group;
                savedState.Individual    = _indiv;
                savedState.Evaluation    = _eval;
                savedState.Condition     = _cond;
                savedState.KeySet        = _keys;
                savedState.Therapist     = _ther;
                savedState.DataCollector = _collect;
                savedState.Role          = _dataRole;
                savedState.Duration      = _sessionTime;

                string json = JsonConvert.SerializeObject(savedState);
                File.WriteAllText(savedStatePath, json);
            }
            catch { }

            var window = new SessionWindow("Recording Session: Session #" + SessionNumber);

            window.GroupName      = _group;
            window.PatientName    = _indiv;
            window.EvaluationName = _eval;
            window.ConditionName  = _cond;
            window.KeyboardName   = _keys + ".json";
            window.SessionCount   = session;
            window.TherapistName  = _ther;
            window.CollectorName  = _collect;
            window.CollectorRole  = _dataRole;
            window.SetKeys(keyboardListViewModel.keyboardSelection);
            window.SessionTime = GetSessionLength(_sessionTime);

            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            window.ShowDialog();

            var kbWindow = new ResultsWindow();

            kbWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            kbWindow.mFrequencyColumns = window.GetFrequencyKeys();
            kbWindow.mDurationColumns  = window.GetDurationKeys();

            kbWindow.mainFreqCounts  = window.GetMainFrequencyCounts();
            kbWindow.mainFreqMinutes = window.GetMainFrequencyTotals();
            kbWindow.mainFreqRPM     = window.GetMainFrequencyRPM();

            kbWindow.mainDurCounts  = window.GetMainDurationTime();
            kbWindow.mainDurMinutes = window.GetMainDurationTotalTime();
            kbWindow.mainDurPercent = window.GetMainDurationPercentageSession();

            kbWindow.schOneFreqCounts  = window.GetSchOneFrequencyCounts();
            kbWindow.schOneFreqMinutes = window.GetSchOneFrequencyTotals();
            kbWindow.schOneFreqRPM     = window.GetSchOneFrequencyRPM();

            kbWindow.schOneDurCounts  = window.GetSchOneDurationTime();
            kbWindow.schOneDurMinutes = window.GetSchOneDurationTotalTime();
            kbWindow.schOneDurPercent = window.GetSchOneDurationPercentageSession();

            kbWindow.schTwoFreqCounts  = window.GetSchTwoFrequencyCounts();
            kbWindow.schTwoFreqMinutes = window.GetSchTwoFrequencyTotals();
            kbWindow.schTwoFreqRPM     = window.GetSchTwoFrequencyRPM();

            kbWindow.schTwoDurCounts  = window.GetSchTwoDurationTime();
            kbWindow.schTwoDurMinutes = window.GetSchTwoDurationTotalTime();
            kbWindow.schTwoDurPercent = window.GetSchTwoDurationPercentageSession();

            kbWindow.schThreeFreqCounts  = window.GetSchThreeFrequencyCounts();
            kbWindow.schThreeFreqMinutes = window.GetSchThreeFrequencyTotals();
            kbWindow.schThreeFreqRPM     = window.GetSchThreeFrequencyRPM();

            kbWindow.schThreeDurCounts  = window.GetSchThreeDurationTime();
            kbWindow.schThreeDurMinutes = window.GetSchThreeDurationTotalTime();
            kbWindow.schThreeDurPercent = window.GetSchThreeDurationPercentageSession();

            kbWindow.ShowDialog();

            if (kbWindow.SaveData && window.stopWatch.Elapsed.TotalSeconds > 0)
            {
                XSSFWorkbook hssfworkbook = new XSSFWorkbook();

                try
                {
                    ISheet page = hssfworkbook.CreateSheet("Cover Page");
                    window.WriteResults(page, window.freqIntervalListMain, window.stopWatch, window.durationIntervalListMain, window.mMultiScheds[0], true, 0);

                    page = hssfworkbook.CreateSheet("Schedule 1 Only");
                    window.WriteResults(page, window.freqIntervalListSchOne, window.scheduleOne, window.durationIntervalListSchOne, window.mMultiScheds[1], false, 1);
                    page = hssfworkbook.CreateSheet("Schedule 2 Only");
                    window.WriteResults(page, window.freqIntervalListSchTwo, window.scheduleTwo, window.durationIntervalListSchTwo, window.mMultiScheds[2], false, 2);
                    page = hssfworkbook.CreateSheet("Schedule 3 Only");
                    window.WriteResults(page, window.freqIntervalListSchThree, window.scheduleThree, window.durationIntervalListSchThree, window.mMultiScheds[3], false, 3);

                    page = hssfworkbook.CreateSheet("FrequencyIntervals");
                    window.WriteFreqIntervalResults(page, window.keyFrequency, window.mKeyboards.frequencyKeys, window.freqIntervalListMain);

                    page = hssfworkbook.CreateSheet("DurationIntervals");
                    window.WriteDurIntervalResults(page, window.keyDuration, window.mKeyboards.durationKeys, window.durationIntervalListMain);

                    var task = new Task <bool>(() =>
                    {
                        var targetDir = Path.Combine(Properties.Settings.Default.SaveLocation, window.GroupName, window.PatientName, window.EvaluationName, window.ConditionName);
                        var di        = new DirectoryInfo(targetDir);
                        return(di.Exists);
                    });
                    task.Start();

                    bool resp = task.Wait(100) && task.Result;

                    if (resp)
                    {
                        var targetFile = Path.Combine(Properties.Settings.Default.SaveLocation,
                                                      window.GroupName,
                                                      window.PatientName,
                                                      window.EvaluationName,
                                                      window.ConditionName,
                                                      "Session_" + window.SessionCount + "_" + window.CollectorRole + ".xlsx");

                        using (FileStream file = new FileStream(targetFile, FileMode.Create))
                        {
                            hssfworkbook.Write(file);
                        }
                    }
                    else
                    {
                        var targetFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                      "DataTracker",
                                                      window.GroupName,
                                                      window.PatientName,
                                                      window.EvaluationName,
                                                      window.ConditionName,
                                                      "Session_" + window.SessionCount + "_" + window.CollectorRole + ".xlsx");

                        using (FileStream file = new FileStream(targetFile, FileMode.Create))
                        {
                            hssfworkbook.Write(file);
                        }

                        MessageBox.Show("Saved to local location!");
                    }
                }
                catch (IOException e2)
                {
                    Console.WriteLine(e2.ToString());
                }
            }

            CountSessions();
        }
 //@Override
 protected override IParcelable OnSaveInstanceState()
 {
     IParcelable superState = base.OnSaveInstanceState();
     SavedState savedState = new SavedState(superState);
     savedState.currentPage = mCurrentPage;
     return savedState;
 }
Пример #51
0
    public static void Load()
    {
        if (ES2.Exists("PVState"))
        {
            SavedState loaded = ES2.Load <SavedState> ("PVState");

            GameControl.Level = loaded.Level;

            gameControl.BeginGame(true);

            int[][] positions = new int[loaded.ObstacleXPositions.Count][];
            for (int i = 0; i < loaded.ObstacleXPositions.Count; i++)
            {
                positions[i] = new int[] { loaded.ObstacleXPositions[i], loaded.ObstacleYPositions[i] };
                AddObstacle(loaded.ObstacleXPositions[i], loaded.ObstacleYPositions[i]);
            }
            obstacleLibrary.LoadObstaclesFromState(loaded.ObstacleLevelType, positions);

            foreach (LibraryCard lc in loaded.CardsInHand)
            {
                Card card = gameControl.Create(lc.CardName);
                gameControl.DrawIntoHand(card, true);
            }

            foreach (LibraryCard lc in loaded.CardsInDiscard)
            {
                Card card = gameControl.Create(lc.CardName, true);
                card.InvisibleDiscard();
            }

            gameControl.Deck = loaded.CardsInDeck;

            S.GameControlInst.CheckDeckCount();

            shopControl.Goals = loaded.Goals;

            if (loaded.ShopMode)
            {
                Debug.Log("shop mode!");
                shopControl.CardsToBuyFrom    = new List <LibraryCard> [3];
                shopControl.CardsToBuyFrom[0] = loaded.ShopCardList1;
                shopControl.CardsToBuyFrom[1] = loaded.ShopCardList2;
                shopControl.CardsToBuyFrom[2] = loaded.ShopCardList3;
                S.GameControlGUIInst.ForceDim();
                S.ShopControlInst.ProduceCards();
            }
            else
            {
                for (int i = 0; i < loaded.Enemies.Count; i++)
                {
                    Enemy newEnemy = enemyLibrary.LoadEnemy(loaded.Enemies[i],
                                                            loaded.EnemyXPositions[i],
                                                            loaded.EnemyYPositions[i],
                                                            loaded.EnemyHealths[i]);
                    newEnemy.CurrentPlays = loaded.EnemyPlays[i];
                }

                gridControl.EnemiesFindGridUnits();
                shopControlGUI.NewLevelNewGoals(loaded.Goals.Length, loaded.Goals);

                gameControl.BleedingTurns = loaded.BleedingTurns;
                gameControl.SwollenTurns  = loaded.SwollenTurns;
                gameControl.HungerTurns   = loaded.HungerTurns;
                EventControl.LoadTriggerListState(loaded.TriggerList);
            }

            player.transform.position = new Vector3(loaded.PlayerPosition[0], loaded.PlayerPosition[1], 1);
            player.playerGU.xPosition = loaded.PlayerPosition[0];
            player.playerGU.yPosition = loaded.PlayerPosition[1];
            player.currentHealth      = loaded.PlayerHealth;
            gameControl.SetMoves(loaded.PlayerPlays);
            gameControl.SetMoves(loaded.PlayerMoves);
            gameControl.SetDollars(loaded.Dollars);
            clickControl.AllowForfeitButtonInput = true;
        }
    }
Пример #52
0
        protected override IParcelable OnSaveInstanceState()
        {
            var superState = base.OnSaveInstanceState();

            var savedState = new SavedState(superState, _slideState);
            return savedState;
        }
Пример #53
0
        internal async Task Init()
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("App.config")); //"log4net.config"

            if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
            {
                WriteAndWaitForKey($@"This application must be run as administrator in order to function properly.");
                return;
            }

            //ArkToolkitDomain.Initialize();
            //File.WriteAllText(@"ark.json", JsonConvert.SerializeObject(ArkSavegameToolkitNet.ArkToolkitSettings.Instance, Formatting.Indented));

            var arkConfigCustom = false;

            if (File.Exists(Constants.ArkConfigFilePath))
            {
                try
                {
                    // use custom settings from ark.json
                    ArkToolkitSettings.Instance.Setup(JsonConvert.DeserializeObject <ArkToolkitSettings>(File.ReadAllText(Constants.ArkConfigFilePath)));
                    arkConfigCustom = true;
                }
                catch (Exception ex)
                {
                    Console.AddLogError($@"Error loading 'ark.config'. Using default config. (""{ex.Message}"")");
                    Logging.LogException("Error loading 'ark.config'. Using default config.", ex, GetType());
                }
            }

            if (!arkConfigCustom)
            {
                // initialize default settings
                ArkToolkitDomain.Initialize();
            }

            _config = null;
            string validationMessage = null;
            string errorMessage      = null;

            if (File.Exists(Constants.ConfigFilePath))
            {
                try
                {
                    _config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(Constants.ConfigFilePath));
                    if (_config != null)
                    {
                        if (_config.Discord == null)
                        {
                            _config.Discord = new DiscordConfigSection();
                        }
                        _config.SetupDefaults();
                    }
                    else
                    {
                        errorMessage = "Config.json is empty. Please delete it and restart the application.";
                    }
                }
                catch (Exception ex)
                {
                    validationMessage = ex.Message;
                }
            }
            var hasValidConfig = _config != null;

            if (_config == null)
            {
                //load defaultconfig
                if (!File.Exists(Constants.DefaultConfigFilePath))
                {
                    WriteAndWaitForKey($@"The required file defaultconfig.json is missing from application directory. Please redownload the application.");
                    return;
                }

                try
                {
                    _config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(Constants.DefaultConfigFilePath));
                }
                catch (Exception ex)
                {
                }

                WriteAndWaitForKey(
                    $@"The file config.json is empty or contains errors. Skipping automatic startup...",
                    validationMessage);
            }

            Configuration.Config  = _config as Config;
            About.HasValidConfig  = hasValidConfig;
            About.ValidationError = validationMessage;
            About.ConfigError     = errorMessage;

            if (!hasValidConfig)
            {
                About.IsActive = true;
                return;
            }
            else
            {
                About.IsVisible  = false;
                Console.IsActive = true;
            }

            string errors = ValidateConfig();

            if (errors.Length > 0)
            {
                WriteAndWaitForKey(errors);
                return;
            }

            IProgress <string> progress = new Progress <string>(message =>
            {
                Console.AddLog(message);
            });

            var constants = new Shared.Constants();

            //if (config.Debug)
            //{
            //    //we reset the state so that every run will be the same
            //    if (File.Exists(constants.DatabaseFilePath)) File.Delete(constants.DatabaseFilePath);
            //    if (File.Exists(constants.SavedStateFilePath)) File.Delete(constants.SavedStateFilePath);

            //    //optionally use a saved database state
            //    var databaseStateFilePath = Path.Combine(config.JsonOutputDirPath, "Database.state");
            //    if (File.Exists(databaseStateFilePath)) File.Copy(databaseStateFilePath, constants.DatabaseFilePath);
            //}

            _savedstate = null;
            try
            {
                if (File.Exists(constants.SavedStateFilePath))
                {
                    _savedstate       = JsonConvert.DeserializeObject <SavedState>(File.ReadAllText(constants.SavedStateFilePath));
                    _savedstate._Path = constants.SavedStateFilePath;
                }
            }
            catch { /*ignore exceptions */ }
            _savedstate = _savedstate ?? new SavedState(constants.SavedStateFilePath);

            var discord = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = _config.Discord.LogLevel
            });

            discord.Log += msg =>
            {
                Console.AddLog(msg.Message);
                return(Task.CompletedTask);
            };

            var discordCommands = new CommandService(new CommandServiceConfig
            {
            });

            var anonymizeData = new ArkBotAnonymizeData();

            //setup dependency injection
            var thisAssembly = Assembly.GetExecutingAssembly();
            var builder      = new ContainerBuilder();

            builder.RegisterType <ArkServerContext>().AsSelf();
            builder.RegisterInstance(anonymizeData).AsSelf().As <ArkAnonymizeData>();
            if (_config.UseCompatibilityChangeWatcher)
            {
                builder.RegisterType <ArkSaveFileWatcherTimer>().As <IArkSaveFileWatcher>();
            }
            else
            {
                builder.RegisterType <ArkSaveFileWatcher>().As <IArkSaveFileWatcher>();
            }
            builder.RegisterInstance(discord).AsSelf();
            builder.RegisterInstance(discordCommands).AsSelf();
            builder.RegisterType <AutofacDiscordServiceProvider>().As <IServiceProvider>().SingleInstance();
            builder.RegisterType <ArkDiscordBot>();
            builder.RegisterInstance(constants).As <IConstants>();
            builder.RegisterInstance(_savedstate).As <ISavedState>();
            builder.RegisterInstance(_config as Config).As <IConfig>();
            builder.RegisterType <EfDatabaseContext>().AsSelf().As <IEfDatabaseContext>()
            .WithParameter(new TypedParameter(typeof(string), _config.DatabaseConnectionString));
            builder.RegisterType <EfDatabaseContextFactory>();
            builder.RegisterType <DatabaseRepo>().As <IDatabaseRepo>().SingleInstance();

            builder.RegisterType <ArkServerService>().As <IArkServerService>().SingleInstance();
            builder.RegisterType <SavegameBackupService>().As <ISavegameBackupService>().SingleInstance();
            builder.RegisterType <PlayerLastActiveService>().As <IPlayerLastActiveService>().SingleInstance();
            builder.RegisterType <LogCleanupService>().As <ILogCleanupService>().SingleInstance();

            builder.RegisterHubs(Assembly.GetExecutingAssembly());

            builder.RegisterType <ArkContextManager>().WithParameter(new TypedParameter(typeof(IProgress <string>), progress)).AsSelf().SingleInstance();
            builder.RegisterType <DiscordManager>().AsSelf().SingleInstance();
            builder.RegisterType <ScheduledTasksManager>().AsSelf().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).SingleInstance();

            builder.RegisterType <NotificationManager>().AsSelf().SingleInstance();

            Container = builder.Build();

            //update database
            try
            {
                using (var db = Container.Resolve <EfDatabaseContext>())
                {
                    db.Database.Migrate();
                }
            }
            catch (SqlException ex)
            {
                Console.AddLogError($@"Error initializing Microsoft SQL Server (""{ex.Message}"")");
                Logging.LogException("Error initializing Microsoft SQL Server.", ex, GetType());
                return;
            }

            _contextManager = Container.Resolve <ArkContextManager>();
            //server/cluster contexts
            if (_config.Clusters?.Count > 0)
            {
                foreach (var cluster in _config.Clusters)
                {
                    var context = new ArkClusterContext(cluster, anonymizeData);
                    _contextManager.AddCluster(context);
                }
            }

            if (_config.Servers?.Count > 0)
            {
                var playerLastActiveService = Container.Resolve <IPlayerLastActiveService>();
                var backupService           = Container.Resolve <ISavegameBackupService>();
                var logCleanupService       = Container.Resolve <ILogCleanupService>();
                foreach (var server in _config.Servers)
                {
                    var clusterContext = _contextManager.GetCluster(server.ClusterKey);
                    var context        = Container.Resolve <ArkServerContext>(
                        new TypedParameter(typeof(ServerConfigSection), server),
                        new TypedParameter(typeof(ArkClusterContext), clusterContext));
                    var initTask = context.Initialize(); //fire and forget
                    _contextManager.AddServer(context);
                }

                // Initialize managers so that they are ready to handle events such as ArkContextManager.InitializationCompleted-event.
                var scheduledTasksManager = Container.Resolve <ScheduledTasksManager>();
                var notificationMangager  = Container.Resolve <NotificationManager>();

                // Trigger manual updates for all servers (initialization)
                foreach (var context in _contextManager.Servers)
                {
                    ManuallyUpdateServers.Add(new MenuItemViewModel
                    {
                        Header           = context.Config.Key,
                        Command          = new DelegateCommand <string>(OnManuallyTriggerServerUpdate),
                        CommandParameter = context.Config.Key
                    });
                    _contextManager.QueueUpdateServerManual(context);
                }

                // Trigger manual updates for all clusters (initialization)
                foreach (var context in _contextManager.Clusters)
                {
                    ManuallyUpdateClusters.Add(new MenuItemViewModel
                    {
                        Header           = context.Config.Key,
                        Command          = new DelegateCommand <string>(OnManuallyTriggerClusterUpdate),
                        CommandParameter = context.Config.Key
                    });
                    _contextManager.QueueUpdateClusterManual(context);
                }
            }

            //run the discord bot
            if (_config.Discord.Enabled)
            {
                _runDiscordBotCts  = new CancellationTokenSource();
                _runDiscordBotTask = await Task.Factory.StartNew(async() => await RunDiscordBot(), _runDiscordBotCts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            else
            {
                Console.AddLog("Discord bot is disabled.");
            }

            //load the server multipliers data
            await ArkServerMultipliers.Instance.LoadOrUpdate();

            var modIds = _config.Servers?.SelectMany(x => x.ModIds).Distinct().ToArray() ?? new int[] { };

            //load the species stats data
            await ArkSpeciesStats.Instance.LoadOrUpdate(modIds);

            //load the items data
            await ArkItems.Instance.LoadOrUpdate(modIds);

            //ssl
            if (_config.WebApp.Ssl?.Enabled == true)
            {
                var path   = $"{_config.WebApp.Ssl.Name}.pfx";
                var revoke = false;
                var renew  = false;
                if (File.Exists(path))
                {
                    try
                    {
                        using (var rlt = new X509Certificate2(path, _config.WebApp.Ssl.Password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet))
                        {
                            if (DateTime.Now < rlt.NotBefore || DateTime.Now > rlt.NotAfter.AddDays(-31))
                            {
                                using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                                {
                                    store.Open(OpenFlags.ReadWrite);
                                    if (store.Certificates.Contains(rlt))
                                    {
                                        store.Remove(rlt);
                                    }
                                    store.Close();
                                }

                                renew = revoke = true;
                            }
                        }
                    }
                    catch (Exception ex) { Logging.LogException("Failed to remove ssl certificate from store.", ex, GetType()); }
                }
                else
                {
                    renew = true;
                }

                if (renew)
                {
                    var success = false;
                    Console.AddLog(@"SSL Certificate request issued...");
                    AcmeContext acme = null;
                    try
                    {
                        var pathAccountKey = $"{_config.WebApp.Ssl.Name}-account.pem";
                        if (File.Exists(pathAccountKey))
                        {
                            var accountKey = KeyFactory.FromPem(File.ReadAllText(pathAccountKey));

                            acme = new AcmeContext(WellKnownServers.LetsEncryptV2, accountKey);
                            var account = await acme.Account();
                        }
                        else
                        {
                            acme = new AcmeContext(WellKnownServers.LetsEncryptV2);
                            var account = await acme.NewAccount(_config.WebApp.Ssl.Email, true);

                            var pemKey = acme.AccountKey.ToPem();
                            File.WriteAllText(pathAccountKey, pemKey);
                        }

                        var order = await acme.NewOrder(_config.WebApp.Ssl.Domains);

                        var authz         = (await order.Authorizations()).First();
                        var httpChallenge = await authz.Http();

                        var keyAuthz = httpChallenge.KeyAuthz;

                        using (var webapp = Host.CreateDefaultBuilder()
                                            .UseServiceProviderFactory(new AutofacChildLifetimeScopeServiceProviderFactory(Container.BeginLifetimeScope("AspNetCore_IsolatedRoot_SSL_Renew")))
                                            .ConfigureWebHostDefaults(webBuilder =>
                        {
                            webBuilder
                            .ConfigureLogging(logging =>
                            {
                                logging.ClearProviders();
                                logging.AddDebug();
                                logging.AddWebApp();
                            })
                            .UseUrls(_config.WebApp.Ssl.ChallengeListenPrefix)
                            .Configure((appBuilder) =>
                            {
                                appBuilder.UseRouting();
                                appBuilder.UseEndpoints(endpoints =>
                                {
                                    endpoints.MapGet($"/.well-known/acme-challenge/{httpChallenge.Token}", context =>
                                    {
                                        context.Response.ContentType = "application/text";
                                        context.Response.StatusCode = StatusCodes.Status200OK;
                                        return(context.Response.WriteAsync(keyAuthz));
                                    });
                                });
                            });
                        }).Build())
                        {
                            (webapp as IHost).Start();

                            var result = await httpChallenge.Validate();

                            while (result.Status == Certes.Acme.Resource.ChallengeStatus.Pending || result.Status == Certes.Acme.Resource.ChallengeStatus.Processing)
                            {
                                await Task.Delay(500);

                                result = await httpChallenge.Resource();
                            }

                            if (result.Status == Certes.Acme.Resource.ChallengeStatus.Valid)
                            {
                                var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);
                                var cert       = await order.Generate(new CsrInfo
                                {
                                    CountryName  = new RegionInfo(CultureInfo.CurrentCulture.Name).TwoLetterISORegionName,
                                    Locality     = "Web",
                                    Organization = "ARK Bot",
                                }, privateKey);

                                if (revoke)
                                {
                                    //await acme.RevokeCertificate(
                                    //    File.ReadAllBytes(path),
                                    //    Certes.Acme.Resource.RevocationReason.Superseded,
                                    //    KeyFactory.FromPem(File.ReadAllText(pathPrivateKey)));

                                    if (File.Exists(path))
                                    {
                                        File.Delete(path);
                                    }
                                }

                                //File.WriteAllText(pathPrivateKey, privateKey.ToPem());
                                var pfxBuilder = cert.ToPfx(privateKey);
                                var pfx        = pfxBuilder.Build(_config.WebApp.Ssl.Name, _config.WebApp.Ssl.Password);
                                File.WriteAllBytes(path, pfx);

                                success = true;
                            }
                        }

                        if (success)
                        {
                            Console.AddLog(@"SSL Certificate request completed!");
                        }
                        else
                        {
                            Console.AddLog(@"SSL Certificate challenge failed!");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.AddLogError($@"SSL Certificate request failed! (""{ex.Message}"")");
                        Logging.LogException("Failed to issue ssl certificate.", ex, GetType());
                    }
                }

                // clean up all bindings created by ark bot
                {
                    var(success, output) = await ProcessHelper.RunCommandLine("netsh http show sslcert", _config);

                    if (success && !string.IsNullOrEmpty(output))
                    {
                        var r        = new Regex($@"(?:(?:\s*IP\:port\s*\:\s*(?<ip>[^\:]+?)\:(?<port>\d+))|(?:\s*Hostname\:port\s*\:\s*(?<hostname>[^\:]+?)\:(?<port>\d+))).*Application ID\s*\:\s*{{{Constants.AppId}}}", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                        var sections = output.Split("\r\n\r\n\r\n", StringSplitOptions.RemoveEmptyEntries);
                        foreach (var section in sections)
                        {
                            var m = r.Match(section);
                            if (!m.Success)
                            {
                                continue;
                            }

                            if (m.Groups["hostname"].Success && m.Groups["port"].Success)
                            {
                                await ProcessHelper.RunCommandLine($"netsh http delete sslcert hostnameport={m.Groups["hostname"].Value}:{m.Groups["port"].Value}", _config);
                            }
                            else if (m.Groups["ip"].Success && m.Groups["port"].Success)
                            {
                                await ProcessHelper.RunCommandLine($"netsh http delete sslcert ipport={m.Groups["ip"].Value}:{m.Groups["port"].Value}", _config);
                            }
                        }
                    }
                }
            }

            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-3.1
            try
            {
                _webapp = Host.CreateDefaultBuilder()
                          .UseServiceProviderFactory(new AutofacChildLifetimeScopeServiceProviderFactory(Container.BeginLifetimeScope("AspNetCore_IsolatedRoot")))
                          .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(options =>
                    {
                        options.Listen(IPEndPoint.Parse(_config.WebApp.IPEndpoint), listenOptions =>
                        {
                            if (_config.WebApp.Ssl.Enabled)
                            {
                                listenOptions.UseHttps($"../{_config.WebApp.Ssl.Name}.pfx", _config.WebApp.Ssl.Password);
                            }
                        });
                    })
                    .ConfigureLogging(logging =>
                    {
                        logging.ClearProviders();
                        logging.AddDebug();
                        logging.AddWebApp();
                    })
                    .UseContentRoot(Path.Combine(AppContext.BaseDirectory, "WebApp"))         //Directory.GetCurrentDirectory()
                    .UseWebRoot(Path.Combine(AppContext.BaseDirectory, "WebApp"))
                    .UseStartup <WebAppStartup>();
                }).Build();
                (_webapp as IHost).Start();
                Console.AddLog("Web App started");
            }
            catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 5664)  //Failed to bind to address <...>: address already in use.
            {
                var portInUseBy = (string)null;

                try
                {
                    if (IPEndPoint.TryParse(_config.WebApp.IPEndpoint, out var ipEndpoint))
                    {
                        // power shell
                        // Get-Process -Id (Get-NetTCPConnection -LocalPort 8600).OwningProcess | Format-List *
                        var(success, output) = await ProcessHelper.RunCommandLine($"(Get-Process -Id (Get-NetTCPConnection -LocalPort {ipEndpoint.Port}).OwningProcess).Name", _config, UseCallOperator : false);

                        if (success && !string.IsNullOrEmpty(output))
                        {
                            portInUseBy = $@"Port {ipEndpoint.Port} in use by: {output}";
                        }
                    }
                }
                catch (Exception) { /* do nothing */ }

                Console.AddLogError($@"Failed to start web app! (""{ex.Message}"")");
                if (!string.IsNullOrWhiteSpace(portInUseBy))
                {
                    Console.AddLogError(portInUseBy);
                }
                Logging.LogException("Failed to start web app.", ex, GetType());
            }
        }