Example #1
0
 public Session(SessionState suggested, int minimumNumberOfPlayers)
 {
     _registeredUsers = new List<User>();
     _games = new List<Game>();
     _sessionState = suggested;
     _minmumNumberOfPlayers = minimumNumberOfPlayers;
 }
Example #2
0
        public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces,
            ScriptPackSession scriptPackSession)
        {
            Guard.AgainstNullArgument("references", references);
            Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);

            references.PathReferences.UnionWith(scriptPackSession.References);

            SessionState<Evaluator> sessionState;
            if (!scriptPackSession.State.ContainsKey(SessionKey))
            {
                Logger.Debug("Creating session");
                var context = new CompilerContext(new CompilerSettings
                {
                    AssemblyReferences = references.PathReferences.ToList()
                }, new ConsoleReportPrinter());

                var evaluator = new Evaluator(context);
                var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct();

                var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
                MonoHost.SetHost((ScriptHost)host);

                evaluator.ReferenceAssembly(typeof(MonoHost).Assembly);
                evaluator.InteractiveBaseClass = typeof(MonoHost);

                sessionState = new SessionState<Evaluator>
                {
                    References = new AssemblyReferences(references.PathReferences, references.Assemblies),
                    Namespaces = new HashSet<string>(),
                    Session = evaluator
                };

                ImportNamespaces(allNamespaces, sessionState);

                scriptPackSession.State[SessionKey] = sessionState;
            }
            else
            {
                Logger.Debug("Reusing existing session");
                sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey];

                var newReferences = sessionState.References == null ? references : references.Except(sessionState.References);
                foreach (var reference in newReferences.PathReferences)
                {
                    Logger.DebugFormat("Adding reference to {0}", reference);
                    sessionState.Session.LoadAssembly(reference);
                }

                sessionState.References = new AssemblyReferences(references.PathReferences, references.Assemblies);

                var newNamespaces = sessionState.Namespaces == null ? namespaces : namespaces.Except(sessionState.Namespaces);
                ImportNamespaces(newNamespaces, sessionState);
            }

            Logger.Debug("Starting execution");
            var result = Execute(code, sessionState.Session);
            Logger.Debug("Finished execution");
            return result;
        }
 public HttpContext(string metabasePath, string sessionId, IDictionary<string, object> sessionState)
 {
     ServerVariables = new ServerVariables(metabasePath);
     RequestCookies = new Cookies(sessionId);
     ResponseCookies = new Cookies();
     SessionState = new SessionState(sessionState);
 }
Example #4
0
        public Session(Server server, int id, CreateSessionData sessionData)
        {
            admin = new SessionAdmin(this);
            this.server = server;
            this.id = id;
            data = sessionData;
            if(data.MinPlayers > data.MaxPlayers)
                throw new MinPlayersOutOfRangeException();
            if(data.MinPlayers < 2)
                throw new MinPlayersOutOfRangeException();
            if(data.MinPlayers > 8)
                throw new MinPlayersOutOfRangeException();
            if(data.MaxPlayers < 2)
                throw new MaxPlayersOutOfRangeException();
            if(data.MaxPlayers > 8)
                throw new MaxPlayersOutOfRangeException();
            if(data.MaxSpectators < 0)
                throw new MaxSpectatorsOutOfRangeException();

            state = SessionState.WaitingForPlayers;
            eventMgr = new SessionEventManager(this);
            players = new Dictionary<int, SessionPlayer>(data.MaxPlayers);
            playerList = new List<SessionPlayer>(data.MaxPlayers);
            spectators = new Dictionary<int, SessionSpectator>(data.MaxSpectators);
            spectatorList = new List<SessionSpectator>(data.MaxSpectators);
            creatorId = 0;
            gamesPlayed = 0;
            remainingCharacters = Utils.GetCharacterTypes(this);
            eventMgr.StartPolling();
        }
Example #5
0
        public void Init()
        {
            try
            {
                state = SessionState.Initialized;
                context = new XnMOpenNIContext();
                context.Init();

                session = new XnMSessionManager(context, "Click,Wave", "RaiseHand");
                session.SessionStarted += new EventHandler<PointEventArgs>(session_SessionStarted);
                session.FocusStartDetected += new EventHandler<FocusStartEventArgs>(session_FocusStartDetected);

                slider = new XnMSelectableSlider2D(bounds.Width, bounds.Height);
                slider.Deactivate += new EventHandler(slider_Deactivate);
                slider.ItemHovered += new EventHandler<SelectableSlider2DHoverEventArgs>(slider_ItemHovered);

                pointDenoiser = new XnMPointDenoiser();
                pointDenoiser.AddListener(slider);

                flowRouter = new XnMFlowRouter();
                flowRouter.SetActiveControl(pointDenoiser);

                session.AddListener(flowRouter);
            }
            catch (XnMException)
            {
                state = SessionState.Starting;
            }
        }
Example #6
0
 public POSSession(Guid id, string userName, DateTime openDate, DateTime closeDate, SessionState state)
 {
     this.Id = id;
     this.UserName = userName;
     this.OpenDate = openDate;
     this.CloseDate = closeDate;
     this.SessionState = state;
 }
 public override void Dispose()
 {
     if (state.connection != null) {
         Disconnect();
         state.connection.Dispose();
     }
     state = new SessionState();
 }
        public void SaveSessionState(IManosContext ctx, SessionState state)
        {
            if (!state.Modified)
                return;

            // Just store it
            m_ActiveSessions[state.SessionID] = state;
        }
Example #9
0
        public Session(
            IApplication app, IMessageStoreFactory storeFactory, SessionID sessID, DataDictionaryProvider dataDictProvider,
            SessionSchedule sessionSchedule, int heartBtInt, ILogFactory logFactory, IMessageFactory msgFactory, string senderDefaultApplVerID)
        {
            this.Application = app;
            this.SessionID = sessID;
            this.DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider);
            this.schedule_ = sessionSchedule;
            this.msgFactory_ = msgFactory;

            this.SenderDefaultApplVerID = senderDefaultApplVerID;

            this.SessionDataDictionary = this.DataDictionaryProvider.GetSessionDataDictionary(this.SessionID.BeginString);
            if (this.SessionID.IsFIXT)
                this.ApplicationDataDictionary = this.DataDictionaryProvider.GetApplicationDataDictionary(this.SenderDefaultApplVerID);
            else
                this.ApplicationDataDictionary = this.SessionDataDictionary;

            ILog log;
            if (null != logFactory)
                log = logFactory.Create(sessID);
            else
                log = new NullLog();

            state_ = new SessionState(log, heartBtInt)
            {
                MessageStore = storeFactory.Create(sessID)
            };

            // Configuration defaults.
            // Will be overridden by the SessionFactory with values in the user's configuration.
            this.PersistMessages = true;
            this.ResetOnDisconnect = false;
            this.SendRedundantResendRequests = false;
            this.ValidateLengthAndChecksum = true;
            this.CheckCompID = true;
            this.MillisecondsInTimeStamp = true;
            this.EnableLastMsgSeqNumProcessed = false;
            this.MaxMessagesInResendRequest = 0;
            this.SendLogoutBeforeTimeoutDisconnect = false;
            this.IgnorePossDupResendRequests = false;
            this.RequiresOrigSendingTime = true;
            this.CheckLatency = true;
            this.MaxLatency = 120;

            if (!IsSessionTime)
                Reset("Out of SessionTime (Session construction)");
            else if (IsNewSession)
                Reset("New session");

            lock (sessions_)
            {
                sessions_[this.SessionID] = this;
            }

            this.Application.OnCreate(this.SessionID);
            this.Log.OnEvent("Created session");
        }
        protected override void OnStateChanged (SessionState state)
        {
            if (state == SessionState.Authenticating)
                loadingIndicator.StartAnimating ();
            else
                loadingIndicator.StopAnimating ();

            statusLabel.Text = state.ToString ();
        }
        public void SetSessionState(Session session, SessionState state, string data = null)
        {
            SessionRepository.Change(session, delegate(ref Session s)
            {
                s.State = state;

                if (data != null)
                    s.StateJson = data;
            });
        }
            public void ShouldReturnOnlyLastValueOfVariablesDeclaredManyTimes([NoAutoProperties]RoslynReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);
                engine.Execute("int x = 2;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "System.Int32 x = 2" });
            }
            public void ShouldReturnOnlyLastValueOfVariablesDeclaredManyTimes([NoAutoProperties]MonoScriptEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };
                scriptPackSession.State[MonoScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);
                engine.Execute("int x = 2;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(), scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "int x = 2" });
            }
 private void NotifySessionStateChanged(SessionState state)
 {
     Debug.Log("Event: NotifySessionStateChanged Fired");
     sessionMStateLabel.text = "SessionM State: " + state.ToString();
     if (state == SessionState.StartedOnline) {
         gui.OnPopulateTiers(sessionM.GetTiers());
         sessionM.UpdateOffers();
         sessionM.FetchContent("Furious7_OneLastRide_BD_30_DM_HD_UPRX3032AH-DM_1080_800-mp4", true);
     }
 }
        public void SessionStateStoreTest()
        {
            SessionState session = new SessionState("12345", 100);
            db.Store(session);

            IList<SessionState> list = db.Load<SessionState>(delegate(SessionState ss){
                return ss.SessionId == "12345";
            });
            Assert.AreEqual(1, list.Count);
            Assert.AreEqual("12345", list[0].SessionId);
        }
 public void Call(Session session, SessionState state, Exception exception)
 {
     // Make a request for 'Me' information about the current user
         if (session.IsOpened)
         {
             Intent mainIntent = new Intent(this, typeof(MainActivity));
             mainIntent.PutExtra("facebookToken", session.AccessToken);
             SetResult(Result.FirstUser, mainIntent);
             Finish();
         }
 }
            public void ShouldReturnDeclaredVariables([NoAutoProperties]CSharpReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<ScriptState> { Session = CSharpScript.Run("") };
                scriptPackSession.State[CommonScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                scriptPackSession);

                engine.GetLocalVariables(scriptPackSession).ShouldEqual(new Collection<string> { "System.Int32 x", "System.String y" });
            }
Example #18
0
 public ChannelBase GetTarget(SessionState state, int buffersLimit = 5, bool fillEnvelopeRecipients = false, Node remoteNode = null, Node localNode = null)
 {
     return new TestChannel(
         state,
         _transport.Object,
         _sendTimeout,
         buffersLimit,
         fillEnvelopeRecipients,
         remoteNode, 
         localNode
         );
 }
