示例#1
0
 private void startButton_Click(object sender, EventArgs e)
 {
     endTime = DateTime.Now.AddMinutes(20);
     timer.Start();
     appState = AppState.Running;
     UpdateTexts();
 }
示例#2
0
  private void LoadMarkupCategories(Configuration.ApplicationRow application, AppState appState, OleDbConnection connection)
  {
    bool selected = false;

    foreach (Configuration.ApplicationMarkupCategoryRow link in application.GetApplicationMarkupCategoryRows())
    {
      string roles = link.MarkupCategoryRow.IsAuthorizedRolesNull() ? "public" : link.MarkupCategoryRow.AuthorizedRoles;

      if (AppUser.RoleIsInList(roles, connection))
      {
        HtmlGenericControl option = new HtmlGenericControl("option");
        option.Attributes["value"] = link.CategoryID;
        option.InnerText = link.MarkupCategoryRow.DisplayName;

        if (link.CategoryID == appState.MarkupCategory)
        {
          option.Attributes["selected"] = "selected";
          selected = true;
        }

        ddlMarkupCategory.Controls.Add(option);
      }
    }

    if (!selected)
    {
      appState.MarkupCategory = "";
      appState.MarkupGroups = new StringCollection();

      if (ddlMarkupCategory.Controls.Count > 0)
      {
        appState.MarkupCategory = ((HtmlGenericControl)ddlMarkupCategory.Controls[0]).Attributes["value"];
      }
    }
  }
示例#3
0
 private void Form1_Load(object sender, EventArgs e)
 {
     appState = AppState.Initial;
     timer.Interval = 1000;
     timer.Tick += timer_Tick;
     UpdateTexts();
 }
示例#4
0
 public AppInfo(
     string aName,
     AppState aState,
     bool aPendingUpdate,
     bool aPendingDelete,
     string aUdn,
     string aFriendlyName,
     bool aAutoUpdate,
     string aUpdateUrl,
     string aIconUrl,
     AppVersion aVersion,
     DateTime? aDownloadLastModified,
     bool aIsSystemApp)
 {
     Name = aName;
     State = aState;
     PendingUpdate = aPendingUpdate;
     PendingDelete = aPendingDelete;
     Udn = aUdn;
     FriendlyName = aFriendlyName;
     AutoUpdate = aAutoUpdate;
     UpdateUrl = aUpdateUrl;
     IconUrl = aIconUrl;
     Version = aVersion;
     DownloadLastModified = aDownloadLastModified;
     IsSystemApp = aIsSystemApp;
 }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed += Smtc_ButtonPressed;
            smtc.PropertyChanged += Smtc_PropertyChanged;
            smtc.IsEnabled = true;
            smtc.IsPauseEnabled = true;
            smtc.IsPlayEnabled = true;
            smtc.IsNextEnabled = true;
            smtc.IsPreviousEnabled = true;
            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);
            if (value == null)
                foregroundAppState = AppState.Unknown;
            else
                foregroundAppState = EnumHelper.Parse<AppState>(value.ToString());
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            if (foregroundAppState != AppState.Suspended)
                MessageService.SendMessageToForeground(new BackgroundTaskStateChangedMessage(BackgroundTaskState.Running));

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());

            deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it
            ReadytoConfirmFiles();

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)

            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
示例#6
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            appState = AppState.OFFLINE;

            this.InitializeComponent();
            this.Suspending += OnSuspending;
            this.Resuming += App_Resuming;
        }
示例#7
0
文件: PdfMap.cs 项目: ClaireBrill/GPV
  public PdfMap(AppState appState, string templateId, List<String> input, PreserveMode preserveMode, double originalWidth)
	{
		_appState = appState;
		_templateId = templateId;
    _input = input;
		_preserveMode = preserveMode;
		_originalWidth = originalWidth;
	}
示例#8
0
 /// <summary>
 /// 设置程序状态
 /// </summary>
 /// <param name="state"></param>
 void SetAppState(AppState state)
 {
     appState = state;
     this.btnStart.Enabled = (appState == AppState.Stoped);
     this.btnStop.Enabled = (appState == AppState.Started);
     this.txtBindAddr.Enabled = (appState == AppState.Stoped);
     this.txtBindPort.Enabled = (appState == AppState.Stoped);
     this.txtTargetAddr.Enabled = (appState == AppState.Stoped);
     this.txtTargetPort.Enabled = (appState == AppState.Stoped);
     this.txtDisConn.Enabled = (appState == AppState.Started);
     this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
 }
示例#9
0
 private void stopButton_Click(object sender, EventArgs e)
 {
     switch (appState)
     {
         case AppState.Initial:
         case AppState.Stopped:
             Application.Exit();
             break;
         case AppState.Running:
         case AppState.Alarming:
             timer.Stop();
             appState = AppState.Stopped;
             break;
     }
     UpdateTexts();
 }
示例#10
0
  public void Initialize(Configuration config, AppState appState, Configuration.ApplicationRow application)
  {
    using (OleDbConnection connection = AppContext.GetDatabaseConnection())
    {
      LoadMarkupCategories(application, appState, connection);

      if (AppAuthentication.Mode != AuthenticationMode.None)
      {
        tboMarkupUser.Attributes["value"] = AppUser.GetDisplayName(connection);
        tboMarkupUser.Attributes["disabled"] = "disabled";
        chkMarkupLock.Style["visibility"] = "visible";
        labMarkupLock.Style["visibility"] = "visible";
        cmdNewMarkup.Attributes["class"] = "CommandLink";
      }
    }
  }
示例#11
0
        public static void ResetCoordinates()
        {
            Globals.X1 = 0.00;
            Globals.Y1 = 0.00;

            Globals.X2 = 0.00;
            Globals.Y2 = 0.00;

            Globals.X3 = 0.00;
            Globals.Y3 = 0.00;

            Globals.X4 = 0.00;
            Globals.Y4 = 0.00;

            setCoordinates = false;
            appState = AppState.firstCoordinate;
        }
        /// <summary>
        /// Registers the notification.
        /// </summary>
        /// <param name="appState">State of the application.</param>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">AnalyticsNotifications Service URL setting is null or empty</exception>
        public void RegisterNotification(AppState appState)
        {
            try
            {
                //Adding to group by projectId
                Nlog.Log(LogLevel.Trace, "PC Web - Start addining connection into group");
                Groups.Add(Context.ConnectionId, appState.ProjectId.ToString(CultureInfo.InvariantCulture));
                Nlog.Log(LogLevel.Trace, "PC Web - Connection added to group");

                if (BaseApiController.IsMockMode())
                {
                    MockWorkflowState.WorkflowStateChanged += OnMockWorkflowStateChanged;
                }
                else
                {
                    Nlog.Log(LogLevel.Trace, "PC Web - Fired RegisterNotification");
                    var serviceUri = ConfigurationManager.AppSettings.Get(AnalyticsNotifications);
                    if (String.IsNullOrEmpty(serviceUri))
                    {
                        throw new ConfigurationErrorsException("AnalyticsNotifications Service URL setting is null or empty");
                    }
                    var hubConnection = new HubConnection(serviceUri);
                    var serviceHubProxy = hubConnection.CreateHubProxy("WorkflowStateServiceHub");

                    //Handle incoming calls from service
                    //BroadcastWorkflowState for updated project
                    serviceHubProxy.On<long, List<AnalyticsWorkflowState>>("UpdateWorkflowState", BroadcastWorkflowState);

                    //Signalr service connection 
                    Nlog.Log(LogLevel.Trace, "PC Web - Starting service signalr connection");
                    hubConnection.Start().ContinueWith(task => {}).Wait();
                    Nlog.Log(LogLevel.Trace, "PC Web - Service signalr connection success");

                    //Register for notifications
                    Nlog.Log(LogLevel.Trace, "PC Web - Invoking service signalr RegisterNotification");
                    serviceHubProxy.Invoke("RegisterNotification", appState.MatterId, appState.ProjectId)
                        .ContinueWith(task =>{}).Wait();
                    Nlog.Log(LogLevel.Trace, "PC Web - Invoked service signalr RegisterNotification");
                }
            }
            catch (Exception ex)
            {
                Nlog.Log(LogLevel.Error, ex.GetBaseException());
            }
        }
示例#13
0
 void timer_Tick(object sender, EventArgs e)
 {
     switch (appState)
     {
         case AppState.Running:
             var remainingTime = (DateTime.Now - endTime);
             timeDisplay.Text = remainingTime.ToString("mm\\:ss");
             if (remainingTime.TotalSeconds >= 0)
             {
                 appState = AppState.Alarming;
                 UpdateTexts();
             }
             break;
         case AppState.Alarming:
             System.Media.SystemSounds.Beep.Play();
             break;
     }
 }