Example #19
0
        public ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession)
        {
            Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);

            _logger.Info("Starting to create execution components");
            _logger.Debug("Creating script host");

            var distinctReferences = references.Union(scriptPackSession.References).Distinct().ToList();
            SessionState<Session> sessionState;

            if (!scriptPackSession.State.ContainsKey(SessionKey))
            {
                var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs);
                _logger.Debug("Creating session");
                var session = _scriptEngine.CreateSession(host);

                foreach (var reference in distinctReferences)
                {
                    _logger.DebugFormat("Adding reference to {0}", reference);
                    session.AddReference(reference);
                }

                foreach (var @namespace in namespaces.Union(scriptPackSession.Namespaces).Distinct())
                {
                    _logger.DebugFormat("Importing namespace {0}", @namespace);
                    session.ImportNamespace(@namespace);
                }

                sessionState = new SessionState<Session> {References = distinctReferences, Session = session};
                scriptPackSession.State[SessionKey] = sessionState;
            }
            else
            {
                _logger.Debug("Reusing existing session");
                sessionState = (SessionState<Session>) scriptPackSession.State[SessionKey];

                var newReferences = sessionState.References == null || !sessionState.References.Any() ? distinctReferences : distinctReferences.Except(sessionState.References);
                if (newReferences.Any())
                {
                    foreach (var reference in newReferences)
                    {
                        _logger.DebugFormat("Adding reference to {0}", reference);
                        sessionState.Session.AddReference(reference);
                    }
                    sessionState.References = newReferences;
                }
            }

            _logger.Info("Starting execution");
            var result = Execute(code, sessionState.Session);
            _logger.Info("Finished execution");
            return result;
        }
Example #20
0
 internal SmppSession(Stream inputStream, Stream outputStream)
 {
     _pduSender = new PduSender(outputStream);
     _pduReceiver = new PduReceiver(inputStream, this);
     _receiverTask = _pduReceiver.Start().ContinueWith(t =>
     {
         _state = SessionState.Closed;
         Console.WriteLine("Receiver task completed.");
         if (t.IsFaulted)
             Console.WriteLine("Failed with exception: {0}", t.Exception.Flatten());
     });
     _senderTask = _pduSender.Start();
 }
            public void ShouldReturn0VariablesAfterReset([NoAutoProperties]MonoScriptEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };
                scriptPackSession.State[MonoScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
    scriptPackSession);

                scriptPackSession.State[MonoScriptEngine.SessionKey] = new SessionState<Evaluator> { Session = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())) };

                engine.GetLocalVariables(scriptPackSession).ShouldBeEmpty();
            }
            public void ShouldReturn0VariablesAfterReset([NoAutoProperties]RoslynReplEngine engine, ScriptPackSession scriptPackSession)
            {
                var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;

                engine.Execute("int x = 1;", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                    scriptPackSession);
                engine.Execute(@"var y = ""www"";", new string[0], new AssemblyReferences(), Enumerable.Empty<string>(),
                scriptPackSession);

                scriptPackSession.State[RoslynScriptEngine.SessionKey] = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };

                engine.GetLocalVariables(scriptPackSession).ShouldBeEmpty();
            }
Example #23
0
 public ClientChannel GetTarget(Guid? sessionId = null, SessionState state = SessionState.New, bool fillEnvelopeRecipients = false, bool autoReplyPings = true, bool autoNotifyReceipt = true, Node remoteNode = null, Node localNode = null)
 {
     return new TestClientChannel(
         sessionId,
         state,
         _transport.Object,
         _sendTimeout,
         fillEnvelopeRecipients,
         autoReplyPings,
         autoNotifyReceipt,
         remoteNode,
         localNode
         );
 }
		private SessionState<object> GetSession(IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession)
		{
			var distinctReferences = references.Union(scriptPackSession.References).Distinct().Select(x => x.Replace(".dll", "")).ToList();
			var distinctNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct().ToList();

			var sessionState = new SessionState<object> {
				References = distinctReferences,
				Namespaces = distinctNamespaces
			};

			scriptPackSession.State[SessionKey] = sessionState;

			return sessionState;
		}
Example #25
0
 private static void MediaEngineExOnPlaybackEvent(MediaEngineEvent mediaEvent, long param1, int param2)
 {
     if (mediaEvent == MediaEngineEvent.LoadedData)
     {
         if (_desiredPosition.HasValue)
             _mediaEngineEx.CurrentTime = _desiredPosition.Value.TotalSeconds;
         if (_sessionState == SessionState.Started)
             _mediaEngineEx.Play();
     }
     if (mediaEvent == MediaEngineEvent.Ended)
     {
         _sessionState = SessionState.Stopped;
         _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => OnSongFinishedPlaying(null, null)).AsTask();
     }
 }
 public void SetState(Guid movieId, SessionState state, DateTime changingOccured)
 {
     if (state == SessionState.Closed)
     {
         _sessions.RemoveAll(session => session.MovieId == movieId);
         _timeMarks.Remove(movieId);
     }
     if (state == SessionState.Active)
     {
         _timeMarks.Add(movieId, changingOccured);
         foreach (var session in _sessions.Where(s => s.MovieId == movieId))
         {
             session.SessionState = state;
         }
     }
 }
 public ISession Create(
     IEngine engine,
     IDbConnection connection,
     IDbTransaction transaction = null,
     bool disposeConnection = true,
     bool commitAndDisposeTransaction = false,
     bool isTransactionLess = false) {
     var sessionState = new SessionState(
         engine.Configuration,
         connection,
         transaction,
         disposeConnection,
         commitAndDisposeTransaction,
         isTransactionLess);
     return new Session(engine, sessionState);
 }
Example #28
0
            public void ShouldSetIsCompleteSubmissionToFalseIfCodeIsMissingCurlyBracket(
                [NoAutoProperties] RoslynReplEngine engine, ScriptPackSession scriptPackSession)
            {
                // Arrange
                const string Code = "class test {";

                var session = new SessionState<Session> { Session = new ScriptEngine().CreateSession() };
                scriptPackSession.State[RoslynScriptEngine.SessionKey] = session;
                var refs = new AssemblyReferences(new[] { "System" });

                // Act
                var result = engine.Execute(
                    Code, new string[0], refs, Enumerable.Empty<string>(), scriptPackSession);

                // Assert
                result.IsCompleteSubmission.ShouldBeFalse();
            }
		public async Task LogOut()
		{
			await Task.Factory.StartNew(async () =>
				{
					try
					{
						_facebookService.LogOut();
						CurrentUser = null;
						State = SessionState.LoggedOut;
						var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
						await ParseUser.LogOutAsync(tokenSource.Token);
					}
					catch(Exception ex)
					{
						handleException(ex);	
					}
				}).ConfigureAwait(false);			
		}
        InstanceContext IInstanceContextProvider.GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            SessionState state = null;

            bool hasSession = (channel.SessionId != null);
            if (hasSession)
            {
                state = channel.Extensions.Find<SessionState>();
                if (state != null)
                    return state.WaitForInstanceContext();
            }

            int headerIndex = message.Headers.FindHeader(ClientHeader.HeaderName, ClientHeader.HeaderNamespace);
            string clientId = null;
            if (headerIndex != -1)
                clientId = message.Headers.GetHeader<string>(headerIndex);

            if (clientId == null)
                return null;

            bool isNew = false;
            lock (this.ThisLock)
            {
                LighterSessionStateManager manager = LighterSessionContext.GetInstance().SessionManager;
                if (!manager.TryGetValue(clientId, out state))
                {
                    state = new SessionState(clientId, null);
                    manager.Add(clientId, state);
                    isNew = true;
                }
            }

            if (hasSession)
                channel.Extensions.Add(state);

            if (isNew)
                return null;

            InstanceContext instanceContext = state.WaitForInstanceContext();
            if (hasSession)
                instanceContext.IncomingChannels.Add(channel);

            return instanceContext;
        }
Example #31
0
 private void BTN_Stop_Data_Collection_Click(object sender, EventArgs e)
 {
     CurrentSessionState = SessionState.Wait_ForNext_Session;
 }
 /// <summary>
 /// Deletes the data with the specified key.
 /// </summary>
 /// <param name="key">The key.</param>
 public void Delete(string key)
 {
     SessionState.Remove(key);
     _removedThisSession.Add(key);
 }
 private static OperationState GetResolvePackagesOperationState()
 {
     return((OperationState)SessionState.GetInt(kStateResolvePackages, defaultValue: (int)OperationState.Pending));
 }
Example #34
0
 /// <summary>
 /// 初始刷新令牌
 /// </summary>
 protected void InitRefreshToken()
 {
     SessionState.Set(UC_Page_Refresh, "");
     Utility.WriteCookie(UC_Page_Refresh, "");
 }
        static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages)
        {
            // Do nothing if there were compile errors on the target
            if (CompilerMessagesContainError(messages))
            {
                Debug.Log("Weaver: stop because compile errors on target");
                return;
            }

            // Should not run on the editor only assemblies
            if (assemblyPath.Contains("-Editor") || assemblyPath.Contains(".Editor"))
            {
                return;
            }

            // don't weave mirror files
            string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);

            if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName)
            {
                return;
            }

            // find Mirror.dll
            string mirrorRuntimeDll = FindMirrorRuntime();

            if (string.IsNullOrEmpty(mirrorRuntimeDll))
            {
                Debug.LogError("Failed to find Mirror runtime assembly");
                return;
            }
            if (!File.Exists(mirrorRuntimeDll))
            {
                // this is normal, it happens with any assembly that is built before mirror
                // such as unity packages or your own assemblies
                // those don't need to be weaved
                // if any assembly depends on mirror, then it will be built after
                return;
            }

            // find UnityEngine.CoreModule.dll
            string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath();

            if (string.IsNullOrEmpty(unityEngineCoreModuleDLL))
            {
                Debug.LogError("Failed to find UnityEngine assembly");
                return;
            }

            HashSet <string> dependencyPaths = GetDependecyPaths(assemblyPath);

            // passing null in the outputDirectory param will do an in-place update of the assembly
            if (Program.Process(unityEngineCoreModuleDLL, mirrorRuntimeDll, null, new[] { assemblyPath }, dependencyPaths.ToArray(), HandleWarning, HandleError))
            {
                // NOTE: WeaveFailed is critical for unit tests but isn't used elsewhere
                WeaveFailed = false;
            }
            else
            {
                // Set false...will be checked in \Editor\EnterPlayModeSettingsCheck.CheckSuccessfulWeave()
                SessionState.SetBool("MIRROR_WEAVE_SUCCESS", false);

                WeaveFailed = true;
                if (UnityLogEnabled)
                {
                    Debug.LogError("Weaving failed for: " + assemblyPath);
                }
            }
        }
Example #36
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            // If not force, then see if the alias already exists

            if (!Force)
            {
                AliasInfo existingAlias = null;
                if (string.IsNullOrEmpty(Scope))
                {
                    existingAlias = SessionState.Internal.GetAlias(Name);
                }
                else
                {
                    existingAlias = SessionState.Internal.GetAliasAtScope(Name, Scope);
                }

                if (existingAlias != null)
                {
                    // Throw if alias exists and is private...
                    SessionState.ThrowIfNotVisible(this.CommandOrigin, existingAlias);

                    // Since the alias already exists, write an error.

                    SessionStateException aliasExists =
                        new SessionStateException(
                            Name,
                            SessionStateCategory.Alias,
                            "AliasAlreadyExists",
                            SessionStateStrings.AliasAlreadyExists,
                            ErrorCategory.ResourceExists);

                    WriteError(
                        new ErrorRecord(
                            aliasExists.ErrorRecord,
                            aliasExists));
                    return;
                }
            }

            // Create the alias info

            AliasInfo newAlias =
                new AliasInfo(
                    Name,
                    Value,
                    Context,
                    Option);

            newAlias.Description = Description;

            string action =
                AliasCommandStrings.NewAliasAction;

            string target =
                StringUtil.Format(AliasCommandStrings.NewAliasTarget, Name, Value);

            if (ShouldProcess(target, action))
            {
                // Set the alias in the specified scope or the
                // current scope.

                AliasInfo result = null;

                try
                {
                    if (string.IsNullOrEmpty(Scope))
                    {
                        result = SessionState.Internal.SetAliasItem(newAlias, Force, MyInvocation.CommandOrigin);
                    }
                    else
                    {
                        result = SessionState.Internal.SetAliasItemAtScope(newAlias, Scope, Force, MyInvocation.CommandOrigin);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
                catch (PSArgumentOutOfRangeException argOutOfRange)
                {
                    WriteError(
                        new ErrorRecord(
                            argOutOfRange.ErrorRecord,
                            argOutOfRange));
                    return;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    return;
                }

                // Write the alias to the pipeline if PassThru was specified

                if (PassThru && result != null)
                {
                    WriteObject(result);
                }
            }
        }
Example #37
0
        protected override void OnEnable()
        {
            base.OnEnable();

            if (target == null)
            {
                // Either when we are recompiling, or the inspector window is hidden behind another one, the target can get destroyed (null) and thereby will raise an ArgumentException when accessing serializedObject. For now, just return.
                return;
            }

            MixedRealityToolkitConfigurationProfile mrtkConfigProfile = target as MixedRealityToolkitConfigurationProfile;

            // Experience configuration
            experienceSettingsProfile = serializedObject.FindProperty("experienceSettingsProfile");
            experienceScaleMigration  = serializedObject.FindProperty("targetExperienceScale");

            // Camera configuration
            enableCameraSystem = serializedObject.FindProperty("enableCameraSystem");
            cameraSystemType   = serializedObject.FindProperty("cameraSystemType");
            cameraProfile      = serializedObject.FindProperty("cameraProfile");
            // Input system configuration
            enableInputSystem  = serializedObject.FindProperty("enableInputSystem");
            inputSystemType    = serializedObject.FindProperty("inputSystemType");
            inputSystemProfile = serializedObject.FindProperty("inputSystemProfile");
            // Boundary system configuration
            enableBoundarySystem         = serializedObject.FindProperty("enableBoundarySystem");
            boundarySystemType           = serializedObject.FindProperty("boundarySystemType");
            xrsdkBoundarySystemType      = serializedObject.FindProperty("xrsdkBoundarySystemType");
            boundaryVisualizationProfile = serializedObject.FindProperty("boundaryVisualizationProfile");
#if UNITY_2019
            xrPipelineUtility.Enable();
#endif // UNITY_2019

            // Teleport system configuration
            enableTeleportSystem = serializedObject.FindProperty("enableTeleportSystem");
            teleportSystemType   = serializedObject.FindProperty("teleportSystemType");
            // Spatial Awareness system configuration
            enableSpatialAwarenessSystem  = serializedObject.FindProperty("enableSpatialAwarenessSystem");
            spatialAwarenessSystemType    = serializedObject.FindProperty("spatialAwarenessSystemType");
            spatialAwarenessSystemProfile = serializedObject.FindProperty("spatialAwarenessSystemProfile");
            // Diagnostics system configuration
            enableDiagnosticsSystem  = serializedObject.FindProperty("enableDiagnosticsSystem");
            enableVerboseLogging     = serializedObject.FindProperty("enableVerboseLogging");
            diagnosticsSystemType    = serializedObject.FindProperty("diagnosticsSystemType");
            diagnosticsSystemProfile = serializedObject.FindProperty("diagnosticsSystemProfile");
            // Scene system configuration
            enableSceneSystem  = serializedObject.FindProperty("enableSceneSystem");
            sceneSystemType    = serializedObject.FindProperty("sceneSystemType");
            sceneSystemProfile = serializedObject.FindProperty("sceneSystemProfile");

            // Additional registered components configuration
            registeredServiceProvidersProfile = serializedObject.FindProperty("registeredServiceProvidersProfile");

            // Editor settings
            useServiceInspectors = serializedObject.FindProperty("useServiceInspectors");
            renderDepthBuffer    = serializedObject.FindProperty("renderDepthBuffer");

            SelectedProfileTab = SessionState.GetInt(SelectedTabPreferenceKey, SelectedProfileTab);

            if (renderProfileFuncs == null)
            {
                renderProfileFuncs = new Func <bool>[]
                {
                    () => {
                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            // Reconciling old Experience Scale property with the Experience Settings Profile
                            var oldExperienceSettigsScale = (experienceSettingsProfile.objectReferenceValue as MixedRealityExperienceSettingsProfile)?.TargetExperienceScale;

                            changed |= RenderProfile(experienceSettingsProfile, typeof(MixedRealityExperienceSettingsProfile), true, false, null);

                            // Experience configuration
                            if (!mrtkConfigProfile.ExperienceSettingsProfile.IsNull())
                            {
                                // If the Experience Scale property changed, make sure we also alter the configuration profile's target experience scale property for compatibility
                                var newExperienceSettigs = (experienceSettingsProfile.objectReferenceValue as MixedRealityExperienceSettingsProfile)?.TargetExperienceScale;
                                if (oldExperienceSettigsScale.HasValue && newExperienceSettigs.HasValue && oldExperienceSettigsScale != newExperienceSettigs)
                                {
                                    experienceScaleMigration.intValue = (int)newExperienceSettigs;
                                    experienceScaleMigration.serializedObject.ApplyModifiedProperties();
                                }
                                // If we have not changed the Experience Settings profile and it's value is out of sync with the top level configuration profile, display a migration prompt
                                else if ((ExperienceScale)experienceScaleMigration.intValue != mrtkConfigProfile.ExperienceSettingsProfile.TargetExperienceScale)
                                {
                                    Color errorColor   = Color.Lerp(Color.white, Color.red, 0.5f);
                                    Color defaultColor = GUI.color;

                                    GUI.color = errorColor;
                                    EditorGUILayout.HelpBox("A previous version of this profile has a different Experience Scale, displayed below. Please modify the Experience Setting Profile's Target Experience Scale or select your desired scale below", MessageType.Warning);
                                    var oldValue = experienceScaleMigration.intValue;
                                    EditorGUILayout.PropertyField(experienceScaleMigration);
                                    if (oldValue != experienceScaleMigration.intValue)
                                    {
                                        mrtkConfigProfile.ExperienceSettingsProfile.TargetExperienceScale = (ExperienceScale)experienceScaleMigration.intValue;
                                    }
                                    GUI.color = defaultColor;
                                }


                                ExperienceScale experienceScale         = mrtkConfigProfile.ExperienceSettingsProfile.TargetExperienceScale;
                                string          targetExperienceSummary = GetExperienceDescription(experienceScale);
                                if (!string.IsNullOrEmpty(targetExperienceSummary))
                                {
                                    EditorGUILayout.HelpBox(targetExperienceSummary, MessageType.None);
                                    EditorGUILayout.Space();
                                }
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableCameraSystem);

                            const string service = "Camera System";
                            if (enableCameraSystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.CameraSystemType, mrtkConfigProfile.CameraProfile != null);

                                EditorGUILayout.PropertyField(cameraSystemType);

                                changed |= RenderProfile(cameraProfile, typeof(MixedRealityCameraProfile), true, false);
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableInputSystem);

                            const string service = "Input System";
                            if (enableInputSystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.InputSystemType, mrtkConfigProfile.InputSystemProfile != null);

                                EditorGUILayout.PropertyField(inputSystemType);

                                changed |= RenderProfile(inputSystemProfile, null, true, false, typeof(IMixedRealityInputSystem));
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        if (mrtkConfigProfile.ExperienceSettingsProfile.IsNull())
                        {
                            // Alert that an experience settings profile has not been selected
                            GUILayout.Space(6f);
                            EditorGUILayout.HelpBox("Boundaries require an experience settings profile with a Room scale target experience scale.", MessageType.Warning);
                            GUILayout.Space(6f);
                        }
                        else
                        {
                            var experienceScale = mrtkConfigProfile.ExperienceSettingsProfile.TargetExperienceScale;
                            if (experienceScale != ExperienceScale.Room)
                            {
                                // Alert the user if the experience scale does not support boundary features.
                                GUILayout.Space(6f);
                                EditorGUILayout.HelpBox("Boundaries are only supported in Room scale experiences.", MessageType.Warning);
                                GUILayout.Space(6f);
                            }
                        }

                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableBoundarySystem);

                            const string service = "Boundary System";
                            if (enableBoundarySystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.BoundarySystemSystemType, mrtkConfigProfile.BoundaryVisualizationProfile != null);

#if UNITY_2019
                                xrPipelineUtility.RenderXRPipelineTabs();
#endif // UNITY_2019

                                EditorGUILayout.PropertyField(xrPipelineUtility.SelectedPipeline == SupportedUnityXRPipelines.XRSDK ? xrsdkBoundarySystemType : boundarySystemType);

                                changed |= RenderProfile(boundaryVisualizationProfile, null, true, false, typeof(IMixedRealityBoundarySystem));
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        const string service = "Teleport System";
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableTeleportSystem);
                            if (enableTeleportSystem.boolValue)
                            {
                                // Teleport System does not have a profile scriptableobject so auto to true
                                CheckSystemConfiguration(service, mrtkConfigProfile.TeleportSystemSystemType, true);

                                EditorGUILayout.PropertyField(teleportSystemType);
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            return(c.changed);
                        }
                    },
                    () => {
                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            const string service = "Spatial Awareness System";
                            EditorGUILayout.PropertyField(enableSpatialAwarenessSystem);

                            if (enableSpatialAwarenessSystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.SpatialAwarenessSystemSystemType, mrtkConfigProfile.SpatialAwarenessSystemProfile != null);

                                EditorGUILayout.PropertyField(spatialAwarenessSystemType);

                                EditorGUILayout.HelpBox("Spatial Awareness settings are configured per observer.", MessageType.Info);

                                changed |= RenderProfile(spatialAwarenessSystemProfile, null, true, false, typeof(IMixedRealitySpatialAwarenessSystem));
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        EditorGUILayout.HelpBox("It is recommended to enable the Diagnostics system during development. Be sure to disable prior to building your shipping product.", MessageType.Warning);

                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableVerboseLogging);
                            EditorGUILayout.PropertyField(enableDiagnosticsSystem);

                            const string service = "Diagnostics System";
                            if (enableDiagnosticsSystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.DiagnosticsSystemSystemType, mrtkConfigProfile.DiagnosticsSystemProfile != null);

                                EditorGUILayout.PropertyField(diagnosticsSystemType);

                                changed |= RenderProfile(diagnosticsSystemProfile, typeof(MixedRealityDiagnosticsProfile));
                            }
                            else
                            {
                                RenderSystemDisabled(service);
                            }

                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        bool changed = false;
                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(enableSceneSystem);
                            const string service = "Scene System";
                            if (enableSceneSystem.boolValue)
                            {
                                CheckSystemConfiguration(service, mrtkConfigProfile.SceneSystemSystemType, mrtkConfigProfile.SceneSystemProfile != null);

                                EditorGUILayout.PropertyField(sceneSystemType);

                                changed |= RenderProfile(sceneSystemProfile, typeof(MixedRealitySceneSystemProfile), true, true, typeof(IMixedRealitySceneSystem));
                            }
                            changed |= c.changed;
                        }
                        return(changed);
                    },
                    () => {
                        return(RenderProfile(registeredServiceProvidersProfile, typeof(MixedRealityRegisteredServiceProvidersProfile), true, false));
                    },
                    () => {
                        EditorGUILayout.PropertyField(useServiceInspectors);

                        using (var c = new EditorGUI.ChangeCheckScope())
                        {
                            EditorGUILayout.PropertyField(renderDepthBuffer);
                            if (c.changed)
                            {
                                if (renderDepthBuffer.boolValue)
                                {
                                    CameraCache.Main.gameObject.AddComponent <DepthBufferRenderer>();
                                }
                                else
                                {
                                    foreach (var dbr in FindObjectsOfType <DepthBufferRenderer>())
                                    {
                                        UnityObjectExtensions.DestroyObject(dbr);
                                    }
                                }
                            }
                        }
                        return(false);
                    },
                };
            }
        }