示例#14
0
  private void Initialize(AppState appState, int width, int height, double resolution)
  {
    _appState = appState;
    _width = width;
    _height = height;
    _resolution = resolution;

    if (_width * _resolution > 2048)
    {
      _resolution *= 2048 / (_resolution * _width);
    }

    if (_height * _resolution > 2048)
    {
      _resolution *= 2048 / (_resolution * _height);
    }

    _extent = _appState.Extent;
    _extent.Reaspect(_width, _height);
    _transform = new AffineTransformation(_width, _height, _extent);
  }
		internal XNALogic(Application parent, object host, out Microsoft.Xna.Framework.GamerServices.GamerServicesComponent gamerServicesComponent)
		{
			this.state = new AppState(parent);
			this.parent = parent;

			parent.UpdateManager.Add(state);
			parent.UpdateManager.Add(parent);

			gamerServicesComponent = null;

			if (host is GameComponentHost)
			{
				this.xnaGame = new XNAGameComponentHostAppWrapper(this, parent, host as GameComponentHost);
			}
			else
			{
#if !XBOX360
				if (host == null)
				{
					this.xnaGame = new XNAGameAppWrapper(this, parent, out gamerServicesComponent);
				}
				//else
				//{
				//    WinFormsHostControl _host = host as WinFormsHostControl;
				//    if (_host != null)
				//        this.xnaGame = new XNAWinFormsHostAppWrapper(this, parent, _host);
				//    else
				//        this.xnaGame = new XNAGameAppWrapper(this, parent, out gamerServicesComponent);
				//}
#else
				this.xnaGame = new XNAGameAppWrapper(this, parent, out gamerServicesComponent);
#endif
			}

			this.Exiting += delegate
			{
				Xen.Graphics.Resource.ClearResourceTracking();
			};
		}
示例#16
0
 /// <summary>
 /// 设置程序状态
 /// </summary>
 /// <param name="state"></param>
 void SetAppState(AppState state)
 {
     appState = state;
     this.btnStart.Enabled = (appState == AppState.Stoped);
     this.btnStop.Enabled = (appState == AppState.Started);
     this.txtIpAddress.Enabled = (appState == AppState.Stoped);
     this.txtPort.Enabled = (appState == AppState.Stoped);
     this.txtDisConn.Enabled = (appState == AppState.Started);
     this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
 }
        /// <summary>
        /// The Run method is the entry point of a background task. 
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");

            // Initialize SystemMediaTransportControls (SMTC) for integration with
            // the Universal Volume Control (UVC).
            //
            // The UI for the UVC must update even when the foreground process has been terminated
            // and therefore the SMTC is configured and updated from the background task.
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed += smtc_ButtonPressed;
            smtc.PropertyChanged += smtc_PropertyChanged;
            smtc.IsEnabled = true;
            smtc.IsPauseEnabled = true;
            smtc.IsPlayEnabled = true;
            smtc.IsNextEnabled = true;
            smtc.IsPreviousEnabled = true;

            // Read persisted state of foreground app
            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);
            if (value == null)
                foregroundAppState = AppState.Unknown;
            else
                foregroundAppState = EnumHelper.Parse<AppState>(value.ToString());

            // Add handlers for MediaPlayer
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            // Initialize message channel 
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            // Send information to foreground that background task has been started if app is active
            if (foregroundAppState != AppState.Suspended)
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());

            deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
            backgroundTaskStarted.Set();
            
            smtc.PlaybackStatus = MediaPlaybackStatus.Stopped;
            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // event may raise immediately before continung thread excecution so must be at the end
        }
示例#18
0
        /// <summary>
        /// 初始化设备列表信息
        /// </summary>
        static NvrTable()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "Config\\";

            m_storageType = (AppState.GetConfigSetting(m_storageTypeKey) != null) ? StorageTypesConverter.GetStorageType(AppState.GetConfigSetting(m_storageTypeKey)) : StorageTypes.Unknown;
            m_connStr     = AppState.GetConfigSetting(m_connStrKey);
            if (m_storageType == StorageTypes.SQLite)
            {
                m_connStr = string.Format(m_connStr, path);
            }
            if (m_storageType == StorageTypes.Unknown || m_connStr.IsNullOrBlank())
            {
                throw new ApplicationException("The SIP Registrar cannot start with no persistence settings.");
            }
        }
        public override void AdvanceDemo()
        {
            switch (currentAppState)
            {
            case AppState.DemoStepCreateSession:
                CloudManager.ResetSessionStatusIndicators();
                currentAnchorId    = "";
                currentCloudAnchor = null;
                currentAppState    = AppState.DemoStepConfigSession;
                break;

            case AppState.DemoStepConfigSession:
                ConfigureSession();
                currentAppState = AppState.DemoStepStartSession;
                break;

            case AppState.DemoStepStartSession:
                CloudManager.EnableProcessing = true;
                currentAppState = AppState.DemoStepCreateLocalAnchor;
                break;

            case AppState.DemoStepCreateLocalAnchor:
                if (spawnedObject != null)
                {
                    currentAppState = AppState.DemoStepSaveCloudAnchor;
                }
                break;

            case AppState.DemoStepSaveCloudAnchor:
                currentAppState = AppState.DemoStepSavingCloudAnchor;
                SaveCurrentObjectAnchorToCloud();
                break;

            case AppState.DemoStepStopSession:
                CloudManager.EnableProcessing = false;
                CleanupSpawnedObjects();
                CloudManager.ResetSession();
                currentAppState = AppState.DemoStepCreateSessionForQuery;
                break;

            case AppState.DemoStepCreateSessionForQuery:
                ConfigureSession();
                currentAppState = AppState.DemoStepStartSessionForQuery;
                break;

            case AppState.DemoStepStartSessionForQuery:
                CloudManager.EnableProcessing = true;
                currentAppState = AppState.DemoStepLookForAnchor;
                break;

            case AppState.DemoStepLookForAnchor:
                currentAppState = AppState.DemoStepLookingForAnchor;
                currentWatcher  = CloudManager.CreateWatcher();
                break;

            case AppState.DemoStepLookingForAnchor:
                break;

            case AppState.DemoStepDeleteFoundAnchor:
                Task.Run(async() =>
                {
                    await CloudManager.DeleteAnchorAsync(currentCloudAnchor);
                    currentCloudAnchor = null;
                });
                currentAppState = AppState.DemoStepStopSessionForQuery;
                CleanupSpawnedObjects();
                break;

            case AppState.DemoStepStopSessionForQuery:
                CloudManager.EnableProcessing = false;
                currentWatcher  = null;
                currentAppState = AppState.DemoStepComplete;
                break;

            case AppState.DemoStepComplete:
                currentCloudAnchor = null;
                currentAppState    = AppState.DemoStepCreateSession;
                CleanupSpawnedObjects();
                break;

            default:
                Debug.Log("Shouldn't get here for app state " + currentAppState.ToString());
                break;
            }
        }
示例#20
0
    IEnumerator OnSceneLoadedRoutine()
    {
        Dbg.LogRelease(this, "APP: Scene loaded");

        while (!readyForSceneLoad)
        {
            yield return(null);
        }

        Scene activeScene = SceneManager.GetActiveScene();

        if (activeScene.name == splashSceneName)
        {
            Dbg.LogRelease(this, "APP: Scene was splash");

            // Null here already because after this we're done
            setupRoutine = null;

            for (int buildIndex = 0; buildIndex < SceneManager.sceneCountInBuildSettings; ++buildIndex)
            {
                string sceneName      = Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(buildIndex));
                bool   validSceneName =
                    !string.IsNullOrEmpty(sceneName) &&
                    sceneName != loadingSceneName &&
                    sceneName != splashSceneName
                ;
                if (validSceneName)
                {
                    Dbg.LogRelease(this, "APP: Found first scene \"{0}\"", sceneName);
                    LoadScene(sceneName);
                    yield break;
                }
            }

            Dbg.LogErrorRelease(this, "APP: Did not find a first scene to load");
            yield break;
        }

        Dbg.LogRelease(this, "APP: Disabling Gravity");
        Vector3 gravityToRestore = Physics.gravity;

        Physics.gravity = Vector3.zero;

        AppState appState = FindAndInitializeAppState();

        if (appState != null)
        {
            while (!appState.readyForSetup)
            {
                yield return(null);
            }

            currentAppState = appState;

            try
            {
                currentAppState.AtSetup();
            }
            catch (Exception exc)
            {
                Dbg.LogExcRelease(exc);
                Dbg.LogErrorRelease(this, "APP: State setup failed");

                UE.Debug.Break();
            }
        }

        Dbg.LogRelease(this, "APP: Restoring Gravity");
        Physics.gravity = gravityToRestore;
        setupRoutine    = null;
    }