Example #38
0
        void InitIfNeeded()
        {
            if (m_Initialized)
            {
                return;
            }

            if (m_CachedCallstack == null)
            {
                m_CachedCallstack = new List <ulong>();
            }

            var cpuDetailColumns = new[]
            {
                HierarchyFrameDataView.columnObjectName,
                HierarchyFrameDataView.columnTotalPercent,
                HierarchyFrameDataView.columnGcMemory,
                HierarchyFrameDataView.columnTotalTime
            };
            var gpuDetailColumns = new[]
            {
                HierarchyFrameDataView.columnObjectName,
                HierarchyFrameDataView.columnTotalGpuPercent,
                HierarchyFrameDataView.columnDrawCalls,
                HierarchyFrameDataView.columnTotalGpuTime
            };
            var profilerColumns   = gpuView ? gpuDetailColumns : cpuDetailColumns;
            var defaultSortColumn = gpuView ? HierarchyFrameDataView.columnTotalGpuTime : HierarchyFrameDataView.columnTotalTime;

            var columns     = ProfilerFrameDataHierarchyView.CreateColumns(profilerColumns);
            var headerState = ProfilerFrameDataHierarchyView.CreateDefaultMultiColumnHeaderState(columns, defaultSortColumn);

            headerState.columns[0].minWidth              = 60;
            headerState.columns[0].autoResize            = true;
            headerState.columns[0].allowToggleVisibility = false;

            var multiColumnHeaderStateData = SessionState.GetString(multiColumnHeaderStatePrefKey, "");

            if (!string.IsNullOrEmpty(multiColumnHeaderStateData))
            {
                try
                {
                    var restoredHeaderState = JsonUtility.FromJson <MultiColumnHeaderState>(multiColumnHeaderStateData);
                    if (restoredHeaderState != null)
                    {
                        m_MultiColumnHeaderState = restoredHeaderState;
                    }
                }
                catch {} // Nevermind, we'll just fall back to the default
            }

            if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_MultiColumnHeaderState, headerState))
            {
                MultiColumnHeaderState.OverwriteSerializedFields(m_MultiColumnHeaderState, headerState);
            }

            var firstInit = m_MultiColumnHeaderState == null;

            m_MultiColumnHeaderState = headerState;

            m_MultiColumnHeader = new ProfilerFrameDataMultiColumnHeader(m_MultiColumnHeaderState, columns)
            {
                height = 25
            };
            if (firstInit)
            {
                m_MultiColumnHeader.ResizeToFit();
            }

            m_MultiColumnHeader.visibleColumnsChanged += OnMultiColumnHeaderChanged;
            m_MultiColumnHeader.sortingChanged        += OnMultiColumnHeaderChanged;

            if (m_TreeViewState == null)
            {
                m_TreeViewState = new TreeViewState();
            }
            m_TreeView = new ObjectsTreeView(m_TreeViewState, m_MultiColumnHeader);
            m_TreeView.frameItemEvent += frameItemEvent;

            if (m_VertSplit == null || m_VertSplit.relativeSizes == null || m_VertSplit.relativeSizes.Length == 0)
            {
                m_VertSplit = new SplitterState(new[] { SessionState.GetFloat(splitter0StatePrefKey, 60f), SessionState.GetFloat(splitter1StatePrefKey, 40f) }, new[] { 50, 50 }, null);
            }

            m_Initialized = true;
        }
Example #39
0
 void OnMultiColumnHeaderChanged(MultiColumnHeader header)
 {
     SessionState.SetString(multiColumnHeaderStatePrefKey, JsonUtility.ToJson(header.state));
 }
Example #40
0
 private void NotifySessionStateChanged(SessionState state)
 {
     Debug.Log("Event: NotifySessionStateChanged Fired");
 }
Example #41
0
 public SessionAccount(string license, string steam, string name, string handle, SessionState state, DateTime queuestarttime, bool haspriority, Reserved reservedtype, Reserved reservedused)
 {
     License          = license;
     Steam            = steam;
     Name             = name;
     Handle           = handle;
     State            = state;
     QueueStartTime   = queuestarttime;
     HasPriority      = haspriority;
     ReservedType     = reservedtype;
     ReservedTypeUsed = reservedused;
 }
Example #42
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        ///
        protected override void ProcessRecord()
        {
            Collection <AliasInfo> importedAliases = GetAliasesFromFile(this.ParameterSetName.Equals(LiteralPathParameterSetName,
                                                                                                     StringComparison.OrdinalIgnoreCase));

            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (AliasInfo alias in importedAliases)
            {
                // If not force, then see if the alias already exists

                // NTRAID#Windows Out Of Band Releases-906910-2006/03/17-JonN
                string action = AliasCommandStrings.ImportAliasAction;

                string target = StringUtil.Format(AliasCommandStrings.ImportAliasTarget, alias.Name, alias.Definition);

                if (!ShouldProcess(target, action))
                {
                    continue;
                }

                if (!Force)
                {
                    AliasInfo existingAlias = null;
                    if (String.IsNullOrEmpty(Scope))
                    {
                        existingAlias = SessionState.Internal.GetAlias(alias.Name);
                    }
                    else
                    {
                        existingAlias = SessionState.Internal.GetAliasAtScope(alias.Name, Scope);
                    }

                    if (existingAlias != null)
                    {
                        // Write an error for aliases that aren't visible...
                        try
                        {
                            SessionState.ThrowIfNotVisible(origin, existingAlias);
                        }
                        catch (SessionStateException sessionStateException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    sessionStateException.ErrorRecord,
                                    sessionStateException));
                            // Only report the error once...
                            continue;
                        }

                        // Since the alias already exists, write an error.

                        SessionStateException aliasExists =
                            new SessionStateException(
                                alias.Name,
                                SessionStateCategory.Alias,
                                "AliasAlreadyExists",
                                SessionStateStrings.AliasAlreadyExists,
                                ErrorCategory.ResourceExists);

                        WriteError(
                            new ErrorRecord(
                                aliasExists.ErrorRecord,
                                aliasExists));
                        continue;
                    }

                    if (VerifyShadowingExistingCommandsAndWriteError(alias.Name))
                    {
                        continue;
                    }
                } // if (!Force)

                // Set the alias in the specified scope or the
                // current scope.

                AliasInfo result = null;

                try
                {
                    if (String.IsNullOrEmpty(Scope))
                    {
                        result = SessionState.Internal.SetAliasItem(alias, Force, MyInvocation.CommandOrigin);
                    }
                    else
                    {
                        result = SessionState.Internal.SetAliasItemAtScope(alias, Scope, Force, MyInvocation.CommandOrigin);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    continue;
                }
                catch (PSArgumentOutOfRangeException argOutOfRange)
                {
                    WriteError(
                        new ErrorRecord(
                            argOutOfRange.ErrorRecord,
                            argOutOfRange));
                    continue;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    continue;
                }

                // Write the alias to the pipeline if PassThru was specified

                if (PassThru && result != null)
                {
                    WriteObject(result);
                }
            }
        } // ProcessRecord
 /// <summary>
 /// Resolve a Win32 path using current PS session state.
 /// </summary>
 /// <param name="state">The session state.</param>
 /// <param name="path">The path to resolve.</param>
 /// <returns>The resolved Win32 path.</returns>
 public static string ResolveWin32Path(SessionState state, string path)
 {
     return(ResolveWin32Path(state, path, true));
 }
Example #44
0
 private void BTN_Cancel_Test_Click(object sender, EventArgs e)
 {
     CurrentSessionState = SessionState.Wait_ForNext_Session;
 }
Example #45
0
        /// <summary>
        /// Gets the name(s) of the item(s) at the given path.
        /// </summary>
        /// <param name="path">
        /// The name of the item to retrieve, or all if empty or null.
        /// </param>
        /// <param name="returnContainers">
        /// Ignored.
        /// </param>
        protected override void GetChildNames(string path, ReturnContainers returnContainers)
        {
            CommandOrigin origin = this.Context.Origin;

            if (string.IsNullOrEmpty(path))
            {
                IDictionary dictionary = null;

                try
                {
                    dictionary = GetSessionStateTable();
                }
                catch (SecurityException e)
                {
                    WriteError(
                        new ErrorRecord(
                            e,
                            "GetChildNamesSecurityException",
                            ErrorCategory.ReadError,
                            path));
                    return;
                }

                // Now write out each object's key...

                foreach (DictionaryEntry entry in dictionary)
                {
                    try
                    {
                        if (SessionState.IsVisible(origin, entry.Value))
                        {
                            WriteItemObject(entry.Key, (string)entry.Key, false);
                        }
                    }
                    catch (PSArgumentException argException)
                    {
                        WriteError(
                            new ErrorRecord(
                                argException.ErrorRecord,
                                argException));

                        return;
                    }
                    catch (SecurityException securityException)
                    {
                        WriteError(
                            new ErrorRecord(
                                securityException,
                                "GetItemSecurityException",
                                ErrorCategory.PermissionDenied,
                                (string)entry.Key));
                        return;
                    }
                }
            }
            else
            {
                object item = null;

                try
                {
                    item = GetSessionStateItem(path);
                }
                catch (SecurityException e)
                {
                    WriteError(
                        new ErrorRecord(
                            e,
                            "GetChildNamesSecurityException",
                            ErrorCategory.ReadError,
                            path));
                    return;
                }

                if (item != null)
                {
                    if (SessionState.IsVisible(origin, item))
                    {
                        WriteItemObject(path, path, false);
                    }
                }
            }
        }
            public override void OnInspectorGUI()
            {
                ButtonIconSet bis = (ButtonIconSet)target;

                bool showQuadIconFoldout   = SessionState.GetBool(ShowQuadIconsFoldoutKey, false);
                bool showSpriteIconFoldout = SessionState.GetBool(ShowSpriteIconsFoldoutKey, false);
                bool showCharIconFoldout   = SessionState.GetBool(ShowCharIconsFoldoutKey, false);
                bool showAvailableIcons    = SessionState.GetBool(AvailableIconsFoldoutKey, true);
                bool showSelectedIcons     = SessionState.GetBool(SelectedIconsFoldoutKey, true);

#if UNITY_2019_3_OR_NEWER
                showQuadIconFoldout = EditorGUILayout.BeginFoldoutHeaderGroup(showQuadIconFoldout, "Quad Icons");
#else
                showQuadIconFoldout = EditorGUILayout.Foldout(showQuadIconFoldout, "Quad Icons");
#endif
                if (showQuadIconFoldout)
                {
                    using (new EditorGUI.IndentLevelScope(1))
                    {
                        quadIconsProp.isExpanded = true;
                        EditorGUILayout.PropertyField(quadIconsProp, true);
                    }
                }
#if UNITY_2019_3_OR_NEWER
                EditorGUILayout.EndFoldoutHeaderGroup();
#endif

#if UNITY_2019_3_OR_NEWER
                showSpriteIconFoldout = EditorGUILayout.BeginFoldoutHeaderGroup(showSpriteIconFoldout, "Sprite Icons");
#else
                showSpriteIconFoldout = EditorGUILayout.Foldout(showSpriteIconFoldout, "Sprite Icons");
#endif
                if (showSpriteIconFoldout)
                {
                    using (new EditorGUI.IndentLevelScope(1))
                    {
                        spriteIconsProp.isExpanded = true;

                        // Check if the sprite Icons were updated
                        EditorGUI.BeginChangeCheck();
                        EditorGUILayout.PropertyField(spriteIconsProp, true);
                        // End the code block and update the label if a change occurred
                        if (EditorGUI.EndChangeCheck())
                        {
                            serializedObject.ApplyModifiedProperties();
                            bis.UpdateSpriteIconTextures();
                        }
                    }
                }
#if UNITY_2019_3_OR_NEWER
                EditorGUILayout.EndFoldoutHeaderGroup();
#endif

#if UNITY_2019_3_OR_NEWER
                showCharIconFoldout = EditorGUILayout.BeginFoldoutHeaderGroup(showCharIconFoldout, "Font Icons");
#else
                showCharIconFoldout = EditorGUILayout.Foldout(showCharIconFoldout, "Font Icons");
#endif


#if UNITY_2019_3_OR_NEWER
                EditorGUILayout.EndFoldoutHeaderGroup();
#endif

                if (showCharIconFoldout)
                {
                    EditorGUILayout.PropertyField(charIconFontProp);

                    if (charIconFontProp.objectReferenceValue == null)
                    {
                        EditorGUILayout.HelpBox(noIconFontMessage, MessageType.Warning);
                        if (!CheckIfHololensIconFontExists())
                        {
                            EditorGUILayout.HelpBox(downloadIconFontMessage, MessageType.Info);
                            if (GUILayout.Button("View Button Documentation"))
                            {
                                EditorApplication.ExecuteMenuItem(textMeshProMenuItem);
                                Application.OpenURL(hololensIconFontUrl);
                            }
                        }
                    }
                    else
                    {
                        TMP_FontAsset fontAsset = (TMP_FontAsset)charIconFontProp.objectReferenceValue;

#if UNITY_2019_3_OR_NEWER
                        showAvailableIcons = EditorGUILayout.BeginFoldoutHeaderGroup(showAvailableIcons, "Available Icons");
#else
                        showAvailableIcons = EditorGUILayout.Foldout(showAvailableIcons, "Available Icons");
#endif

                        if (showAvailableIcons)
                        {
                            if (fontAsset.characterTable.Count == 0)
                            {
                                EditorGUILayout.HelpBox("No icons are available in this font. The font may be configured incorrectly.", MessageType.Warning);
                                if (GUILayout.Button("Open Font Editor"))
                                {
                                    Selection.activeObject = bis.CharIconFont;
                                }
                            }
                            else
                            {
                                EditorGUILayout.HelpBox("Click an icon to add it to your selected icons.", MessageType.Info);
                                if (GUILayout.Button("Open Font Editor"))
                                {
                                    Selection.activeObject = bis.CharIconFont;
                                }

                                int removeIndex = -1;
                                int addIndex    = -1;
                                int column      = 0;

                                column = 0;
                                EditorGUILayout.BeginHorizontal();
                                for (int i = 0; i < fontAsset.characterTable.Count; i++)
                                {
                                    if (column >= maxButtonsPerColumn)
                                    {
                                        column = 0;
                                        EditorGUILayout.EndHorizontal();
                                        EditorGUILayout.BeginHorizontal();
                                    }
                                    if (GUILayout.Button(" ",
                                                         GUILayout.MinHeight(maxButtonSize),
                                                         GUILayout.MaxHeight(maxButtonSize),
                                                         GUILayout.MaxWidth(maxButtonSize)))
                                    {
                                        addIndex = i;
                                    }
                                    Rect textureRect = GUILayoutUtility.GetLastRect();
                                    EditorDrawTMPGlyph(textureRect, fontAsset, fontAsset.characterTable[i]);
                                    column++;
                                }

                                if (column > 0)
                                {
                                    EditorGUILayout.EndHorizontal();
                                }

                                if (removeIndex >= 0)
                                {
                                    List <CharIcon> charIconsSet = new List <CharIcon>(bis.charIcons);
                                    charIconsSet.RemoveAt(removeIndex);
                                    bis.charIcons = charIconsSet.ToArray();
                                    EditorUtility.SetDirty(target);
                                }

                                if (addIndex >= 0)
                                {
                                    uint unicode             = fontAsset.characterTable[addIndex].unicode;
                                    bool alreadyContainsIcon = false;
                                    foreach (CharIcon c in bis.charIcons)
                                    {
                                        if (c.Character == unicode)
                                        {
                                            alreadyContainsIcon = true;
                                            break;
                                        }
                                    }

                                    if (!alreadyContainsIcon)
                                    {
                                        charIconsProp.InsertArrayElementAtIndex(charIconsProp.arraySize);

                                        SerializedProperty newIconProp = charIconsProp.GetArrayElementAtIndex(charIconsProp.arraySize - 1);
                                        SerializedProperty charProp    = newIconProp.FindPropertyRelative("Character");
                                        SerializedProperty nameProp    = newIconProp.FindPropertyRelative("Name");

                                        charProp.intValue    = (int)unicode;
                                        nameProp.stringValue = "Icon " + charIconsProp.arraySize.ToString();

                                        serializedObject.ApplyModifiedProperties();
                                    }
                                }
                            }
                            EditorGUILayout.Space();
                        }
#if UNITY_2019_3_OR_NEWER
                        EditorGUILayout.EndFoldoutHeaderGroup();
                        showSelectedIcons = EditorGUILayout.BeginFoldoutHeaderGroup(showSelectedIcons, "Selected Icons");
#else
                        showSelectedIcons = EditorGUILayout.Foldout(showSelectedIcons, "Selected Icons");
#endif

                        if (showSelectedIcons)
                        {
                            int removeIndex = -1;

                            if (charIconsProp.arraySize > 0)
                            {
                                EditorGUILayout.HelpBox("These icons will appear in the button config helper inspector. Click an icon to remove it from this list.", MessageType.Info);

                                using (new EditorGUILayout.VerticalScope())
                                {
                                    for (int i = 0; i < charIconsProp.arraySize; i++)
                                    {
                                        SerializedProperty charIconNameprop = charIconsProp.GetArrayElementAtIndex(i).FindPropertyRelative("Name");

                                        using (new EditorGUILayout.HorizontalScope())
                                        {
                                            if (GUILayout.Button(" ", GUILayout.MinHeight(maxButtonSize), GUILayout.MaxHeight(maxButtonSize)))
                                            {
                                                removeIndex = i;
                                            }
                                            Rect textureRect = GUILayoutUtility.GetLastRect();
                                            EditorDrawTMPGlyph(textureRect, bis.charIcons[i].Character, fontAsset);
                                            charIconNameprop.stringValue = EditorGUILayout.TextField(charIconNameprop.stringValue);
                                            EditorGUILayout.Space();
                                        }

                                        EditorGUILayout.Space();
                                    }
                                }
                            }
                            else
                            {
                                EditorGUILayout.HelpBox("No icons added yet. Click available icons to add.", MessageType.Info);
                            }

                            if (removeIndex >= 0)
                            {
                                charIconsProp.DeleteArrayElementAtIndex(removeIndex);
                            }
                        }

#if UNITY_2019_3_OR_NEWER
                        EditorGUILayout.EndFoldoutHeaderGroup();
#endif
                    }
                }

                SessionState.SetBool(ShowQuadIconsFoldoutKey, showQuadIconFoldout);
                SessionState.SetBool(ShowSpriteIconsFoldoutKey, showSpriteIconFoldout);
                SessionState.SetBool(ShowCharIconsFoldoutKey, showCharIconFoldout);
                SessionState.SetBool(AvailableIconsFoldoutKey, showAvailableIcons);
                SessionState.SetBool(SelectedIconsFoldoutKey, showSelectedIcons);

                serializedObject.ApplyModifiedProperties();
            }
Example #47
0
 private static void StartSession(Variant startPosition)
 {
     _sessionState = SessionState.Started;
     _session.Start(null, startPosition);
 }
Example #48
0
        /// <summary>
        /// Callback function for the outputstream.
        /// </summary>
        /// <param name="streamHandle">Bass stream handle that requests sample data.</param>
        /// <param name="buffer">Buffer to write the sampledata to.</param>
        /// <param name="requestedBytes">Requested number of bytes.</param>
        /// <param name="userData"></param>
        /// <returns>Number of bytes read.</returns>
        private int OutputStreamWriteProc(int streamHandle, IntPtr buffer, int requestedBytes, IntPtr userData)
        {
            IInputSource inputSource;

            lock (_syncObj)
            {
                if (_state == SessionState.Reset)
                {
                    return(0);
                }
                inputSource = _currentInputSource;
                if (inputSource == null)
                {
                    _state = SessionState.Ended;
                    return((int)BASSStreamProc.BASS_STREAMPROC_END);
                }
            }

            try
            {
                BassStream stream = inputSource.OutputStream;
                int        read   = stream.Read(buffer, requestedBytes);

                bool doCheckNextInputSource = false;
                lock (_syncObj)
                    if (!_isAwaitingNextInputSource && stream.GetPosition() > stream.Length.Subtract(REQUEST_NEXT_ITEM_THRESHOLD))
                    { // Near end of the stream - make sure that next input source is available
                        _isAwaitingNextInputSource = true;
                        doCheckNextInputSource     = true;
                    }
                if (doCheckNextInputSource)
                {
                    _playbackProcessor.CheckInputSourceAvailable();
                }

                if (read > 0)
                {
                    // Normal case, we have finished
                    return(read);
                }

                // Old buffer ran out of samples - either we can get another valid input source below or we are finished. End wait state.
                _isAwaitingNextInputSource = false;

                // Nothing could be read from old input source. Second try: Next input source.
                IInputSource newInputSource = _playbackProcessor.PeekNextInputSource();

                // Special treatment for CD drives: If the new input source is from the same audio CD drive, we must take the stream over
                BassCDTrackInputSource bcdtisOld = inputSource as BassCDTrackInputSource;
                BassCDTrackInputSource bcdtisNew = newInputSource as BassCDTrackInputSource;
                if (bcdtisOld != null && bcdtisNew != null)
                {
                    if (bcdtisOld.SwitchTo(bcdtisNew))
                    {
                        _playbackProcessor.ClearNextInputSource();
                        return(OutputStreamWriteProc(streamHandle, buffer, requestedBytes, userData));
                    }
                }

                lock (_syncObj)
                {
                    _currentInputSource = null;
                    _controller.ScheduleDisposeObject_Async(inputSource);
                    if (newInputSource == null)
                    {
                        _state = SessionState.Ended;
                        return((int)BASSStreamProc.BASS_STREAMPROC_END);
                    }
                }

                if (!MatchesInputSource(newInputSource))
                { // The next available input source is not compatible, so end our stream. The playback processor will start a new playback session later.
                    lock (_syncObj)
                        _state = SessionState.Ended;
                    return((int)BASSStreamProc.BASS_STREAMPROC_END);
                }
                _playbackProcessor.ClearNextInputSource(); // Should be the contents of newInputSource
                lock (_syncObj)
                {
                    _currentInputSource = newInputSource;
                    _state = SessionState.Playing;
                }

                // Next try
                return(OutputStreamWriteProc(streamHandle, buffer, requestedBytes, userData));
            }
            catch (Exception)
            {
                // We might come here due to a race condition. To avoid that, we would have to employ a new manual locking mechanism
                // to avoid that during the execution of this method, no methods are called from outside which change our
                // streams/partner instances.
                return(0);
            }
        }