示例#21
0
        // Activate weird delegates

        protected override async Task MigrateContext(AppState state)
        {
            var block = await Cache.Blocks.CurrentAsync();

            var protocol = await Cache.Protocols.GetAsync(block.ProtoCode);

            var weirdDelegates = (await Db.Contracts
                                  .AsNoTracking()
                                  .Include(x => x.WeirdDelegate)
                                  .Where(x =>
                                         x.DelegateId == null &&
                                         x.WeirdDelegateId != null &&
                                         x.WeirdDelegate.Balance > 0)
                                  .Select(x => new
            {
                Contract = x,
                Delegate = x.WeirdDelegate
            })
                                  .ToListAsync())
                                 .GroupBy(x => x.Delegate.Id);

            var activatedDelegates = new Dictionary <int, Data.Models.Delegate>(weirdDelegates.Count());

            foreach (var weirds in weirdDelegates)
            {
                var delegat = await UpgradeUser(weirds.First().Delegate, block.Level, protocol);

                activatedDelegates.Add(delegat.Id, delegat);

                delegat.MigrationsCount++;
                block.Operations |= Operations.Migrations;
                Db.MigrationOps.Add(new MigrationOperation
                {
                    Id        = Cache.AppState.NextOperationId(),
                    Block     = block,
                    Level     = block.Level,
                    Timestamp = block.Timestamp,
                    Account   = delegat,
                    Kind      = MigrationKind.ActivateDelegate
                });
                state.MigrationOpsCount++;

                foreach (var weird in weirds)
                {
                    var delegator = weird.Contract;
                    if (delegator.DelegateId != null)
                    {
                        throw new Exception("migration error");
                    }

                    delegator.WeirdDelegate = null;

                    Db.TryAttach(delegator);
                    Cache.Accounts.Add(delegator);

                    delegator.WeirdDelegate   = delegat;
                    delegator.Delegate        = delegat;
                    delegator.DelegateId      = delegat.Id;
                    delegator.DelegationLevel = delegator.FirstLevel;
                    delegator.Staked          = true;

                    delegat.DelegatorsCount++;
                    delegat.StakingBalance += delegator.Balance;
                }
            }

            var ids = activatedDelegates.Keys.ToList();
            var weirdOriginations = await Db.OriginationOps
                                    .AsNoTracking()
                                    .Where(x => x.Contract != null && ids.Contains((int)x.Contract.WeirdDelegateId))
                                    .Select(x => new
            {
                x.Contract.WeirdDelegateId,
                Origination = x
            })
                                    .ToListAsync();

            foreach (var op in weirdOriginations)
            {
                var delegat = activatedDelegates[(int)op.WeirdDelegateId];

                Db.TryAttach(op.Origination);
                op.Origination.Delegate = delegat;
                if (delegat.Id != op.Origination.SenderId && delegat.Id != op.Origination.ManagerId)
                {
                    delegat.OriginationsCount++;
                }
            }
        }
示例#22
0
 public void ResetStage()
 {
     CurrentAppState = AppState.Waitingfordisplay;
 }
示例#23
0
        protected override async Task RevertContext(AppState state)
        {
            var block = await Cache.Blocks.CurrentAsync();

            var delegates = await Db.Delegates
                            .AsNoTracking()
                            .Include(x => x.DelegatedAccounts)
                            .Where(x => x.ActivationLevel == block.Level)
                            .ToListAsync();

            foreach (var delegat in delegates)
            {
                var delegators = delegat.DelegatedAccounts.ToList();
                foreach (var delegator in delegators)
                {
                    Db.TryAttach(delegator);
                    Cache.Accounts.Add(delegator);

                    (delegator as Contract).WeirdDelegate = null;
                    delegator.Delegate        = null;
                    delegator.DelegateId      = null;
                    delegator.DelegationLevel = null;
                    delegator.Staked          = false;

                    delegat.DelegatorsCount--;
                    delegat.StakingBalance -= delegator.Balance;
                }

                if (delegat.StakingBalance != delegat.Balance || delegat.DelegatorsCount > 0)
                {
                    throw new Exception("migration error");
                }

                var user = DowngradeDelegate(delegat);
                user.MigrationsCount--;

                foreach (var delegator in delegators)
                {
                    (delegator as Contract).WeirdDelegate = user;
                }
            }

            var migrationOps = await Db.MigrationOps
                               .AsNoTracking()
                               .Where(x => x.Kind == MigrationKind.ActivateDelegate)
                               .ToListAsync();

            Db.MigrationOps.RemoveRange(migrationOps);

            state.MigrationOpsCount -= migrationOps.Count;

            var ids = delegates.Select(x => x.Id).ToList();
            var weirdOriginations = await Db.OriginationOps
                                    .AsNoTracking()
                                    .Where(x => x.Contract != null && ids.Contains((int)x.Contract.WeirdDelegateId))
                                    .Select(x => new
            {
                x.Contract.WeirdDelegateId,
                Origination = x
            })
                                    .ToListAsync();

            foreach (var op in weirdOriginations)
            {
                var delegat = delegates.First(x => x.Id == op.WeirdDelegateId);

                Db.TryAttach(op.Origination);
                op.Origination.DelegateId = null;
                if (delegat.Id != op.Origination.SenderId && delegat.Id != op.Origination.ManagerId)
                {
                    delegat.OriginationsCount--;
                }
            }
        }
 /// <summary>Closes the Page.</summary>
 private void ClosePage() => AppState.GoBack();
 public UIItemsPresenter(UIItemsUseCase useCase, AppState appState)
 {
     _useCase  = useCase;
     _appState = appState;
 }