Example #49
0
        public override void OnInspectorGUI()
        {
            var configurationProfile = (MixedRealityToolkitConfigurationProfile)target;

            serializedObject.Update();

            if (!RenderMRTKLogoAndSearch())
            {
                CheckEditorPlayMode();
                return;
            }

            CheckEditorPlayMode();

            if (!MixedRealityToolkit.IsInitialized)
            {
                EditorGUILayout.HelpBox("No Mixed Reality Toolkit found in scene.", MessageType.Warning);
                if (InspectorUIUtility.RenderIndentedButton("Add Mixed Reality Toolkit instance to scene"))
                {
                    MixedRealityInspectorUtility.AddMixedRealityToolkitToScene(configurationProfile);
                }
            }

            if (!configurationProfile.IsCustomProfile)
            {
                EditorGUILayout.HelpBox("The Mixed Reality Toolkit's core SDK profiles can be used to get up and running quickly.\n\n" +
                                        "You can use the default profiles provided, copy and customize the default profiles, or create your own.", MessageType.Warning);
                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("Copy & Customize"))
                {
                    SerializedProperty targetProperty  = null;
                    UnityEngine.Object selectionTarget = null;
                    // If we have an active MRTK instance, find its config profile serialized property
                    if (MixedRealityToolkit.IsInitialized)
                    {
                        selectionTarget = MixedRealityToolkit.Instance;
                        SerializedObject mixedRealityToolkitObject = new SerializedObject(MixedRealityToolkit.Instance);
                        targetProperty = mixedRealityToolkitObject.FindProperty("activeProfile");
                    }
                    MixedRealityProfileCloneWindow.OpenWindow(null, target as BaseMixedRealityProfile, targetProperty, selectionTarget);
                }

                if (MixedRealityToolkit.IsInitialized)
                {
                    if (GUILayout.Button("Create new profiles"))
                    {
                        ScriptableObject profile = CreateInstance(nameof(MixedRealityToolkitConfigurationProfile));
                        var newProfile           = profile.CreateAsset("Assets/MixedRealityToolkit.Generated/CustomProfiles") as MixedRealityToolkitConfigurationProfile;
                        UnityEditor.Undo.RecordObject(MixedRealityToolkit.Instance, "Create new profiles");
                        MixedRealityToolkit.Instance.ActiveProfile = newProfile;
                        Selection.activeObject = newProfile;
                    }
                }

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
            }

            bool isGUIEnabled = !IsProfileLock((BaseMixedRealityProfile)target) && GUI.enabled;

            GUI.enabled = isGUIEnabled;

            bool changed = false;

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Width(100));
            GUI.enabled = true; // Force enable so we can view profile defaults

            int prefsSelectedTab = SessionState.GetInt(SelectedTabPreferenceKey, 0);

            SelectedProfileTab = GUILayout.SelectionGrid(prefsSelectedTab, ProfileTabTitles, 1, GUILayout.MaxWidth(125));
            if (SelectedProfileTab != prefsSelectedTab)
            {
                SessionState.SetInt(SelectedTabPreferenceKey, SelectedProfileTab);
            }

            GUI.enabled = isGUIEnabled;
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            using (new EditorGUI.IndentLevelScope())
            {
                changed |= renderProfileFuncs[SelectedProfileTab]();
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            serializedObject.ApplyModifiedProperties();
            GUI.enabled = true;

            if (changed && MixedRealityToolkit.IsInitialized)
            {
                EditorApplication.delayCall += () => MixedRealityToolkit.Instance.ResetConfiguration(configurationProfile);
            }
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            if (multiLineHelpBoxStyle == null)
            {
                multiLineHelpBoxStyle          = new GUIStyle(EditorStyles.helpBox);
                multiLineHelpBoxStyle.wordWrap = true;
            }

            connectorTarget          = serializedObject.FindProperty("target");
            connectorFollowType      = serializedObject.FindProperty("connectorFollowType");
            pivotMode                = serializedObject.FindProperty("pivotMode");
            pivotDirection           = serializedObject.FindProperty("pivotDirection");
            pivotDirectionOrient     = serializedObject.FindProperty("pivotDirectionOrient");
            manualPivotDirection     = serializedObject.FindProperty("manualPivotDirection");
            manualPivotLocalPosition = serializedObject.FindProperty("manualPivotLocalPosition");
            pivotDistance            = serializedObject.FindProperty("pivotDistance");

            editorSettingsFoldout = EditorGUILayout.Foldout(editorSettingsFoldout, EditorSettingsContent, true);
            SessionState.SetBool(EditorSettingsFoldoutKey, editorSettingsFoldout);

            if (editorSettingsFoldout)
            {
                EditorGUI.BeginChangeCheck();
                DrawManualDirectionHandle = EditorGUILayout.Toggle("Draw Manual Direction Handle", DrawManualDirectionHandle);

                if (EditorGUI.EndChangeCheck())
                {
                    SessionState.SetBool(DrawManualDirectionHandleKey, DrawManualDirectionHandle);
                }
            }

            if (connectorTarget.objectReferenceValue == null)
            {
                EditorGUILayout.HelpBox("No target set. ToolTip will not use connector component.", MessageType.Info);
                EditorGUILayout.PropertyField(connectorTarget);
            }
            else
            {
                EditorGUILayout.PropertyField(connectorTarget);

                string helpText = string.Empty;
                switch (connector.ConnectorFollowingType)
                {
                case ConnectorFollowType.AnchorOnly:
                    helpText = "Only the tooltip's anchor will follow the target. Tooltip content will not be altered.";
                    break;

                case ConnectorFollowType.Position:
                    helpText = "The entire tooltip will follow the target. Tooltip will not rotate.";
                    break;

                case ConnectorFollowType.PositionAndYRotation:
                    helpText = "The entire tooltip will follow the target. Tooltip will match target's Y rotation.";
                    break;

                case ConnectorFollowType.PositionAndXYRotation:
                    helpText = "The entire tooltip will follow the target. Tooltip will match target's X and Y rotation.";
                    break;
                }

                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                EditorGUILayout.LabelField(helpText, EditorStyles.miniLabel);
                EditorGUILayout.EndVertical();
                EditorGUILayout.PropertyField(connectorFollowType);

                switch (connector.ConnectorFollowingType)
                {
                case ConnectorFollowType.AnchorOnly:
                    // Pivot mode doesn't apply to anchor-only connections
                    break;

                default:
                    EditorGUILayout.PropertyField(pivotMode);
                    switch (connector.PivotMode)
                    {
                    case ConnectorPivotMode.Manual:
                        // We just want to set the pivot ourselves
                        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                        EditorGUILayout.LabelField("Pivot will not be altered by connector.", EditorStyles.miniLabel);
                        EditorGUILayout.EndVertical();
                        break;

                    case ConnectorPivotMode.Automatic:
                        EditorGUILayout.PropertyField(pivotDirectionOrient);
                        switch (connector.PivotDirectionOrient)
                        {
                        case ConnectorOrientType.OrientToCamera:
                            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                            EditorGUILayout.LabelField("Pivot will be set in direction relative to camera.", EditorStyles.miniLabel);
                            EditorGUILayout.EndVertical();
                            break;

                        case ConnectorOrientType.OrientToObject:
                            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                            EditorGUILayout.LabelField("Pivot will be set in direction relative to target.", EditorStyles.miniLabel);
                            EditorGUILayout.EndVertical();
                            break;
                        }
                        ConnectorPivotDirection newPivotDirection = DrawPivotDirection(connector.PivotDirection);
                        pivotDirection.enumValueIndex = (int)newPivotDirection;
                        switch (connector.PivotDirection)
                        {
                        case ConnectorPivotDirection.Manual:
                            EditorGUILayout.PropertyField(manualPivotDirection);
                            break;

                        default:
                            break;
                        }
                        EditorGUILayout.PropertyField(pivotDistance);
                        break;

                    case ConnectorPivotMode.LocalPosition:
                        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                        EditorGUILayout.LabelField("Pivot will be set to position relative to target.", EditorStyles.miniLabel);
                        EditorGUILayout.EndVertical();
                        EditorGUILayout.PropertyField(manualPivotLocalPosition);
                        break;
                    }
                    break;
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
Example #51
0
        /// <summary>
        /// 更新服务端刷新令牌
        /// </summary>
        protected void SetRefreshServerToken()
        {
            string tokenPage = DateTime.Now.Ticks.ToString();

            SessionState.Set(UC_Page_Refresh, tokenPage);
        }
Example #52
0
 protected override ScriptResult Execute(string code, object globals, SessionState <ScriptState> sessionState)
 {
     return(ShouldCompile()
         ? CompileAndExecute(code, globals)
         : InvokeEntryPointMethod(globals, LoadAssemblyFromCache()));
 }
Example #53
0
        public void ToSubGraph()
        {
            var graphView = graphEditorView.graphView;

            string path;
            string sessionStateResult = SessionState.GetString(k_PrevSubGraphPathKey, k_PrevSubGraphPathDefaultValue);
            string pathToOriginSG     = Path.GetDirectoryName(AssetDatabase.GUIDToAssetPath(selectedGuid));

            SessionState.EraseString("HitlerMcFaggotFace");

            if (!sessionStateResult.Equals(k_PrevSubGraphPathDefaultValue))
            {
                path = sessionStateResult;
            }
            else
            {
                path = pathToOriginSG;
            }

            path = EditorUtility.SaveFilePanelInProject("Save Sub Graph", "New Shader Sub Graph", ShaderSubGraphImporter.Extension, "", path);
            path = path.Replace(Application.dataPath, "Assets");
            if (path.Length == 0)
            {
                return;
            }

            graphObject.RegisterCompleteObjectUndo("Convert To Subgraph");

            var nodes  = graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray();
            var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity);

            foreach (var node in nodes)
            {
                var center = node.drawState.position.center;
                bounds = Rect.MinMaxRect(
                    Mathf.Min(bounds.xMin, center.x),
                    Mathf.Min(bounds.yMin, center.y),
                    Mathf.Max(bounds.xMax, center.x),
                    Mathf.Max(bounds.yMax, center.y));
            }
            var middle = bounds.center;

            bounds.center = Vector2.zero;

            // Collect graph inputs
            var graphInputs = graphView.selection.OfType <BlackboardField>().Select(x => x.userData as ShaderInput);

            // Collect the property nodes and get the corresponding properties
            var propertyNodeGuids = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).propertyGuid);
            var metaProperties    = graphView.graph.properties.Where(x => propertyNodeGuids.Contains(x.guid));

            // Collect the keyword nodes and get the corresponding keywords
            var keywordNodeGuids = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is KeywordNode)).Select(x => ((KeywordNode)x.node).keywordGuid);
            var metaKeywords     = graphView.graph.keywords.Where(x => keywordNodeGuids.Contains(x.guid));

            var copyPasteGraph = new CopyPasteGraph(
                graphView.graph.assetGuid,
                graphView.selection.OfType <ShaderGroup>().Select(x => x.userData),
                graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(),
                graphView.selection.OfType <Edge>().Select(x => x.userData as IEdge),
                graphInputs,
                metaProperties,
                metaKeywords,
                graphView.selection.OfType <StickyNote>().Select(x => x.userData));

            var deserialized = CopyPasteGraph.FromJson(JsonUtility.ToJson(copyPasteGraph, false));

            if (deserialized == null)
            {
                return;
            }

            var subGraph = new GraphData {
                isSubGraph = true
            };

            subGraph.path = "Sub Graphs";
            var subGraphOutputNode = new SubGraphOutputNode();

            {
                var drawState = subGraphOutputNode.drawState;
                drawState.position           = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size);
                subGraphOutputNode.drawState = drawState;
            }
            subGraph.AddNode(subGraphOutputNode);

            // Always copy deserialized keyword inputs
            foreach (ShaderKeyword keyword in deserialized.metaKeywords)
            {
                ShaderInput copiedInput = keyword.Copy();
                subGraph.SanitizeGraphInputName(copiedInput);
                subGraph.SanitizeGraphInputReferenceName(copiedInput, keyword.overrideReferenceName);
                subGraph.AddGraphInput(copiedInput);

                // Update the keyword nodes that depends on the copied keyword
                var dependentKeywordNodes = deserialized.GetNodes <KeywordNode>().Where(x => x.keywordGuid == keyword.guid);
                foreach (var node in dependentKeywordNodes)
                {
                    node.owner       = graphView.graph;
                    node.keywordGuid = copiedInput.guid;
                }
            }

            var groupGuidMap = new Dictionary <Guid, Guid>();

            foreach (GroupData groupData in deserialized.groups)
            {
                var oldGuid = groupData.guid;
                var newGuid = groupData.RewriteGuid();
                groupGuidMap[oldGuid] = newGuid;
                subGraph.CreateGroup(groupData);
            }

            List <Guid> groupGuids  = new List <Guid>();
            var         nodeGuidMap = new Dictionary <Guid, Guid>();

            foreach (var node in deserialized.GetNodes <AbstractMaterialNode>())
            {
                var oldGuid = node.guid;
                var newGuid = node.RewriteGuid();
                nodeGuidMap[oldGuid] = newGuid;
                var drawState = node.drawState;
                drawState.position = new Rect(drawState.position.position - middle, drawState.position.size);
                node.drawState     = drawState;

                if (!groupGuids.Contains(node.groupGuid))
                {
                    groupGuids.Add(node.groupGuid);
                }

                // Checking if the group guid is also being copied.
                // If not then nullify that guid
                if (node.groupGuid != Guid.Empty)
                {
                    node.groupGuid = !groupGuidMap.ContainsKey(node.groupGuid) ? Guid.Empty : groupGuidMap[node.groupGuid];
                }

                subGraph.AddNode(node);
            }

            foreach (var note in deserialized.stickyNotes)
            {
                if (!groupGuids.Contains(note.groupGuid))
                {
                    groupGuids.Add(note.groupGuid);
                }

                if (note.groupGuid != Guid.Empty)
                {
                    note.groupGuid = !groupGuidMap.ContainsKey(note.groupGuid) ? Guid.Empty : groupGuidMap[note.groupGuid];
                }

                note.RewriteGuid();
                subGraph.AddStickyNote(note);
            }

            // figure out what needs remapping
            var externalOutputSlots = new List <IEdge>();
            var externalInputSlots  = new List <IEdge>();

            foreach (var edge in deserialized.edges)
            {
                var outputSlot = edge.outputSlot;
                var inputSlot  = edge.inputSlot;

                Guid remappedOutputNodeGuid;
                Guid remappedInputNodeGuid;
                var  outputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(outputSlot.nodeGuid, out remappedOutputNodeGuid);
                var  inputSlotExistsInSubgraph  = nodeGuidMap.TryGetValue(inputSlot.nodeGuid, out remappedInputNodeGuid);

                // pasting nice internal links!
                if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph)
                {
                    var outputSlotRef = new SlotReference(remappedOutputNodeGuid, outputSlot.slotId);
                    var inputSlotRef  = new SlotReference(remappedInputNodeGuid, inputSlot.slotId);
                    subGraph.Connect(outputSlotRef, inputSlotRef);
                }
                // one edge needs to go to outside world
                else if (outputSlotExistsInSubgraph)
                {
                    externalInputSlots.Add(edge);
                }
                else if (inputSlotExistsInSubgraph)
                {
                    externalOutputSlots.Add(edge);
                }
            }

            // Find the unique edges coming INTO the graph
            var uniqueIncomingEdges = externalOutputSlots.GroupBy(
                edge => edge.outputSlot,
                edge => edge,
                (key, edges) => new { slotRef = key, edges = edges.ToList() });

            var externalInputNeedingConnection = new List <KeyValuePair <IEdge, AbstractShaderProperty> >();

            var       amountOfProps  = uniqueIncomingEdges.Count();
            const int height         = 40;
            const int subtractHeight = 20;
            var       propPos        = new Vector2(0, -((amountOfProps / 2) + height) - subtractHeight);

            foreach (var group in uniqueIncomingEdges)
            {
                var sr       = group.slotRef;
                var fromNode = graphObject.graph.GetNodeFromGuid(sr.nodeGuid);
                var fromSlot = fromNode.FindOutputSlot <MaterialSlot>(sr.slotId);

                AbstractShaderProperty prop;
                switch (fromSlot.concreteValueType)
                {
                case ConcreteSlotValueType.Texture2D:
                    prop = new Texture2DShaderProperty();
                    break;

                case ConcreteSlotValueType.Texture2DArray:
                    prop = new Texture2DArrayShaderProperty();
                    break;

                case ConcreteSlotValueType.Texture3D:
                    prop = new Texture3DShaderProperty();
                    break;

                case ConcreteSlotValueType.Cubemap:
                    prop = new CubemapShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector4:
                    prop = new Vector4ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector3:
                    prop = new Vector3ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector2:
                    prop = new Vector2ShaderProperty();
                    break;

                case ConcreteSlotValueType.Vector1:
                    prop = new Vector1ShaderProperty();
                    break;

                case ConcreteSlotValueType.Boolean:
                    prop = new BooleanShaderProperty();
                    break;

                case ConcreteSlotValueType.Matrix2:
                    prop = new Matrix2ShaderProperty();
                    break;

                case ConcreteSlotValueType.Matrix3:
                    prop = new Matrix3ShaderProperty();
                    break;

                case ConcreteSlotValueType.Matrix4:
                    prop = new Matrix4ShaderProperty();
                    break;

                case ConcreteSlotValueType.SamplerState:
                    prop = new SamplerStateShaderProperty();
                    break;

                case ConcreteSlotValueType.Gradient:
                    prop = new GradientShaderProperty();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (prop != null)
                {
                    var materialGraph    = (GraphData)graphObject.graph;
                    var fromPropertyNode = fromNode as PropertyNode;
                    var fromProperty     = fromPropertyNode != null?materialGraph.properties.FirstOrDefault(p => p.guid == fromPropertyNode.propertyGuid) : null;

                    prop.displayName = fromProperty != null ? fromProperty.displayName : fromSlot.concreteValueType.ToString();
                    prop.displayName = GraphUtil.SanitizeName(subGraph.addedInputs.Select(p => p.displayName), "{0} ({1})", prop.displayName);

                    subGraph.AddGraphInput(prop);
                    var propNode = new PropertyNode();
                    {
                        var drawState = propNode.drawState;
                        drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f) + propPos, drawState.position.size);
                        propPos           += new Vector2(0, height);
                        propNode.drawState = drawState;
                    }
                    subGraph.AddNode(propNode);
                    propNode.propertyGuid = prop.guid;

                    foreach (var edge in group.edges)
                    {
                        subGraph.Connect(
                            new SlotReference(propNode.guid, PropertyNode.OutputSlotId),
                            new SlotReference(nodeGuidMap[edge.inputSlot.nodeGuid], edge.inputSlot.slotId));
                        externalInputNeedingConnection.Add(new KeyValuePair <IEdge, AbstractShaderProperty>(edge, prop));
                    }
                }
            }

            var uniqueOutgoingEdges = externalInputSlots.GroupBy(
                edge => edge.outputSlot,
                edge => edge,
                (key, edges) => new { slot = key, edges = edges.ToList() });

            var externalOutputsNeedingConnection = new List <KeyValuePair <IEdge, IEdge> >();

            foreach (var group in uniqueOutgoingEdges)
            {
                var outputNode = subGraph.outputNode as SubGraphOutputNode;

                AbstractMaterialNode node = graphView.graph.GetNodeFromGuid(group.edges[0].outputSlot.nodeGuid);
                MaterialSlot         slot = node.FindSlot <MaterialSlot>(group.edges[0].outputSlot.slotId);
                var slotId = outputNode.AddSlot(slot.concreteValueType);

                var inputSlotRef = new SlotReference(outputNode.guid, slotId);

                foreach (var edge in group.edges)
                {
                    var newEdge = subGraph.Connect(new SlotReference(nodeGuidMap[edge.outputSlot.nodeGuid], edge.outputSlot.slotId), inputSlotRef);
                    externalOutputsNeedingConnection.Add(new KeyValuePair <IEdge, IEdge>(edge, newEdge));
                }
            }

            if (FileUtilities.WriteShaderGraphToDisk(path, subGraph))
            {
                AssetDatabase.ImportAsset(path);
            }

            // Store path for next time
            if (!pathToOriginSG.Equals(Path.GetDirectoryName(path)))
            {
                SessionState.SetString(k_PrevSubGraphPathKey, Path.GetDirectoryName(path));
            }
            else
            {
                // Or continue to make it so that next time it will open up in the converted-from SG's directory
                SessionState.EraseString(k_PrevSubGraphPathKey);
            }

            var loadedSubGraph = AssetDatabase.LoadAssetAtPath(path, typeof(SubGraphAsset)) as SubGraphAsset;

            if (loadedSubGraph == null)
            {
                return;
            }

            var subGraphNode = new SubGraphNode();
            var ds           = subGraphNode.drawState;

            ds.position            = new Rect(middle - new Vector2(100f, 150f), Vector2.zero);
            subGraphNode.drawState = ds;

            // Add the subgraph into the group if the nodes was all in the same group group
            if (groupGuids.Count == 1)
            {
                subGraphNode.groupGuid = groupGuids[0];
            }

            graphObject.graph.AddNode(subGraphNode);
            subGraphNode.asset = loadedSubGraph;

            foreach (var edgeMap in externalInputNeedingConnection)
            {
                graphObject.graph.Connect(edgeMap.Key.outputSlot, new SlotReference(subGraphNode.guid, edgeMap.Value.guid.GetHashCode()));
            }

            foreach (var edgeMap in externalOutputsNeedingConnection)
            {
                graphObject.graph.Connect(new SlotReference(subGraphNode.guid, edgeMap.Value.inputSlot.slotId), edgeMap.Key.inputSlot);
            }

            graphObject.graph.RemoveElements(
                graphView.selection.OfType <IShaderNodeView>().Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(),
                new IEdge[] {},
                new GroupData[] {},
                graphView.selection.OfType <StickyNote>().Select(x => x.userData).ToArray());
            graphObject.graph.ValidateGraph();
        }
Example #54
0
        public void StartHost(string profilePath, string logFolder, ILogger outputLogger, LogVerbosity verbosity)
        {
            if (_hostEnd != null)
            {
                throw new InvalidOperationException("Host process is already running");
            }

            var useridentity = User as WindowsIdentity;
            // In remote broker User Identity type is always WindowsIdentity
            string suppressUI     = (useridentity == null) ? string.Empty : "--rhost-suppress-ui ";
            string isRepl         = Id.StartsWithIgnoreCase("REPL") ? "--rhost-interactive " : string.Empty;
            string brokerPath     = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath   = Path.Combine(brokerPath, RHostExe);
            string logFolderParam = string.IsNullOrEmpty(logFolder) ? string.Empty : Invariant($"--rhost-log-dir \"{logFolder}\"");
            string commandLine    = Invariant($"\"{rhostExePath}\" {suppressUI}{isRepl}--rhost-name \"{Id}\" {logFolderParam} --rhost-log-verbosity {(int)verbosity} {CommandLineArguments}");
            var    usernameBldr   = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
            var    domainBldr     = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);

            // Get R_HOME value
            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(Interpreter.Info.Path, shortHome, shortHome.Capacity);

            Stream stdout, stdin, stderror;
            bool   loggedOnUser = useridentity != null && WindowsIdentity.GetCurrent().User != useridentity.User;

            // build user environment block
            Win32EnvironmentBlock eb;

            if (loggedOnUser)
            {
                uint error = NativeMethods.CredUIParseUserName(User.Name, usernameBldr, usernameBldr.Capacity, domainBldr, domainBldr.Capacity);
                if (error != 0)
                {
                    _sessionLogger.LogError(Resources.Error_UserNameParse, User.Name, error);
                    throw new ArgumentException(Resources.Error_UserNameParse.FormatInvariant(User.Name, error));
                }

                string username = usernameBldr.ToString();
                string domain   = domainBldr.ToString();

                eb = CreateEnvironmentBlockForUser(useridentity, username, profilePath);
            }
            else
            {
                eb = Win32EnvironmentBlock.Create((useridentity ?? WindowsIdentity.GetCurrent()).Token);
            }

            // add additional variables to the environment block
            eb["R_HOME"] = shortHome.ToString();
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "R_HOME", eb["R_HOME"]);
            eb["PATH"] = Invariant($"{Interpreter.Info.BinPath};{Environment.GetEnvironmentVariable("PATH")}");
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "PATH", eb["PATH"]);


            _sessionLogger.LogInformation(Resources.Info_StartingRHost, Id, User.Name, commandLine);
            using (Win32NativeEnvironmentBlock nativeEnv = eb.GetNativeEnvironmentBlock()) {
                if (loggedOnUser)
                {
                    _process = Win32Process.StartProcessAsUser(useridentity, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
                else
                {
                    _process = Win32Process.StartProcessAsUser(null, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
            }

            _process.Exited += delegate(object o, Win32ProcessExitEventArgs exitState){
                _hostEnd?.Dispose();
                _hostEnd = null;
                State    = SessionState.Terminated;
                if (exitState.HasError())
                {
                    _sessionLogger.LogInformation(Resources.Error_ExitRHost, exitState.ExitCode);
                }
            };

            _process.WaitForExit(250);
            if (_process.HasExited && _process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(_process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new Win32Exception(message);
                }
                throw new Win32Exception(_process.ExitCode);
            }

            _sessionLogger.LogInformation(Resources.Info_StartedRHost, Id, User.Name);

            var hostEnd = _pipe.ConnectHost(_process.ProcessId);

            _hostEnd = hostEnd;

            ClientToHostWorker(stdin, hostEnd).DoNotWait();
            HostToClientWorker(stdout, hostEnd).DoNotWait();

            HostToClientErrorWorker(stderror, _process.ProcessId, (int processid, string errdata) => {
                outputLogger?.LogTrace(Resources.Trace_ErrorDataReceived, processid, errdata);
            }).DoNotWait();
        }
 /// <summary>
 /// Tries to get the data previously stored with the specified key.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 /// <returns>
 /// true if found; false otherwise
 /// </returns>
 public bool TryGet(string key, out object value)
 {
     return(SessionState.TryGetValue(key, out value));
 }
Example #56
0
 /// <summary>
 /// Saves the state of the section from SessionState.
 /// </summary>
 public void SaveState()
 {
     SessionState.SetString(SessionStateKey, TutorialCompleted ? "Finished" : "");
 }
Example #57
0
        /// <summary>
        /// Gets the matching variable for the specified name, using the
        /// Include, Exclude, and Scope parameters defined in the base class.
        /// </summary>
        /// <param name="name">
        /// The name or pattern of the variables to retrieve.
        /// </param>
        /// <param name="lookupScope">
        /// The scope to do the lookup in. If null or empty the normal scoping rules apply.
        /// </param>
        /// <param name="wasFiltered">
        /// True is returned if a variable exists of the given name but was filtered
        /// out via globbing, include, or exclude.
        /// </param>
        /// <param name="quiet">
        /// If true, don't report errors when trying to access private variables.
        /// </param>
        /// <returns>
        /// A collection of the variables matching the name, include, and exclude
        /// pattern in the specified scope.
        /// </returns>
        internal List <PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet)
        {
            wasFiltered = false;

            List <PSVariable> result = new List <PSVariable>();

            if (String.IsNullOrEmpty(name))
            {
                name = "*";
            }

            bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name);

            // Now create the filters

            WildcardPattern nameFilter =
                WildcardPattern.Get(
                    name,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> includeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _include,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> excludeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _exclude,
                    WildcardOptions.IgnoreCase);

            if (!nameContainsWildcard)
            {
                // Filter the name here against the include and exclude so that
                // we can report if the name was filtered vs. there being no
                // variable existing of that name.

                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        excludeFilters,
                        false);

                if (!isIncludeMatch || isExcludeMatch)
                {
                    wasFiltered = true;
                    return(result);
                }
            }

            // First get the appropriate view of the variables. If no scope
            // is specified, flatten all scopes to produce a currently active
            // view.

            IDictionary <string, PSVariable> variableTable = null;

            if (String.IsNullOrEmpty(lookupScope))
            {
                variableTable = SessionState.Internal.GetVariableTable();
            }
            else
            {
                variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope);
            }

            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (KeyValuePair <string, PSVariable> entry in variableTable)
            {
                bool isNameMatch    = nameFilter.IsMatch(entry.Key);
                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        excludeFilters,
                        false);

                if (isNameMatch)
                {
                    if (isIncludeMatch && !isExcludeMatch)
                    {
                        // See if the variable is visible
                        if (!SessionState.IsVisible(origin, entry.Value))
                        {
                            // In quiet mode, don't report private variable accesses unless they are specific matches...
                            if (quiet || nameContainsWildcard)
                            {
                                wasFiltered = true;
                                continue;
                            }
                            else
                            {
                                // Generate an error for elements that aren't visible...
                                try
                                {
                                    SessionState.ThrowIfNotVisible(origin, entry.Value);
                                }
                                catch (SessionStateException sessionStateException)
                                {
                                    WriteError(
                                        new ErrorRecord(
                                            sessionStateException.ErrorRecord,
                                            sessionStateException));
                                    // Only report the error once...
                                    wasFiltered = true;
                                    continue;
                                }
                            }
                        }
                        result.Add(entry.Value);
                    }
                    else
                    {
                        wasFiltered = true;
                    }
                }
                else
                {
                    if (nameContainsWildcard)
                    {
                        wasFiltered = true;
                    }
                }
            }
            return(result);
        }