示例#26
0
        public static void ExportToGLTF(this MiloObjectDir milo, string path, AppState appState)
        {
            var serializer    = appState.GetSerializer();
            var pathDirectory = Path.GetDirectoryName(path);

            var textures = milo.Entries
                           .Where(x => "Tex".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                           .Select(y => serializer.ReadFromMiloObjectBytes <Tex>(y as MiloObjectBytes))
                           .ToList();

            var extTexs = textures.Where(x => x.UseExternal).ToList();
            var miloDir = appState.GetWorkingDirectory().FullPath;

            // Update textures
            foreach (var texture in textures.Where(x => x.UseExternal && x.Bitmap == null)) // TODO: Figure out what UseExternal actually means
            {
                var texPath = Path.Combine(miloDir, MakeGenPath(texture.ExternalPath, appState.SystemInfo.Platform));
                var bitmap  = serializer.ReadFromFile <HMXBitmap>(texPath);

                texture.Bitmap      = bitmap;
                texture.UseExternal = false;
            }

            var views = milo.Entries
                        .Where(x => "View".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                        .Select(y => serializer.ReadFromMiloObjectBytes <View>(y as MiloObjectBytes))
                        .ToList();

            views.AddRange(milo.Entries
                           .Where(x => "Group".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                           .Select(y => serializer.ReadFromMiloObjectBytes <Group>(y as MiloObjectBytes))
                           .ToList());

            var meshes = milo.Entries
                         .Where(x => "Mesh".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                         .Select(y => serializer.ReadFromMiloObjectBytes <Mackiloha.Render.Mesh>(y as MiloObjectBytes))
                         .Where(z => !string.IsNullOrEmpty(z.Material)) // Don't care about bone meshes for now
                         .ToList();

            var trans = milo.Entries
                        .Where(x => "Trans".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                        .Select(y => serializer.ReadFromMiloObjectBytes <Mackiloha.Render.TransStandalone>(y as MiloObjectBytes))
                        .ToList();

            var materials = milo.Entries
                            .Where(x => "Mat".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase))
                            .Select(y => serializer.ReadFromMiloObjectBytes <Mackiloha.Render.Mat>(y as MiloObjectBytes))
                            //.Where(z => z.TextureEntries.Count > 0 && z.TextureEntries.Any(w => !string.IsNullOrEmpty(w.Texture))) // TODO: Idk?
                            .ToList();

            var cams = milo.Entries
                       .Where(x => "Cam".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase) && appState.SystemInfo.Version <= 10)
                       .Select(y => serializer.ReadFromMiloObjectBytes <Cam>(y as MiloObjectBytes))
                       .ToList();

            var environs = milo.Entries
                           .Where(x => "Environ".Equals(x.Type, StringComparison.CurrentCultureIgnoreCase) && appState.SystemInfo.Version <= 10)
                           .Select(y => serializer.ReadFromMiloObjectBytes <Environ>(y as MiloObjectBytes))
                           .ToList();

            var miloEntries = textures
                              .Union <MiloObject>(views)
                              .Union(meshes)
                              .Union(trans)
                              .Union(materials)
                              .Union(cams)
                              .Union(environs)
                              .ToList();

            var transEntries = miloEntries
                               .Where(x => x is ITrans)
                               .ToList();

            var drawEntries = miloEntries
                              .Where(x => x is IDraw)
                              .ToList();

            /* var transforms = milo.Entries
             *  .Where(x => x.Type.Equals("Trans", StringComparison.CurrentCultureIgnoreCase))
             *  .Select(y =>
             *  {
             *      var trans = MiloOG.Trans.FromStream(new MemoryStream((y as MiloEntry).Data));
             *      trans.Name = y.Name;
             *      return trans;
             *  }).ToList(); */

            var scene = new GLTF()
            {
                Asset = new Asset()
                {
                    Generator = $"Mackiloha v{typeof(MiloExtensions).Assembly.GetName().Version}"
                },
                Images = textures.Select(x => new Image()
                {
                    Name = Path.GetFileNameWithoutExtension(x.Name) + ".png",
                    Uri  = Path.GetFileNameWithoutExtension(x.Name) + ".png"
                }).ToArray(),
                Samplers = new Sampler[]
                {
                    new Sampler()
                    {
                        MagFilter = MagFilter.Linear,
                        MinFilter = MinFilter.Nearest,
                        WrapS     = WrapMode.Repeat,
                        WrapT     = WrapMode.Repeat
                    }
                },
                Scene = 0
            };

            var currentOffset = 0;

            scene.Textures = textures.Select(x => new Texture()
            {
                Name    = x.Name,
                Sampler = 0,
                Source  = currentOffset++
            }).ToArray();

            var keyIdxPairs = Enumerable.Range(0, textures.Count).ToDictionary(x => textures[x].Name);

            scene.Materials = materials.Select(x => new Material()
            {
                Name = x.Name,
                PbrMetallicRoughness = new PbrMetallicRoughness()
                {
                    BaseColorTexture =
                        // Verify material has texture and exists in milo
                        (x.TextureEntries.Any(w => !string.IsNullOrEmpty(w.Texture)) &&
                         keyIdxPairs.ContainsKey(x.TextureEntries.First(x => !string.IsNullOrEmpty(x.Texture)).Texture))
                            ? new BaseColorTexture()
                    {
                        // TODO: Figure out how to map multiple textures to single material
                        Index = keyIdxPairs[x.TextureEntries.First(y => !string.IsNullOrEmpty(y.Texture)).Texture]
                    }
                            : null,
                    BaseColorFactor = new Vector4 <double>(x.BaseColor.R, x.BaseColor.G, x.BaseColor.B, x.BaseColor.A),
                    MetallicFactor  = (x.TextureEntries.Any(w => !string.IsNullOrEmpty(w.Texture)) && x.TextureEntries.First(y => !string.IsNullOrEmpty(y.Texture)).Unknown2 == 2) ? 1 : 0,
                    RoughnessFactor = (x.TextureEntries.Any(w => !string.IsNullOrEmpty(w.Texture)) && x.TextureEntries.First(y => !string.IsNullOrEmpty(y.Texture)).Unknown2 == 2) ? 0 : 1
                },
                EmissiveFactor = new Vector3 <double>(),
                AlphaMode      = AlphaMode.Mask, // x.Blend == BlendFactor.One ? AlphaMode.Blend : AlphaMode.Opaque,
                DoubleSided    = true
            }).ToArray();

            if (!Directory.Exists(pathDirectory))
            {
                // Create directory
                Directory.CreateDirectory(pathDirectory);
            }

            // Saves textures
            for (int i = 0; i < textures.Count; i++)
            {
                textures[i].Bitmap.SaveAs(serializer.Info,
                                          Path.Combine(pathDirectory, scene.Images[i].Uri));
            }

            var accessors   = new List <Accessor>();
            var sceneMeshes = new List <GLTFTools.Mesh>();

            int bufferSize12 = meshes.Select(x => x.Vertices.Count * 12 * 2).Sum(); // Verts + norms
            int bufferSize8  = meshes.Select(x => x.Vertices.Count * 8).Sum();      // UV
            int bufferSize4  = meshes.Select(x => x.Faces.Count * 6).Sum();         // Faces

            if (bufferSize4 % 4 != 0)
            {
                bufferSize4 += 4 - (bufferSize4 % 4);
            }

            scene.Buffers = new GLTFTools.Buffer[]
            {
                new GLTFTools.Buffer()
                {
                    Name       = Path.GetFileNameWithoutExtension(path),
                    ByteLength = (bufferSize4 + bufferSize8 + bufferSize12),
                    Uri        = Path.GetFileNameWithoutExtension(path) + ".bin"
                }
            };

            scene.BufferViews = new BufferView[]
            {
                new BufferView()
                {
                    Name       = "vertsAndNorms",
                    ByteLength = bufferSize12,
                    ByteOffset = 0,
                    ByteStride = 12
                },
                new BufferView()
                {
                    Name       = "uvs",
                    ByteLength = bufferSize8,
                    ByteOffset = bufferSize12,
                    ByteStride = 8
                },
                new BufferView()
                {
                    Name       = "faces",
                    ByteLength = bufferSize4,
                    ByteOffset = bufferSize12 + bufferSize8,
                    ByteStride = null
                }
            };

            int buffer12Offset = scene.BufferViews[0].ByteOffset.Value;
            int buffer8Offset  = scene.BufferViews[1].ByteOffset.Value;
            int buffer4Offset  = scene.BufferViews[2].ByteOffset.Value;

            var bw = new BinaryWriter(new MemoryStream(new byte[bufferSize12 + bufferSize8 + bufferSize4]));
            Dictionary <string, int> meshIndex = new Dictionary <string, int>();

            currentOffset = 0;

            keyIdxPairs = Enumerable
                          .Range(0, materials.Count)
                          .ToDictionary(x => materials[x].Name);

            foreach (var mesh in meshes)
            {
                if (mesh.Vertices.Count <= 0 || mesh.Faces.Count <= 0)
                {
                    continue;
                }
                meshIndex.Add(mesh.Name, currentOffset++);

                // Finds related material + texture
                var mat = materials.First(x => ((string)x.Name).Equals(mesh.Material, StringComparison.CurrentCultureIgnoreCase));

                sceneMeshes.Add(new GLTFTools.Mesh()
                {
                    Name       = mesh.Name,
                    Primitives = new MeshPrimitive[]
                    {
                        new MeshPrimitive()
                        {
                            Attributes = new MeshPrimitiveAttributes()
                            {
                                Position           = accessors.Count,
                                Normal             = accessors.Count + 1,
                                TextureCoordinate0 = accessors.Count + 2
                            },
                            Indices  = accessors.Count + 3,
                            Material = keyIdxPairs[mesh.Material],
                            Mode     = RenderMode.Triangles
                        }
                    }
                });

                // Vertices
                accessors.Add(new Accessor()
                {
                    Name          = mesh.Name + "_positions",
                    ComponentType = ComponentType.Float,
                    Count         = mesh.Vertices.Count,
                    Min           = new double[]
                    {
                        mesh.Vertices.Select(x => x.X).Min(),
                        mesh.Vertices.Select(x => x.Y).Min(),
                        mesh.Vertices.Select(x => x.Z).Min()
                    },
                    Max = new double[]
                    {
                        mesh.Vertices.Select(x => x.X).Max(),
                        mesh.Vertices.Select(x => x.Y).Max(),
                        mesh.Vertices.Select(x => x.Z).Max()
                    },
                    Type       = GLType.Vector3,
                    BufferView = 0,
                    ByteOffset = buffer12Offset - scene.BufferViews[0].ByteOffset.Value
                });
                bw.BaseStream.Seek(buffer12Offset, SeekOrigin.Begin);
                foreach (var vert in mesh.Vertices)
                {
                    bw.Write(vert.X);
                    bw.Write(vert.Y);
                    bw.Write(vert.Z);
                }
                buffer12Offset = (int)bw.BaseStream.Position;

                // Normals
                accessors.Add(new Accessor()
                {
                    Name          = mesh.Name + "_normals",
                    ComponentType = ComponentType.Float,
                    Count         = mesh.Vertices.Count,
                    Min           = new double[]
                    {
                        mesh.Vertices.Select(x => x.NormalX).Min(),
                        mesh.Vertices.Select(x => x.NormalY).Min(),
                        mesh.Vertices.Select(x => x.NormalZ).Min()
                    },
                    Max = new double[]
                    {
                        mesh.Vertices.Select(x => x.NormalX).Max(),
                        mesh.Vertices.Select(x => x.NormalY).Max(),
                        mesh.Vertices.Select(x => x.NormalZ).Max()
                    },
                    Type       = GLType.Vector3,
                    BufferView = 0,
                    ByteOffset = buffer12Offset - scene.BufferViews[0].ByteOffset.Value
                });
                bw.BaseStream.Seek(buffer12Offset, SeekOrigin.Begin);
                foreach (var vert in mesh.Vertices)
                {
                    bw.Write(vert.NormalX);
                    bw.Write(vert.NormalY);
                    bw.Write(vert.NormalZ);
                }
                buffer12Offset = (int)bw.BaseStream.Position;

                // UV coordinates
                accessors.Add(new Accessor()
                {
                    Name          = mesh.Name + "_texcoords",
                    ComponentType = ComponentType.Float,
                    Count         = mesh.Vertices.Count,
                    Min           = new double[]
                    {
                        mesh.Vertices.Select(x => x.U).Min(),
                        mesh.Vertices.Select(x => x.V).Min()
                    },
                    Max = new double[]
                    {
                        mesh.Vertices.Select(x => x.U).Max(),
                        mesh.Vertices.Select(x => x.V).Max()
                    },
                    Type       = GLType.Vector2,
                    BufferView = 1,
                    ByteOffset = buffer8Offset - scene.BufferViews[1].ByteOffset.Value
                });
                bw.BaseStream.Seek(buffer8Offset, SeekOrigin.Begin);
                foreach (var vert in mesh.Vertices)
                {
                    bw.Write(vert.U);
                    bw.Write(vert.V);
                }
                buffer8Offset = (int)bw.BaseStream.Position;

                // Faces
                accessors.Add(new Accessor()
                {
                    Name          = mesh.Name + "_indicies",
                    ComponentType = ComponentType.UnsignedShort,
                    Count         = mesh.Faces.Count * 3,
                    Min           = new double[]
                    {
                        mesh.Faces.SelectMany(x => new [] { x.V1, x.V2, x.V3 }).Min()
                    },
                    Max = new double[]
                    {
                        mesh.Faces.SelectMany(x => new [] { x.V1, x.V2, x.V3 }).Max()
                    },
                    Type       = GLType.Scalar,
                    BufferView = 2,
                    ByteOffset = buffer4Offset - scene.BufferViews[2].ByteOffset.Value
                });
                bw.BaseStream.Seek(buffer4Offset, SeekOrigin.Begin);
                foreach (var face in mesh.Faces)
                {
                    bw.Write(face.V1);
                    bw.Write(face.V2);
                    bw.Write(face.V3);
                }
                buffer4Offset = (int)bw.BaseStream.Position;
            }

            scene.Accessors = accessors.ToArray();
            scene.Meshes    = sceneMeshes.ToArray();

            var nodes     = new List <Node>();
            var nodeIndex = new Dictionary <string, int>();

            /* // TODO: Make milo objects with transforms data
             * MiloOG.AbstractEntry GetAbstractEntry(string name)
             * {
             *  var entry = milo.Entries.FirstOrDefault(x => x.Name == name);
             *  if (entry == null) return null;
             *
             *  switch (entry.Type)
             *  {
             *      case "Mesh":
             *          return meshes.First(y => y.Name == entry.Name);
             *      case "Trans":
             *          return transforms.First(y => y.Name == entry.Name);
             *      case "View":
             *          return views.First(y => y.Name == entry.Name);
             *      default:
             *          return null;
             *  }
             * } */

            /* Matrix4<float>? GetTransform(string transform)
             * {
             *  var transEntry = milo.Entries.FirstOrDefault(y => y.Name == transform);
             *  if (transEntry == null) return null;
             *
             *  switch (transEntry.Type)
             *  {
             *      case "Mesh":
             *          var mesh = meshes.First(y => y.Name == transEntry.Name);
             *          return mesh.Mat2.ToGLMatrix();
             *      case "Trans":
             *          var trans = transforms.First(y => y.Name == transEntry.Name);
             *          return trans.Mat2.ToGLMatrix();
             *      case "View":
             *          var view2 = views.First(y => y.Name == transEntry.Name);
             *          return view2.Mat2.ToGLMatrix();
             *      default:
             *          return null;
             *  }
             * } */

            /* string GetTransformName(MiloOG.AbstractEntry entry)
             * {
             *  switch (entry.Type)
             *  {
             *      case "Mesh":
             *          var mesh = meshes.First(y => y.Name == entry.Name);
             *          return mesh.Transform;
             *      case "Trans":
             *          var trans = transforms.First(y => y.Name == entry.Name);
             *          return trans.Name;
             *      case "View":
             *          var view = views.First(y => y.Name == entry.Name);
             *          return view.Transform;
             *      default:
             *          return null;
             *  }
             * } */

            var shadowRegex = new System.Text.RegularExpressions.Regex("shadow[^.]*.mesh$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            var children = drawEntries
                           .Where(w => w is ITrans) // Use trans collection?
                           .Select(x => new
            {
                Name  = (string)x.Name,
                Trans = (string)(x as ITrans).Transform
            })
                           .Where(y => !string.IsNullOrEmpty(y.Trans))
                           .GroupBy(z => z.Trans)
                           .ToDictionary(g => g.Key, g => g.Select(w => w.Name)
                                         .OrderBy(s => s)
                                         .Where(x => !shadowRegex.IsMatch(x)) // Removes shadow meshes for now
                                         .ToList());

            /* foreach (var entry in meshes.Union<MiloObject>(views)) // TODO: Union w/ trans
             * {
             *  var transName = (entry as Mackiloha.Render.Interfaces.ITrans)
             *      .Trans
             *      .Transform;
             *
             *  if (!children.ContainsKey(transName))
             *      children.Add(transName, new List<string>(new string[] { entry.Name }));
             *  else if (!children[transName].Contains(entry.Name))
             *      children[transName].Add(entry.Name);
             * } */

            var rootIndex = new List <int>();

            foreach (var key in children.Keys)
            {
                rootIndex.Add(nodes.Count);
                var transEntry = transEntries.FirstOrDefault(x => x.Name == key) as ITrans;

                var node = new Node()
                {
                    Name     = "Root_" + key,
                    Mesh     = meshIndex.ContainsKey(key) ? (int?)meshIndex[key] : null,
                    Matrix   = ToGLMatrix((transEntry != null) ? transEntry.Mat2 : Matrix4.Identity()),
                    Children = Enumerable.Range(nodes.Count + 1, children[key].Count).ToArray()
                };
                nodes.Add(node);

                foreach (var child in children[key])
                {
                    var subEntry = drawEntries.First(x => x.Name == child);

                    var subNode = new Node()
                    {
                        Name = subEntry.Name,
                        Mesh = meshIndex.ContainsKey(subEntry.Name) ? (int?)meshIndex[subEntry.Name] : null,
                        //Matrix = ToGLMatrix(subEntry.Mat1)
                    };
                    nodeIndex.Add(child, rootIndex.Last());
                    nodes.Add(subNode);
                }
            }

            int CreateNode(string name) // Returns index of node
            {
                if (nodeIndex.ContainsKey(name))
                {
                    return(nodeIndex[name]);
                }

                var           entry          = drawEntries.First(x => x.Name == name) as IDraw;
                var           transformEntry = drawEntries.First(x => x.Name == (entry as ITrans).Transform);
                List <string> subNodes       = entry.Drawables.Select(x => (string)x).ToList();

                var node = new Node()
                {
                    Name   = name,
                    Mesh   = meshIndex.ContainsKey(name) ? (int?)meshIndex[name] : null,
                    Matrix = ToGLMatrix((entry as ITrans).Mat1),
                    //Matrix = GetTransform(entry.Transform),
                    Children = (subNodes.Count > 0) ? subNodes.Select(x => CreateNode(x)).ToArray() : null
                };

                nodeIndex.Add(name, nodes.Count);
                nodes.Add(node);
                return(nodeIndex[name]);
            }

            // foreach (var n in meshes.Union<MiloOG.AbstractEntry>(views).Union<MiloOG.AbstractEntry>(transforms)) CreateNode(n.Name);
            //
            // scene.Scene = 0;
            // scene.Scenes = new Scene[] { new Scene() { Nodes = Enumerable.Range(0, nodes.Count).ToArray() } };


            // foreach (var view in views) CreateNode(view.Name);
            //
            // // Finds root node
            // var childrenNodes = nodes.SelectMany(x => x.Children ?? new int[0]).Distinct();
            // var parentNodes = Enumerable.Range(0, nodes.Count);
            // var rootIdx = parentNodes.Except(childrenNodes).Single();
            //
            // scene.Scene = 0;
            // scene.Scenes = new Scene[] { new Scene() { Nodes = new int[] { rootIdx } } };

            List <string> GetAllSubs(MiloObject entry)
            {
                List <string> subsEntriesNames = (entry as IDraw).Drawables
                                                 .Select(x => (string)x)
                                                 .ToList();

                var subEntries = subsEntriesNames
                                 .Select(x => drawEntries.FirstOrDefault(y => y.Name == x))
                                 .Where(y => y != null)
                                 .ToList();

                foreach (var subEntry in subEntries)
                {
                    subsEntriesNames.AddRange(GetAllSubs(subEntry));
                }

                return(subsEntriesNames);
            }

            scene.Scene = 0;
            //scene.Scenes = new Scene[] { new Scene() { Nodes = rootIndex.ToArray() } };

            scene.Scenes = views
                           .Select(x => new Scene()
            {
                Nodes = GetAllSubs(x)
                        .Select(y => nodeIndex.ContainsKey(y) ? nodeIndex[y] : -1)
                        .Where(z => z != -1)
                        .Distinct()
                        .ToArray()
            })
                           .OrderByDescending(x => x.Nodes.Length)
                           .ToArray();

            if (scene.Scenes.Length <= 0)
            {
                // Create scene from root notes
                scene.Scenes = new[]
 public IdentityAuthenticationStateProvider(IAuthorizeApi authorizeApi, AppState appState)
 {
     _authorizeApi = authorizeApi;
     _appState     = appState;
 }
示例#28
0
 // Should pass any and all variables and references which
 // are required for setup
 protected virtual void PreinitializeState(AppState appState)
 {
 }
        private void StartStopRecognition(object sender, RoutedEventArgs e)
        {
            if (_currentState == AppState.Idle)
            {

                txtRecognizedText.Text = string.Empty;
                var recognitionEngine = new DetectionEngine(_codebook, _models);
                _signal = new MicrophoneSoundSignalReader();

                var length = (_signal.SampleRate / 1000.0) * EngineParameters.Default.StepSizeMiliseconds;
                if (_aggregator != null)
                {
                    _aggregator.SampleReady -= AggregatorSampleReady;
                }
                _aggregator = new SampleAggregator(Convert.ToInt32(length));

                _aggregator.SampleReady += AggregatorSampleReady;
                _signal.Start();
                Action action = () =>
                {
                    Thread.Sleep(3000);
                    recognitionEngine.RecognizeAsync(_signal, OnMessageReceived, _aggregator);
                };

                action.BeginInvoke(null, null);

                btnRecog.Content = "Stop Recognition";
                _currentState = AppState.Recognition;
            }
            else
            {
                btnRecog.Content = "Start Recognition";
                _signal.Close();
                _currentState = AppState.Idle;
                _aggregator.SampleReady -= AggregatorSampleReady;
                _aggregator = null;
            }
        }
示例#30
0
 public WhenGettingSa1Rom()
 {
     appState = new AppState();
     TestRoms.Include(testRom);
     Command.Run(new LoadRomCommand(appState, testRom));
 }
示例#31
0
	void Update (){
		switch (currentAppState) {
		case AppState.Login:
			if (userExists) {
				currentAssignments.Add (new Assignment ("hotspots_periodic", "hotspots", "NA", false, 9999, "NA", "Periodic Table"));
				currentAppState = AppState.Initialize;
			}
			break;
		case AppState.Initialize:
			if (CheckForInternetConnection ()) {
				StartCoroutine (DownloadListOfURLs ());
				currentAppState = AppState.GetURLs;
			} else {
				currentAppState = AppState.MenuConfig;
			}
			break;
		case AppState.GetURLs:
			//only triggers once DownloadListOfURLs finishes
			if (urlsDownloaded) {
				currentAppState = AppState.DownloadAssignments;
			}
			break;
		case AppState.DownloadAssignments:
			if (assignsLoaded == totalAssigns && imagesLoaded == imagesRequired) {
				currentAppState = AppState.LoadContent;
			}
			
			//lets user know how many images and or assignments are still being loaded
			if (imagesLoaded != imagesRequired) {
				GUIManager.s_instance.SetErrorText (("Loading Images: " + imagesLoaded.ToString () + "/" + imagesRequired.ToString ()));
			} else {
				GUIManager.s_instance.SetErrorText (("Loading Assignments: " + assignsLoaded.ToString () + "/" + totalAssigns.ToString ()));
			}
			break;
		case AppState.LoadContent:
			loadInLocalAssignments ();
			currentAppState = AppState.MenuConfig;
			break;
		case AppState.LoadFromAssign:
			saveAssignmentMastery(currentAssignments[currIndex]);
			currentAppState = AppState.Uploading;
			break;
    case AppState.Uploading:
      if(uploadingDone){
        currentAppState = AppState.MenuConfig;
      }
      break;
		case AppState.MenuConfig:
			List<int> indexesToRemove = new List<int> ();
			for (int i = 0; i<currentAssignments.Count; i++) {
				if (!(supportedTemplates.Contains (currentAssignments [i].type))) {
					indexesToRemove.Add (i);
				}
			}
			for (int i = indexesToRemove.Count-1; i>-1; i--) {
				currentAssignments.RemoveAt (indexesToRemove [i]);
			}
			GUIManager.s_instance.LoadAllAssignments (currentAssignments);
			GUIManager.s_instance.SlideFromLoginToMain ();
			currentAppState = AppState.AssignmentMenu;
			break;
		case AppState.AssignmentMenu:
			if (clicked) {
        timeAtAssignLoad = Time.time;
				currentAssignments [currIndex].timeAtLoad = Time.time;
				clicked = false;
				currentAppState = AppState.PlayConfig;
				Application.LoadLevel (currentAssignments [currIndex].type);
			}
			break;
		case AppState.PlayConfig:
      timeAtAssignLoad = Time.time - timeAtAssignLoad;
			GameObject newMgr = GameObject.Find ("GameManager");
			
			if (currentAssignments [currIndex].type != "hotspots") {
				newMgr.SendMessage ("configureGame", currIndex);//currentAssignments[currIndex]);
			}
			currentAppState = AppState.Playing;
			break;
		case AppState.Playing:
			if (Application.loadedLevelName == "Login") {
				currentAppState = AppState.LoadFromAssign;
			}
			break;
		}
	}
示例#32
0
 /// <summary>
 /// start a quiz
 /// </summary>
 /// <param name="input"></param>
 /// <param name="innerResponse"></param>
 /// <returns>void</returns>
 private void DoQuiz(SkillRequest input, IOutputSpeech innerResponse)
 {
     appstate = AppState.Quiz;
     ClearAppState();
     AskQuestion(input, innerResponse);
 }
示例#33
0
 private void BtnCancel_Click(object sender, RoutedEventArgs e) => AppState.GoBack();
示例#34
0
 public EffectTrackerService(INWScript script, AppState state)
 {
     _      = script;
     _state = state;
 }
 public MassControlMenuHandler(MassController autoController, AppState appState)
 {
     this.autoController = autoController ?? throw new ArgumentNullException(nameof(autoController));
     this.appState       = appState ?? throw new ArgumentNullException(nameof(appState));
 }
示例#36
0
 private void logoutButton_Click(object sender, EventArgs e)
 {
     previousState = currentState;
     currentState = AppState.Start;
     GetNextScreen();
 }
示例#37
0
        /// <summary>
        /// Process the Intent requests and return the speeech output
        /// </summary>
        /// <param name="input"></param>
        /// <returns>IOutputSpeech innerResponse</returns>
        private IOutputSpeech GetIntentRequest(SkillRequest input)
        {
            var           intentRequest = input.Request;
            IOutputSpeech innerResponse = new PlainTextOutputSpeech();

            MakeItemList();

            switch (intentRequest.Intent.Name)
            {
            case "QuizIntent":
                DoQuiz(input, innerResponse = new SsmlOutputSpeech());
                break;

            case "AnswerIntent":
                appstate = GetAppState(input);
                Answer(input, innerResponse = new SsmlOutputSpeech());
                break;

            case "Quiz":
                DoQuiz(input, innerResponse = new SsmlOutputSpeech());
                break;

            case "AskQuestion":
                appstate = AppState.Quiz;
                counter  = GetIntAttributeProperty(input.Session.Attributes, COUNTER);
                AskQuestion(input, innerResponse = new SsmlOutputSpeech());
                break;

            case AlexaConstants.CancelIntent:
                (innerResponse as PlainTextOutputSpeech).Text = EXIT_SKILL_MESSAGE;
                response.Response.ShouldEndSession            = true;
                break;

            case AlexaConstants.StartOverIntent:
                DoQuiz(input, innerResponse        = new SsmlOutputSpeech());
                response.Response.ShouldEndSession = false;
                break;

            case AlexaConstants.StopIntent:
                (innerResponse as PlainTextOutputSpeech).Text = EXIT_SKILL_MESSAGE;
                response.Response.ShouldEndSession            = true;
                break;

            case AlexaConstants.HelpIntent:
                (innerResponse as PlainTextOutputSpeech).Text = HELP_MESSAGE;
                break;

            default:
                if (appstate == AppState.Quiz)
                {
                    Answer(input, innerResponse = new SsmlOutputSpeech());
                }
                else
                {
                    (innerResponse as PlainTextOutputSpeech).Text = WELCOME_MESSAGE;
                }
                break;
            }

            if (innerResponse.Type == "SSML")
            {
                (innerResponse as SsmlOutputSpeech).Ssml = "<speak>" + (innerResponse as SsmlOutputSpeech).Ssml + "</speak>";
            }

            return(innerResponse);
        }
示例#38
0
 private void StatisticsButton_Click(object sender, EventArgs e)
 {
     previousState = currentState;
     currentState = AppState.Statistics;
     GetNextScreen();
 }
示例#39
0
    // Update is called once per frame
    void Update()
    {
        URL = IP + "check_visual_request" + "?t=" + getUTCTime();
        switch (CurrentAppState)
        {
        case AppState.Waitingfordisplay:
            CurrentAppState = AppState.poll_file_name;
            navigates.GetComponent <navigator>().set_IP(IP, uid);
            break;

        case AppState.poll_file_name:
            WWW request = new WWW(URL);
            while (!request.isDone)
            {
            }

            if (dis_info == false)
            {
                infom.GetComponent <tutorial>().download_complete();
                dis_info = true;
            }


            string readHtml = request.text;
            var    N        = JSON.Parse(readHtml);
            VID          = N["vrid"];
            DEM_file     = N["DEM"].ToString();
            Longitude    = N["Longitude"];
            Latitude     = N["Latitude"];
            Height       = N["Height"];
            Width        = N["Width"];
            Pixel_length = N["Pixel_length"];


            switch (VID)
            {
            case 1:
                mapview.GetComponent <load_map>().show_image(Width, Height, "DEM1/tmp");
                cloudmesh.GetComponent <cloud_mesh>().display_request_received(Width, Height, 1);
                navigates.GetComponent <navigator>().set_para_2(Height, Width, Longitude, Latitude, Pixel_length);
                break;

            case 2:
                mapview.GetComponent <load_map>().show_image(Width, Height, "DEM3/2_0");
                cloudmesh.GetComponent <cloud_mesh>().display_request_received(Width, Height, 2);
                navigates.GetComponent <navigator>().set_para_2(Height, Width, Longitude, Latitude, Pixel_length);
                break;

            case 3:
                mapview.GetComponent <load_map>().show_image(Width, Height, "DEM2/3_0");
                cloudmesh.GetComponent <cloud_mesh>().display_request_received(Width, Height, 3);
                navigates.GetComponent <navigator>().set_para_2(Height, Width, Longitude, Latitude, Pixel_length);
                break;
            }
            CurrentAppState = AppState.Ready;
            break;

        case AppState.Ready:

            counter++;

            if (counter == 500)
            {
                WWW check = new WWW(URL);
                while (!check.isDone)
                {
                }
                string readcheck = check.text;
                var    M         = JSON.Parse(readcheck);
                int    tmp_id    = M["vrid"];
                if (tmp_id != VID)
                {
                    Debug.Log("Here");
                    cloudmesh.GetComponent <cloud_mesh>().reset_map();
                    navigates.GetComponent <navigator>().reset();
                    CurrentAppState = AppState.poll_file_name;
                }
                counter = 0;
            }
            break;
        }
    }
示例#40
0
        public User AuthenticateOnline(string email, string password)
        {
            User       user     = null;
            HttpClient client   = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
            var        formData = new FormUrlEncodedContent(new[] {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("username", email),
                new KeyValuePair <string, string>("password", password)
            });

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                       EncodeToBase64(string.Format("{0}:{1}",
                                                                                                                    applicationCode,
                                                                                                                    applicationSecretPass)));
            var response = client.PostAsync("/Authenticate", formData).Result;

            if (response.IsSuccessStatusCode)
            {
                var jsondata = response.Content.ReadAsStringAsync().Result;
                var token    = JsonConvert.DeserializeObject <AccessToken>(jsondata);
                AppState.Instance.OnPremiseToken = token;
                client.Dispose();
                client = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.access_token);
                response = client.GetAsync("api/user/UserById/" + token.Id).Result;
                if (response.IsSuccessStatusCode)
                {
                    jsondata = response.Content.ReadAsStringAsync().Result;
                    user     = JsonConvert.DeserializeObject <User>(jsondata);
                    AppState.Instance.IsSuperAdmin = false;
                    if (user.Roles.Contains("SuperAdmin"))
                    {
                        client.Dispose();
                        var formData1 = new FormUrlEncodedContent(new[] {
                            new KeyValuePair <string, string>("grant_type", "password"),
                            new KeyValuePair <string, string>("username", email),
                            new KeyValuePair <string, string>("password", password)
                        });
                        client = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                                   EncodeToBase64(string.Format("{0}:{1}",
                                                                                                                                applicationCode,
                                                                                                                                applicationSecretPass)));
                        response = client.PostAsync("/Authenticate", formData1).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            jsondata = response.Content.ReadAsStringAsync().Result;
                            token    = JsonConvert.DeserializeObject <AccessToken>(jsondata);
                            AppState.Instance.CentralizedToken = token;
                        }
                        AppState.Instance.IsSuperAdmin = true;
                    }

                    CreateCredentialFile(user, password);
                    if (AppState.Instance.IsSuperAdmin)
                    {
                        SynchPurchaseOrder(user.ServerUserId);
                    }
                }
            }
            else
            {
                ErrorMessage = "Invalid User Name or Password";
            }
            return(user);
        }
示例#41
0
    public override void EnterFrom(AppState state)
    {
        base.EnterFrom(state);

        ShowRequestMenu();
    }
示例#42
0
 public override Task Activate(AppState state, JsonElement block) => new ProtoActivator(this).Activate(state, block);
示例#43
0
        private static void Process_NewRssItems(RssUrlEntry entry, RssTorrent[] new_items)
        {
            foreach (var nitem in new_items)
            {
                if (url_404.Contains(nitem.TorrentFileUrl))
                {
                    continue;
                }

                string save_path = Path.Combine(RssTorrentsStorageDirectory, Utility.CleanFileName(nitem.Name) + ".torrent");
                nitem.TorrentFilePath = save_path;

                if (File.Exists(save_path))
                {
                    //re-load from downloaded file
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        nitem.LastResponseMessage = "Data was already saved";
                        nitem.LastResponseType    = DownloadRssResponse.ResonseType.OK;
                        nitem.Success             = AppState.AddTorrentRss(save_path, entry);
                    }));
                    continue;
                }

                if (!IsQueued(nitem))
                {
                    QueuedItems.Add(nitem);

                    System.Threading.Tasks.Task.Factory.StartNew(new Action(() =>
                    {
                        Debug.WriteLine("[Rssdownloader-TQ]: Work Item '{0}' has been started", nitem.Name, "");

                        var res            = download(nitem.IsMagnetOnly ? nitem.TorrentMagnetUrl : nitem.TorrentFileUrl);
                        nitem.LastResponse = res;

                        Debug.WriteLine("[Rssdownloader-TQ]: Work Item '{0}' resp type is {1}", nitem.Name, res.Type);

                        if (res.Type == DownloadRssResponse.ResonseType.OK || res.Type == DownloadRssResponse.ResonseType.MagnetLink)
                        {
                            byte[] data = res.Data;
                            if (data.Length > 0)
                            {
                                File.WriteAllBytes(save_path, data);
                                Debug.WriteLine("[Rssdownloader-TQ]: Work Item '{0}' succesfully downloaded", nitem.Name, "");

                                App.Current.Dispatcher.Invoke(new Action(() =>
                                {
                                    nitem.Success = AppState.AddTorrentRss(save_path, entry);
                                }));
                            }
                            else
                            {
                                if (res.Type == DownloadRssResponse.ResonseType.MagnetLink)
                                {
                                    Debug.WriteLine("[Rssdownloader-TQ]: Cannot add torrent ({0}) magnet ('{1}')",
                                                    nitem.Name, nitem.TorrentMagnetUrl);
                                }
                                //What should we do?
                            }
                        }
                        else if (res.Type == DownloadRssResponse.ResonseType.NotFound)
                        {
                            if (!url_404.Contains(nitem.TorrentFileUrl))
                            {
                                url_404.Add(nitem.TorrentFileUrl);
                                Debug.WriteLine("[Rssdownloader-TQ]: URL '{0}' not found, therefore banned.", nitem.TorrentFileUrl, "");
                            }
                        }

                        QueuedItems.Remove(nitem);
                        return;
                    }));
                }
            }
        }