Example #58
0
        /// <summary>
        /// Gets the item(s) at the given path.
        /// </summary>
        /// <param name="path">
        /// The name of the item to retrieve, or all if empty or null.
        /// </param>
        /// <param name="recurse">
        /// Ignored.
        /// </param>
        protected override void GetChildItems(string path, bool recurse)
        {
            CommandOrigin origin = this.Context.Origin;

            if (string.IsNullOrEmpty(path))
            {
                IDictionary dictionary = null;

                try
                {
                    dictionary = GetSessionStateTable();
                }
                catch (SecurityException e)
                {
                    WriteError(
                        new ErrorRecord(
                            e,
                            "GetTableSecurityException",
                            ErrorCategory.ReadError,
                            path));
                    return;
                }

                // bug Windows7 #300974 says that we should sort
                List <DictionaryEntry> sortedEntries = new List <DictionaryEntry>(dictionary.Count + 1);
                foreach (DictionaryEntry entry in dictionary)
                {
                    sortedEntries.Add(entry);
                }

                sortedEntries.Sort(
                    delegate(DictionaryEntry left, DictionaryEntry right)
                {
                    string leftKey  = (string)left.Key;
                    string rightKey = (string)right.Key;
                    IComparer <string> stringComparer = StringComparer.CurrentCultureIgnoreCase;
                    return(stringComparer.Compare(leftKey, rightKey));
                });

                // Now write out each object
                foreach (DictionaryEntry entry in sortedEntries)
                {
                    try
                    {
                        if (SessionState.IsVisible(origin, entry.Value))
                        {
                            WriteItemObject(entry.Value, (string)entry.Key, false);
                        }
                    }
                    catch (PSArgumentException argException)
                    {
                        WriteError(
                            new ErrorRecord(
                                argException.ErrorRecord,
                                argException));

                        return;
                    }
                    catch (SecurityException securityException)
                    {
                        WriteError(
                            new ErrorRecord(
                                securityException,
                                "GetItemSecurityException",
                                ErrorCategory.PermissionDenied,
                                (string)entry.Key));
                        return;
                    }
                }
            }
            else
            {
                object item = null;

                try
                {
                    item = GetSessionStateItem(path);
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));

                    return;
                }
                catch (SecurityException securityException)
                {
                    WriteError(
                        new ErrorRecord(
                            securityException,
                            "GetItemSecurityException",
                            ErrorCategory.PermissionDenied,
                            path));
                    return;
                }

                if (item != null)
                {
                    if (SessionState.IsVisible(origin, item))
                    {
                        WriteItemObject(item, path, false);
                    }
                }
            }
        }
Example #59
0
 private void BTN_Start_Data_Collection_Click(object sender, EventArgs e)
 {
     // S
     CurrentSessionState = SessionState.Subject_Data_Entry;
 }
Example #60
0
 private void FM_MRI_TIming_File_Main_Load(object sender, EventArgs e)
 {
     this.KeyPreview     = true;
     this.KeyPress      += Key_Keydown;
     CurrentSessionState = SessionState.Subject_Data_Entry;
 }