示例#44
0
 public override Task Deactivate(AppState state) => new ProtoActivator(this).Deactivate(state);
示例#45
0
 private void QuizButton_Click(object sender, EventArgs e)
 {
     previousState = currentState;
     currentState = AppState.InQuiz;
     GetNextScreen();
 }
        //
        // GET: /Home/
        public async Task <ActionResult> Index()
        {
            // Force SSL
            if (!Request.IsSecureConnection)
            {
                string         httplength   = "http";
                string         nonsecureurl = Request.Url.AbsoluteUri.Substring(httplength.Length);
                string         secureurl    = String.Format("https{0}", nonsecureurl);
                RedirectResult result       = Redirect(secureurl);
                result.ExecuteResult(this.ControllerContext);
            }

            // This is where state of the app is maintained and data passed between view and controller
            AppState appState = new AppState();

            // Authorization back from AAD in a form post as requested in the authorize request
            if (Request.Form != null)
            {
                // Did it return with an error?
                if (!String.IsNullOrEmpty(Request.Form["error"]))
                {
                    appState.ErrorMessage    = Request.Form["error"];
                    appState.AppIsAuthorized = false;

                    return(View(appState));
                }

                // Authorized without error: Check to see if we have an ID token
                if (String.IsNullOrEmpty(Request.Form["id_token"]))
                {
                    appState.AppIsAuthorized = false;
                }
                else
                {
                    // Was it correlated with authorize request
                    var authstate = Session[AppSessionVariables.AuthState] as String;
                    Session[AppSessionVariables.AuthState] = null;
                    if (String.IsNullOrEmpty(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (No auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }
                    if (!Request.Form["state"].Equals(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (Invalid auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }

                    // Get the TenantId out of the ID Token to address tenant specific token endpoint.
                    // No validation of ID Token as the only info we need is the tenantID
                    // If for any case your app wants to use the ID Token to authenticate
                    // it must be validated.
                    JwtToken openIDToken = GetTenantId(Request.Form["id_token"]);
                    appState.TenantId     = openIDToken.tid;
                    appState.TenantDomain = openIDToken.domain;
                    appState.LoggedOnUser = openIDToken.upn;

                    appState.AppIsAuthorized = true;
                }
            }

            if (appState.AppIsAuthorized)
            {
                // Get app-only access tokens ....
                try
                {
                    // Get an app-only access token for the AAD Graph Rest APIs
                    var authResult = await GetAppOnlyAccessToken(appConfig.GraphResourceUri, appState.TenantId);

                    // Get list of users in this Tenant from AAD Graph to fill drop down with smtp addresses
                    List <GraphUser> users = GetUsers(appState.TenantId, authResult.AccessToken);

                    appState.MailboxList        = this.BuildMailboxDropDownList(string.Empty, users);
                    appState.MailboxSmtpAddress = appState.MailboxList.SelectedValue as String;

                    // For convenience maintain this list as a session
                    Session[AppSessionVariables.MailboxList] = users;

                    // Get app-only access tokens for Exchange Rest APIs
                    authResult = await GetAppOnlyAccessToken(appConfig.ExchangeResourceUri, appState.TenantId);

                    appState.AccessToken = authResult.AccessToken;
                    appState.AccessTokenAquiredWithoutError = true;

                    SetSessionInProgress();
                }
                catch (Exception ex)
                {
                    appState.ErrorMessage = ex.Message;
                }
            }

            return(View(appState));
        }
 /// <summary>
 /// Default ctor
 /// </summary>
 internal ReadNewLocoIOsForm(AppState appState)
 {
     this.appState = appState;
     InitializeComponent();
 }
示例#48
0
        public void LoadLocalMarketplace(Dispatcher dispatcher)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");

            if (Directory.Exists(path))
            {
                // Outdated scripts first
                foreach (string file in Directory.EnumerateFiles(path, "*.lua", SearchOption.TopDirectoryOnly))
                {
                    string fileCapture = file;
                    Task.Run(() =>
                    {
                        FileInfo fi = new FileInfo(fileCapture);
                        string checksum;
                        using (MD5 md5 = MD5.Create())
                        {
                            checksum = AppState.GetMd5Hash(md5, File.ReadAllText(fileCapture));
                        }

                        dispatcher.Invoke(() =>
                        {
                            MarketplaceEntry me =
                                new MarketplaceEntry()
                            {
                                ProjectID        = "local_unknown_" + Guid.NewGuid().ToString(),
                                Name             = fi.Name,
                                ShortDescription = "Unknown local script",
                                FullDescription  = "This script was found locally in the Scripts directory but it doesn't use the new scripting format. This file was still loaded as a script but it will have no interaction with the scripting marketplace!",
                                IsLocal          = true,
                                Version          = 0,
                                LatestVersion    = new SemanticVersioning.Version(1, 0, 0),
                                AppRange         = new SemanticVersioning.Range("*"),
                                Changelog        = new System.Collections.Generic.Dictionary <string, string>(),
                                License          = "Unknown, assume All Rights Reserved.",
                                Authors          = new string[] { "Unknown" },
                                Tags             = new string[0],
                                Link             = fileCapture,
                                MD5           = checksum,
                                Flags         = new MarketplaceEntryFlag[] { MarketplaceEntryFlag.LocalScriptOnly },
                                LocalPath     = fileCapture,
                                HasNoMetadata = true
                            };

                            this.LocalDB.Add(me);
                            this.CheckMarketplaceEntryAvailability(me);
                        });
                    });
                }

                // Iterate directories
                foreach (string directory in Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly))
                {
                    string mpe = Directory.EnumerateFiles(directory, "*.json", SearchOption.TopDirectoryOnly).FirstOrDefault();
                    if (mpe != null)
                    {
                        Task.Run(() =>
                        {
                            MarketplaceEntry me = JsonConvert.DeserializeObject <MarketplaceEntry>(File.ReadAllText(mpe));
                            me.IsLocal          = true;
                            me.LocalPath        = mpe;
                            string lp           = Directory.EnumerateFiles(directory, "*.lua", SearchOption.TopDirectoryOnly).FirstOrDefault();
                            me.LocalScriptPath  = mpe;
                            using (MD5 md5 = MD5.Create())
                            {
                                me.MD5 = AppState.GetMd5Hash(md5, File.ReadAllText(lp));
                            }

                            dispatcher.Invoke(() =>
                            {
                                this.LocalDB.Add(me);
                                this.CheckMarketplaceEntryAvailability(me);
                            });
                        });
                    }
                }
            }
        }
示例#49
0
 /// <summary>
 /// 设置程序状态
 /// </summary>
 /// <param name="state"></param>
 void SetAppState(AppState state)
 {
     appState = state;
     this.btnStart.Enabled = (appState == AppState.Stoped);
     this.btnStop.Enabled = (appState == AppState.Started);
     this.txtIpAddress.Enabled = (appState == AppState.Stoped);
     this.txtPort.Enabled = (appState == AppState.Stoped);
     this.cbxAsyncConn.Enabled = (appState == AppState.Stoped);
     this.btnSend.Enabled = (appState == AppState.Started);
 }
 public IManagedComponent()
 {
     this.State = AppState.Created;
 }
        /// <summary>
        /// Raised when a message is recieved from the foreground app
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            AppSuspendedMessage appSuspendedMessage;
            if (MessageService.TryParseMessage(e.Data, out appSuspendedMessage))
            {
                Debug.WriteLine("App suspending"); // App is suspended, you can save your task state at this point
                foregroundAppState = AppState.Suspended;
                var currentTrackId = GetCurrentTrackId();
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, currentTrackId?.ToString());
                return;
            }

            AppResumedMessage appResumedMessage;
            if (MessageService.TryParseMessage(e.Data, out appResumedMessage))
            {
                Debug.WriteLine("App resuming"); // App is resumed, now subscribe to message channel
                foregroundAppState = AppState.Active;
                return;
            }

            StartPlaybackMessage startPlaybackMessage;
            if (MessageService.TryParseMessage(e.Data, out startPlaybackMessage))
            {
                //Foreground App process has signalled that it is ready for playback
                Debug.WriteLine("Starting Playback");
                StartPlayback();
                return;
            }

            SkipNextMessage skipNextMessage;
            if (MessageService.TryParseMessage(e.Data, out skipNextMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to next");
                SkipToNext();
                return;
            }

            SkipPreviousMessage skipPreviousMessage;
            if (MessageService.TryParseMessage(e.Data, out skipPreviousMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to previous");
                SkipToPrevious();
                return;
            }

            TrackChangedMessage trackChangedMessage;
            if (MessageService.TryParseMessage(e.Data, out trackChangedMessage))
            {
                var index = playbackList.Items.ToList().FindIndex(i => (string)i.Source.CustomProperties[TrackIdKey] == trackChangedMessage.TrackId);
                Debug.WriteLine("Skipping to track " + index);
                smtc.PlaybackStatus = MediaPlaybackStatus.Changing;
                playbackList.MoveTo((uint)index);
                return;
            }

            UpdatePlaylistMessage updatePlaylistMessage;
            if (MessageService.TryParseMessage(e.Data, out updatePlaylistMessage))
            {
                CreatePlaybackList(updatePlaylistMessage.PlayList);
                return;
            }
        }
示例#52
0
        /// <summary>
        /// Stop the app.
        /// </summary>
        /// <param name="closeKey">Special key to send to close the app [default=Ctrl-C]</param>
        /// <param name="forceCloseMillisecondsTimeout">Timeout to wait before closing the app forcefully [default=infinite]</param>
        public void Stop(ConsoleSpecialKey closeKey = ConsoleSpecialKey.ControlC, int forceCloseMillisecondsTimeout = Timeout.Infinite)
        {
            ThrowIfDisposed();

            lock (_stateLock)
            {
                if (State == AppState.Undefined || State == AppState.Exited)
                    throw new InvalidOperationException("App is not running.");

                if (State == AppState.Exiting)
                    throw new InvalidOperationException("App is already exiting.");

                State = AppState.Exiting;

                Task.Factory.StartNew(() => CloseConsole(closeKey, forceCloseMillisecondsTimeout),
                    TaskCreationOptions.LongRunning);
            }
        }
        private void StartStopRecording(object sender, RoutedEventArgs e)
        {
            if (_currentState != AppState.Recording && _currentState != AppState.Idle)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(txtWord.Text))
            {
                return;
            }

            if (_currentState == AppState.Idle) //"Start Recording"
            {
                var folderName = Path.Combine(ConfigurationSettings.RecordingFolder, txtWord.Text);
                if (!Directory.Exists(folderName))
                {
                    Directory.CreateDirectory(folderName);
                }

                folderName = Path.GetFullPath(folderName);
                var fileName = Guid.NewGuid() + ".wav";
                var fullFileName = Path.Combine(folderName, fileName);

                _recorder.Record(fullFileName);
                btnRecog.IsEnabled = false;
                btnTrain.IsEnabled = false;

                btnStartStopRecord.Content = "Stop Recording";
                _currentState = AppState.Recording;
            }
            else //"Stop Recording"
            {
                _recorder.Stop();
                btnStartStopRecord.Content = "Start Recording";
                btnRecog.IsEnabled = true;
                btnTrain.IsEnabled = true;
                _currentState = AppState.Idle;
            }
        }
示例#54
0
 private void ForegroundMessengerOnAppResumed(object sender, EventArgs eventArgs)
 {
     Debug.WriteLine("App resuming");
     ForegroundAppState = AppState.Active;
 }
 public AccountPartViewModel()
 {
     if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
         _appState = App.Current.State;
 }
示例#56
0
 // Initialization code. Don't use any Avalonia, third-party APIs or any
 // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
 // yet and stuff might break.
 public static void Main(string[] args)
 {
     AppState.GetAppState().Arguments = args.Length > 0 ? args : new string[] { "" };
     BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
 }
示例#57
0
        /// <summary>
        /// Start the app.
        /// </summary>
        public void Run()
        {
            ThrowIfDisposed();

            lock (_stateLock)
            {
                if (State == AppState.Running)
                    throw new InvalidOperationException("App is already running.");

                if (State == AppState.Exiting)
                    throw new InvalidOperationException("App is exiting.");

                StartProcessAsync();

                State = AppState.Running;
            }
        }
 public MassController(ILogger <MassController> logger, AppState appState, IMachineController machineController)
 {
     this.logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     this.appState          = appState ?? throw new ArgumentNullException(nameof(appState));
     this.machineController = machineController ?? throw new ArgumentNullException(nameof(machineController));
 }
示例#59
0
        private void HandleProcessExit()
        {
            if (_process == null)
                return;

            lock (_stateLock)
            {
                ExitCode = _process.ExitCode;
                ExitTime = _process.ExitTime;

                FreeProcessResources();
                State = AppState.Exited;
            }
            try
            {
                OnExited(new EventArgs());
            }
            catch (Exception ex)
            {
                Trace.TraceError("OnExited exception ignored: Error={0}", ex.ToString());
            }
        }
示例#60
0
 private void CloseChatCard()
 {
     AppState.DevicesFrameChatSessions.RemoveAll(x => x.DeviceId == Session.DeviceId);
     AppState.InvokePropertyChanged(nameof(AppState.DevicesFrameChatSessions));
 }