Esempio n. 1
0
    void OnDestroy()
    {
        sRefCount--;

        if (sRefCount == 0)
        {
            sSingleton = null;
            TrackingWrapper.Shutdown ();
        }
    }
Esempio n. 2
0
  void Awake() {
    if (tm != null && tm != this) {
      Destroy(gameObject);
      return;
    }

    DontDestroyOnLoad(gameObject);
    DontDestroyOnLoad(GetComponentInChildren<AppsFlyerTrackerCallbacks>());
    tm = this;

#if !UNITY_EDITOR
    googleAnalyticsV3 = GetComponent<GoogleAnalyticsV3>();
    if (!googleAnalyticsV3.isActiveAndEnabled)
      initGoogleAnalytics();

    initAppsFlyer();

#endif
  }
        /// <summary>
        /// Upload large file.
        /// </summary>
        /// <param name="folder">The destination folder</param>
        /// <returns>Task to support await of async call.</returns>
        public static async Task UploadLargeFileAsync(OneDriveStorageFolder folder)
        {
            try
            {
                if (folder != null)
                {
                    var selectedFile = await OpenLocalFileAsync();

                    if (selectedFile != null)
                    {
                        using (var localStream = await selectedFile.OpenReadAsync())
                        {
                            Shell.Current.DisplayWaitRing = true;

                            // If the file exceed the Maximum size (ie 4MB)
                            var largeFileCreated = await folder.StorageFolderPlatformService.UploadFileAsync(selectedFile.Name, localStream, CreationCollisionOption.GenerateUniqueName, 320 * 1024);
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);
            }
            catch (ServiceException graphEx)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(graphEx.Error.Message);
            }
            catch (Exception ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);

                TrackingManager.TrackException(ex);
            }
            finally
            {
                Shell.Current.DisplayWaitRing = false;
            }
        }
        /// <summary>
        /// Download a file
        /// </summary>
        /// <param name="item">File to download from OneDrive</param>
        /// <returns>Task to support await of async call.</returns>
        public static async Task DownloadAsync(OneDriveStorageItem item)
        {
            try
            {
                Shell.Current.DisplayWaitRing = true;
                var oneDriveFile = (OneDriveStorageFile)item;
                using (var remoteStream = (await oneDriveFile.StorageFilePlatformService.OpenAsync()) as IRandomAccessStream)
                {
                    await SaveToLocalFolder(remoteStream, oneDriveFile.Name);
                }
            }
            catch (Exception ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);

                TrackingManager.TrackException(ex);
            }
            finally
            {
                Shell.Current.DisplayWaitRing = false;
            }
        }
Esempio n. 5
0
    public static void loadConfigs(TrackingManager myScript)
    {
        if (!Directory.Exists(Application.dataPath + "/StreamingAssets"))
        {
            Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
        }

        string path = Application.dataPath + "/StreamingAssets/tracking_Params.json";

        try
        {
            StreamReader       reader = new StreamReader(path, false);
            string             json   = reader.ReadToEnd();
            TrackingParameters obj    = JsonUtility.FromJson <TrackingParameters>(json);
            reader.Close();
            myScript.tracking = obj;
        } catch
        {
            Debug.LogWarning("Config file was empty.");
            myScript.tracking = new TrackingParameters();
        }
    }
Esempio n. 6
0
    void Count()
    {
        count++;
        if (count == 10)
        {
            TrackingManager.TrackingCall_EasterEgg("10", PlayerLevel.Instance.GetCurrentLevel());
            WaypointMover          mover = gameObject.AddComponent <WaypointMover>();
            UnitRotationController contr = gameObject.AddComponent <UnitRotationController>().Init(mover, _foo);
            contr.TurnToPosition(Camera.main.transform, () => m_animation.SetTrigger(UnitAnimationTypes.bAggro.ToString()));
        }
        else if (count == 20)
        {
            TrackingManager.TrackingCall_EasterEgg("20", PlayerLevel.Instance.GetCurrentLevel());
            m_animation.SetTrigger(UnitAnimationTypes.bDying.ToString());
        }
        else if (count == 3 || (count > 3 && M_Math.Roll(0.1f)))
        {
            TrackingManager.TrackingCall_EasterEgg("3", PlayerLevel.Instance.GetCurrentLevel());

            m_animation.SetTrigger(UnitAnimationTypes.bHit.ToString());
        }
    }
Esempio n. 7
0
        /// <summary>
        /// Carga la información sobre la trazabilidad de los productos adquiridos.
        /// </summary>
        private void LoadProductTracking()
        {
            try
            {
                TrackingManager trackingManager = new TrackingManager();
                List <Tracking> accountsDetail  = trackingManager.Get(SessionHelper.GetUser());

                if (trackingManager.HasErrors)
                {
                    ((front)Master).Alert.Show("Error", trackingManager.ErrorDescription);
                }
                else
                {
                    productRepeater.DataSource = accountsDetail;
                    productRepeater.DataBind();
                }
            }
            catch (Exception exception)
            {
                ((front)Master).Alert.Show("Exception", exception.Message);
            }
        }
        public void UpdateFedexTrackOrders()
        {
            while (true)
            {
                using (var db = new UnitOfWork(_log))
                {
                    var service             = new UpdateOrderTrackingStatus(_company.Id, null, TimeSpan.FromSeconds(10));
                    var actionService       = new SystemActionService(_log, _time);
                    var dbFactory           = new DbFactory();
                    var notificationService = new NotificationService(_log, _time, dbFactory);
                    var companyAddress      = new CompanyAddressService(_company);
                    var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                    var ruleList            = new List <ITrackingRule>()
                    {
                    };

                    var trackingService = new TrackingManager(_log, actionService, addressService, _emailService, _time, ruleList);
                    var fedexInfo       = _company.ShipmentProviderInfoList.FirstOrDefault(sh => sh.Type == (int)ShipmentProviderType.FedexOneRate);

                    var fedexTrackingProvider = new FedexTrackingApi(_log,
                                                                     _time,
                                                                     fedexInfo.EndPointUrl,
                                                                     fedexInfo.UserName,
                                                                     fedexInfo.Password,
                                                                     fedexInfo.Key1,
                                                                     fedexInfo.Key2,
                                                                     fedexInfo.Key3,
                                                                     _company.ShortName);

                    service.UpdateAllShippedOrderStatus(trackingService,
                                                        _time,
                                                        db,
                                                        fedexTrackingProvider,
                                                        _company);
                }
                Thread.Sleep(TimeSpan.FromMinutes(0));
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Upload simple file.
        /// </summary>
        /// <param name="folder">The destination folder</param>
        /// <returns>Task to support await of async call.</returns>
        public static async Task UploadSimpleFileAsync(Services.OneDrive.OneDriveStorageFolder folder)
        {
            Shell.Current.DisplayWaitRing = true;

            try
            {
                if (folder != null)
                {
                    var selectedFile = await OpenLocalFileAsync();

                    if (selectedFile != null)
                    {
                        using (var localStream = await selectedFile.OpenReadAsync())
                        {
                            var fileCreated = await folder.CreateFileAsync(selectedFile.Name, CreationCollisionOption.GenerateUniqueName, localStream);
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);
            }
            catch (ServiceException graphEx)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(graphEx.Error.Message);
            }
            catch (Exception ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);

                TrackingManager.TrackException(ex);
            }
            finally
            {
                Shell.Current.DisplayWaitRing = false;
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Saves multiple values on the visitor, if their key does not start with NcbtPropertyPrefix.
        /// </summary>
        /// <param name="values"></param>
        public static void SetProperties(IDictionary <string, object> values)
        {
            if (IsCrawler)
            {
                return;
            }

            var clone = new Dictionary <string, object>(values);

            foreach (var pair in clone)
            {
                if (pair.Key.StartsWith(NcbtPropertyPrefix))
                {
                    clone.Remove(pair.Key);
                }
            }

            var currentVisitorId = TrackingManager.SetVisitorProperty(VisitorId, clone);

            if (!currentVisitorId.IsNullOrWhiteSpace())
            {
                VisitorId = currentVisitorId;
            }
        }
Esempio n. 11
0
	// ================================================================================================================
	// MAIN EVENT INTERFACE -------------------------------------------------------------------------------------------

	void Awake() {
		instance = this;
	}
Esempio n. 12
0
 void Awake()
 {
     instance  = this;
     startTime = DateTime.Now.ToShortTimeString();
 }
Esempio n. 13
0
        private async Task BootstrapFrame(LaunchActivatedEventArgs launchActivatedEventArgs, IActivatedEventArgs activatedEventArgs, string addTaskTitle = null)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                try
                {
                    ApplicationView appView = ApplicationView.GetForCurrentView();
                    this.mainview = appView;
                    SetupTitleBar(appView);
                    SetupStatusBar(appColor);

                    appView.SetPreferredMinSize(new Size(Constants.AppMinWidth, Constants.AppMinHeight));

                    this.bootstraper = new Bootstraper(ApplicationVersion.GetAppVersion());

                    InitializeViewLocator();

                    await this.bootstraper.ConfigureAsync(rootFrame);

                    this.navigationService = Ioc.Resolve <INavigationService>();
                    this.platformService   = Ioc.Resolve <IPlatformService>();

                    this.suspensionManager = new SuspensionManager(Ioc.Resolve <IPersistenceLayer>(), Ioc.Resolve <ISynchronizationManager>(), Ioc.Resolve <ITileManager>());

                    rootFrame.Navigated        += this.OnNavigated;
                    rootFrame.NavigationFailed += this.OnNavigationFailed;

                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;

                    if (rootFrame.Content == null)
                    {
                        Type   startupPage         = typeof(MainPage);
                        object navigationParameter = launchActivatedEventArgs?.Arguments;

                        var startupManager = Ioc.Resolve <IStartupManager>();
                        if (startupManager.IsFirstLaunch)
                        {
                            startupPage = typeof(WelcomePage);
                        }
                        else if (!String.IsNullOrWhiteSpace(addTaskTitle))
                        {
                            startupPage         = typeof(WelcomePage);
                            navigationParameter = new TaskCreationParameters {
                                Title = addTaskTitle
                            };
                        }

                        SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackRequested;
                        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
                        Window.Current.VisibilityChanged += this.OnVisibilityChanged;

                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation parameter
                        rootFrame.Navigate(startupPage, navigationParameter);
                    }

                    if (launchActivatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                    }
                    else if (activatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(activatedEventArgs);
                    }

                    // Ensure the current window is active
                    Window.Current.Activate();
                }
                catch (Exception ex)
                {
                    var messageBoxService = new MessageBoxService(new NavigationService(rootFrame));
                    await messageBoxService.ShowAsync("Error", "2Day was unable to start please send a screenshot of this page to the development team. Details: " + ex);

                    DeviceFamily deviceFamily = DeviceFamily.Unkown;
                    if (this.platformService != null)
                    {
                        deviceFamily = this.platformService.DeviceFamily;
                    }

                    var trackingManager = new TrackingManager(true, deviceFamily);
                    trackingManager.Exception(ex, "Bootstrap", true);
                }
            }
            else
            {
                if (launchActivatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                }
                else if (activatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(activatedEventArgs);
                }
            }
        }
Esempio n. 14
0
        private async Task SigninAsync(int indexProvider, string appClientId)
        {
            if (!await Tools.CheckInternetConnectionAsync())
            {
                return;
            }

            Shell.Current.DisplayWaitRing = true;
            bool succeeded = false;

            try
            {
                // OnlineId
                if (indexProvider == 0)
                {
                    OneDriveService.Instance.Initialize();
                }
                else if (indexProvider == 1)
                {
                    OneDriveService.Instance.Initialize(appClientId, AccountProviderType.Msa, OneDriveScopes.OfflineAccess | OneDriveScopes.ReadWrite);
                }
                else if (indexProvider == 2)
                {
                    OneDriveService.Instance.Initialize(appClientId, AccountProviderType.Adal);
                }
                else if (indexProvider == 3)
                {
                    OneDriveService.Instance.Initialize(appClientId, AccountProviderType.Msal);
                }

                if (!await OneDriveService.Instance.LoginAsync())
                {
                    throw new Exception("Unable to sign in");
                }

                _currentFolder = _rootFolder = await OneDriveService.Instance.RootFolderAsync();

                OneDriveItemsList.ItemsSource = _rootFolder.GetItemsAsync();
                succeeded = true;
            }
            catch (ServiceException serviceEx)
            {
                await OneDriveSampleHelpers.DisplayOneDriveServiceExceptionAsync(serviceEx);
            }
            catch (Exception ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);

                TrackingManager.TrackException(ex);
            }
            finally
            {
                Shell.Current.DisplayWaitRing = false;
            }

            if (succeeded)
            {
                FilesBox.Visibility       = Visibility.Visible;
                UserBox.Visibility        = Visibility.Visible;
                ClientIdBox.Visibility    = Visibility.Collapsed;
                ClientIdHelper.Visibility = Visibility.Collapsed;
                LogOutButton.Visibility   = Visibility.Visible;
                ConnectButton.Visibility  = Visibility.Collapsed;
                menuButton.Visibility     = Visibility.Visible;
                BackButton.Visibility     = Visibility.Visible;
            }
            else
            {
                FilesBox.Visibility       = Visibility.Collapsed;
                UserBox.Visibility        = Visibility.Collapsed;
                ClientIdBox.Visibility    = Visibility.Visible;
                ClientIdHelper.Visibility = Visibility.Visible;
                LogOutButton.Visibility   = Visibility.Collapsed;
                ConnectButton.Visibility  = Visibility.Visible;
                menuButton.Visibility     = Visibility.Collapsed;
                BackButton.Visibility     = Visibility.Collapsed;
            }
        }
Esempio n. 15
0
        public void ProcessRequest(HttpContext context)
        {
            LogHelper.Info(MethodBase.GetCurrentMethod().DeclaringType, "[ncBT - Scheduler] Start task");

            // Fetch all active actions
            var actions = Action.GetAllLight()
                          .Where(x => x.ActionType != ActionTypeEnum.Inactive)
                          .ToList();
            // Fetch all segments
            var segments = Models.Segment.GetAll().ToDictionary(x => x.Id, x => x);
            // Fetch all properties
            var properties = Property.GetAllLight().ToDictionary(x => x.Id, x => x);

            // Create UmbracoHelper
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            // Get sender email
            var senderEmail = ConfigurationHelper.Settings.Email.Sender;

            // Go through all mail actions
            foreach (var action in actions.Where(x => x.ActionType == ActionTypeEnum.Email))
            {
                // Make sure we have a valid segment
                if (!segments.ContainsKey(action.SegmentId))
                {
                    continue;
                }
                // Make sure we have a valid property
                if (!properties.ContainsKey(action.EmailPropertyId))
                {
                    continue;
                }

                // Pull segment
                var segment = segments[action.SegmentId];
                // Pull property
                var emailProperty = properties[action.EmailPropertyId];
                // Construct flag property
                var flagPropertyAlias = "ncbt.flags.action" + action.Id;

                // Fetch visitors in segment, with email property, not having the flag property
                var segmentProperties = new Dictionary <string, bool>
                {
                    { flagPropertyAlias, false },
                    { emailProperty.Alias, true }
                };
                var visitors = TrackingManager.GetVisitorsInSegmentWithProperties(segment.Alias, segmentProperties);
                LogHelper.Info(MethodBase.GetCurrentMethod().DeclaringType, "[ncBT - Scheduler] Action " + action.Alias + " matched " + visitors.Count + " visitors");

                // Get email node
                var node = umbracoHelper.TypedContent(action.EmailNodeId);

                // Go through visitors
                foreach (var visitor in visitors)
                {
                    LogHelper.Info(MethodBase.GetCurrentMethod().DeclaringType, "[ncBT - Scheduler] - Visitor: " + visitor._id);

                    // Get visitor email
                    var visitorEmail = string.Empty;
                    foreach (var visitorProperty in visitor)
                    {
                        // Find property
                        if (visitorProperty.Key == emailProperty.Alias)
                        {
                            visitorEmail = visitorProperty.Value.Value.ToString();
                        }
                    }
                    // Make sure we're valid
                    if (!visitorEmail.IsNullOrWhiteSpace() && node != null)
                    {
                        // Render mail
                        var emailBody = NcbtEmailHelper.RenderEmail(umbracoHelper, node, visitor);
                        // Send mail to visitor
                        NcbtEmailHelper.SendMail(senderEmail, visitorEmail, action.EmailSubject, emailBody, true);
                        // Add flag property
                        TrackingManager.SetVisitorProperty(visitor._id.ToString(), flagPropertyAlias, "email sent");
                    }
                }
            }

            LogHelper.Info(MethodBase.GetCurrentMethod().DeclaringType, "[ncBT - Scheduler] End task");
        }
Esempio n. 16
0
 public void SendChessboardMovement(ChessboardMovement movement)
 {
     TrackingManager.SendChessboardMovement(movement);
 }
Esempio n. 17
0
 /// <summary>
 /// Tick to process queue from tracking thread
 /// </summary>
 public void ProcessQueueTick()
 {
     TrackingManager.ProcessQueue();
 }
Esempio n. 18
0
 public void Recalibrate()
 {
     TrackingManager.Recalibrate();
 }
Esempio n. 19
0
 public void StopTracking()
 {
     TrackingManager.StopTracking();
 }
Esempio n. 20
0
 public void StartTracking()
 {
     TrackingManager.StartTracking();
 }
        private async Task SigninAsync(string appClientId)
        {
            if (!await Tools.CheckInternetConnectionAsync())
            {
                return;
            }

            SampleController.Current.DisplayWaitRing = true;
            bool succeeded = false;

            try
            {
                // Converged app authentication
                // Get the selected Delegated Permissions
                var scopes = DelegatedPermissions.SelectedItems as string[];

                // If the user hasn't selected a scope then set it to FilesReadAll
                if (scopes == null)
                {
                    scopes = new string[] { MicrosoftGraphScope.FilesReadAll };
                }

                OneDriveService.Instance.Initialize(appClientId, scopes, null, null);

                if (!await OneDriveService.Instance.LoginAsync())
                {
                    throw new Exception("Unable to sign in");
                }

                _graphCurrentFolder = _graphRootFolder = await OneDriveService.Instance.RootFolderForMeAsync();

                OneDriveItemsList.ItemsSource = await _graphRootFolder.GetItemsAsync(20);

                OneDriveItemsList.Visibility = Visibility.Visible;

                succeeded = true;
            }
            catch (ServiceException serviceEx)
            {
                await OneDriveSampleHelpers.DisplayOneDriveServiceExceptionAsync(serviceEx);
            }
            catch (Exception ex)
            {
                await OneDriveSampleHelpers.DisplayMessageAsync(ex.Message);

                TrackingManager.TrackException(ex);
            }
            finally
            {
                SampleController.Current.DisplayWaitRing = false;
            }

            if (succeeded)
            {
                FilesBox.Visibility       = Visibility.Visible;
                UserBox.Visibility        = Visibility.Visible;
                ClientIdBox.Visibility    = Visibility.Collapsed;
                ClientIdHelper.Visibility = Visibility.Collapsed;
                LogOutButton.Visibility   = Visibility.Visible;
                ConnectButton.Visibility  = Visibility.Collapsed;
                menuButton.Visibility     = Visibility.Visible;
                BackButton.Visibility     = Visibility.Visible;
            }
            else
            {
                FilesBox.Visibility       = Visibility.Collapsed;
                UserBox.Visibility        = Visibility.Collapsed;
                ClientIdBox.Visibility    = Visibility.Visible;
                ClientIdHelper.Visibility = Visibility.Visible;
                LogOutButton.Visibility   = Visibility.Collapsed;
                ConnectButton.Visibility  = Visibility.Visible;
                menuButton.Visibility     = Visibility.Collapsed;
                BackButton.Visibility     = Visibility.Collapsed;
            }
        }
Esempio n. 22
0
 protected void Page_Load(object sender, EventArgs e)
 {
     AddProjectionScripts();
     TrackingManager.TrackUse(Request.GetNormalizedParameters(), true);
 }
Esempio n. 23
0
        public async void SafeRun(IBackgroundTaskInstance taskInstance)
        {
            bool hadException = false;

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += this.OnTaskCanceled;

            WinSettings.Instance.SetValue(CoreSettings.BackgroundLastStartExecution, DateTime.Now);
            ReportStatus(BackgroundExecutionStatus.Started);

            LogService.Initialize(new WinLogHandler());
            LogService.Level = WinSettings.Instance.GetValue <LogLevel>(CoreSettings.LogLevel);

            ResourcesLocator.Initialize("ms-appx://", UriKind.Absolute);

            var mutex = new Mutex(false, Constants.SyncPrimitiveAppRunningForeground);

            if (!mutex.WaitOne(1))
            {
                LogService.Log("Agent", "Skipping background agent because app is foreground");
                await LogService.SaveAsync();

                this.deferral.Complete();

                ReportStatus(BackgroundExecutionStatus.Skipped);

                return;
            }

            ITrackingManager trackingManager = null;

            try
            {
                this.persistenceLayer = new WinPersistenceLayer(automaticSave: false);

                var deviceFamily = DeviceFamily.Unkown;

                if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsDesktop;
                }
                else if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Mobile", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsMobile;
                }

                trackingManager = new TrackingManager(false, deviceFamily);

                var workbook = this.persistenceLayer.Open(tryUpgrade: true) as Workbook;

                if (workbook != null)
                {
                    ReportStatus(BackgroundExecutionStatus.WorkbookLoaded);

                    Ioc.RegisterInstance <IWorkbook, Workbook>(workbook);
                    workbook.Initialize();

                    // important: load alarm manager so that we update reminders properly is a recurring task is created
                    var alarmManager = new AlarmManager(workbook);

                    var backgroundSyncManager = new BackgroundSynchronizationManager(workbook, trackingManager, ToastHelper.ToastMessage);
                    await backgroundSyncManager.SetupAsync();

                    if (backgroundSyncManager.CanSync())
                    {
                        ReportStatus(BackgroundExecutionStatus.SyncStarted);

                        this.synchronizationManager = backgroundSyncManager.SynchronizationManager;

                        if (workbook.Settings.GetValue <bool>(CoreSettings.BackgroundToast))
                        {
                            this.synchronizationManager.OperationCompleted += (s, e) => ToastHelper.ToastMessage(e.Item);
                            this.synchronizationManager.OperationFailed    += (s, e) => ToastHelper.ToastMessage(e.Message);
                        }

                        bool result = await backgroundSyncManager.TrySyncAsync(this.persistenceLayer);

                        if (result)
                        {
                            ReportStatus(BackgroundExecutionStatus.SyncCompleted);
                        }
                        else
                        {
                            ReportStatus(BackgroundExecutionStatus.SyncError);
                        }
                    }

                    // update tiles
                    ReportStatus(BackgroundExecutionStatus.TileStarted);

                    TileManager timeManager = new TileManager(workbook, trackingManager, null, true);
                    await timeManager.LoadSecondaryTilesAsync();

                    timeManager.UpdateTiles();

                    ReportStatus(BackgroundExecutionStatus.TileCompleted);

                    // save log
                    await LogService.SaveAsync();
                }
                else
                {
                    ReportStatus(BackgroundExecutionStatus.WorkbookNotLoaded);
                }
            }
            catch (Exception ex)
            {
                hadException = true;

                LogService.Level |= LogLevel.Debug;
                LogService.Log("WinBackgroundTaskHelper", "Exception during background execution: " + ex.GetAllMessages());

                if (trackingManager != null)
                {
                    trackingManager.Exception(ex, "Exception Background task helper");
                }

                ReportStatus(BackgroundExecutionStatus.CompletedException);
            }

            if (!hadException)
            {
                ReportStatus(BackgroundExecutionStatus.CompletedSuccess);
            }

            await LogService.SaveAsync();

            WinSettings.Instance.SetValue(CoreSettings.BackgroundLastEndExecution, DateTime.Now);

            this.deferral.Complete();
        }
Esempio n. 24
0
        public Kinect(BlockingCollection <Message> processingCommandsQueue, KinectDataBuffer buffer, TrackingManager trackingManager)
        {
            CommandsQueue   = processingCommandsQueue;
            Buffer          = buffer;
            TrackingManager = trackingManager;

            KinectSensor = KinectSensor.GetDefault();

            Reader = KinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.Infrared);
            Reader.MultiSourceFrameArrived += MultisourceFrameArrived;

            CoordinateMapper = KinectSensor.CoordinateMapper;

            ColorFrameDescription    = KinectSensor.ColorFrameSource.FrameDescription;
            DepthFrameDescription    = KinectSensor.DepthFrameSource.FrameDescription;
            InfraredFrameDescription = KinectSensor.InfraredFrameSource.FrameDescription;

            KinectSensor.Open();

            // initial message for pipeline, causes it to wait for input and throw exception if nothing arrives
            CommandsQueue.Add(new KinectUpdateMessage(null));
        }
Esempio n. 25
0
        /// <summary>
        /// Checks and reads the current local datafile
        /// </summary>
        /// <param name="dbDatafile"></param>
        private async void CheckLocalDatafile(DBDatafileModel dbDatafile)
        {
            try
            {
                ObservableCollection <TwoFACodeModel> deserializeCollection = new ObservableCollection <TwoFACodeModel>();

                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(dbDatafile.Path);

                if (await FileService.FileExistsAsync(dbDatafile.Name, folder))
                {
                    var dbHash = await App.Repository.Password.GetAsync();

                    // prevent write of the datafile
                    _initialization = true;
                    try
                    {
                        string datafileStr = await FileService.ReadStringAsync(dbDatafile.Name, folder);

                        if (!string.IsNullOrEmpty(datafileStr))
                        {
                            // read the iv for AES
                            DatafileModel datafile = NewtonsoftJSONService.Deserialize <DatafileModel>(datafileStr);
                            var           iv       = datafile.IV;

                            datafile = NewtonsoftJSONService.DeserializeDecrypt <DatafileModel>(
                                SecretService.Helper.ReadSecret(Constants.ContainerName, dbHash.Hash),
                                iv,
                                datafileStr);
                            deserializeCollection = datafile.Collection;
                        }
                    }
                    catch (Exception)
                    {
                        ShowPasswordError();
                    }
                }
                // file not found case
                else
                {
                    ShowFileOrFolderNotFoundError();
                }

                if (deserializeCollection != null)
                {
                    Collection.AddRange(deserializeCollection);
                    if (Collection.Count == 0)
                    {
                        // if no error has occured
                        if (!_errorOccurred)
                        {
                            EmptyAccountCollectionTipIsOpen = true;
                        }
                    }
                    else
                    {
                        if (EmptyAccountCollectionTipIsOpen)
                        {
                            EmptyAccountCollectionTipIsOpen = false;
                        }
                    }
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception exc)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                if (exc is UnauthorizedAccessException)
                {
                    ShowUnauthorizedAccessError();
                }
                else if (exc is FileNotFoundException)
                {
                    ShowFileOrFolderNotFoundError();
                }
                else
                {
                    _errorOccurred = true;
                    TrackingManager.TrackException(exc);
                    ErrorDialogs.ShowUnexpectedError(exc);
                }
            }
            // writing the data file is activated again
            _initialization = false;
        }
Esempio n. 26
0
        //  private IVideoSource src;

        private async void UpdateLoop()
        {
            var conf    = ConfigIO.LoadUserConfig();
            var cam     = new Camera(conf.CameraInfo);
            var tracker = new TrackingManager(conf);

            //cap = new VideoCapture(1);
            //cap.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth, 640);
            //cap.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight, 480);
            //cap.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps, 60);

            // Paths:
            // pseye:0 -> 0th PS EYE
            // dshow:0 -> 0th DSHOW
            // dshow:1 -> ...

            //src = new PSEyeVideoSource(0);
            //src.Open();


            var frames    = 0;
            var lastReset = DateTime.Now;

            while (running)
            {
                var t = await Task.Run(() =>
                {
                    return(cam.Update());
                });

                if (t)
                {
                    imageBox1.Image = cam.Frame;

                    await tracker.UpdateVideo(cam.HsvFrame, cam.FrameBrightness);

                    imageBox2.Image = tracker.Trackers[0].Frame;

                    AdvancedTracking(tracker.Trackers[0].TrackedController.Position, tracker.Trackers[0].Detected);

                    frames++;
                }


                if ((DateTime.Now - lastReset).TotalSeconds > 1)
                {
                    Console.WriteLine(frames);
                    frames    = 0;
                    lastReset = DateTime.Now;
                }
            }

            /*if (cam.Update())
             * {
             *  await tracker.UpdateVideo(cam.HsvFrame, cam.FrameBrightness);
             *  imageBox1.Image = cam.Frame;
             *  imageBox2.Image = tracker.Trackers[0].Frame;
             *
             *  AdvancedTracking(tracker.Trackers[0].TrackedController.Position, tracker.Trackers[0].Detected);
             * }*/
        }
Esempio n. 27
0
        public async Task HandleCommandAsync()
        {
            // This should match the uap:AppService and VoiceCommandService references from the
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (this.triggerDetails != null && this.triggerDetails.Name == CortanaConstants.BackgroundServiceName)
            {
                try
                {
                    DeviceFamily deviceFamily = DeviceFamily.Unkown;
                    if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop", StringComparison.OrdinalIgnoreCase))
                    {
                        deviceFamily = DeviceFamily.WindowsDesktop;
                    }
                    else if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Mobile", StringComparison.OrdinalIgnoreCase))
                    {
                        deviceFamily = DeviceFamily.WindowsMobile;
                    }

                    this.trackingManager = new TrackingManager(false, deviceFamily);

                    this.voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(this.triggerDetails);
                    this.voiceServiceConnection.VoiceCommandCompleted += this.OnVoiceCommandCompleted;

                    Windows.ApplicationModel.VoiceCommands.VoiceCommand voiceCommand = await this.voiceServiceConnection.GetVoiceCommandAsync();

                    CortanaBackgroundCommandBase backgroundCommand = null;
                    foreach (var command in this.commands)
                    {
                        if (command.CommandName.Equals(voiceCommand.CommandName, StringComparison.OrdinalIgnoreCase))
                        {
                            backgroundCommand = command;
                            break;
                        }
                    }

                    if (backgroundCommand != null)
                    {
                        await CortanaDialogHelper.ShowProgressScreen(this.voiceServiceConnection, StringResources.Message_LoadingTasks);

                        this.persistenceLayer = new WinPersistenceLayer(automaticSave: false);
                        var workbook = this.persistenceLayer.Open(tryUpgrade: true);
                        workbook.Initialize();

                        VoiceCommandResponse response = backgroundCommand.Execute(workbook, this.persistenceLayer, voiceCommand);

                        bool success = false;
                        if (response != null)
                        {
                            await this.voiceServiceConnection.ReportSuccessAsync(response);

                            success = true;
                        }

                        this.trackingManager.TagEvent("Cortana", new Dictionary <string, string>
                        {
                            { "Command", backgroundCommand.CommandName },
                            { "Success", success.ToString() },
                            { "Language", CultureInfo.CurrentUICulture?.ToString() ?? "unkown" }
                        });
                    }
                    else
                    {
                        // As with app activation VCDs, we need to handle the possibility that
                        // an app update may remove a voice command that is still registered.
                        // This can happen if the user hasn't run an app since an update.
                        this.LaunchAppInForeground();
                    }
                }
                catch (Exception ex)
                {
                    if (this.trackingManager != null)
                    {
                        this.trackingManager.Exception(ex, "Cortana background service");
                    }
                }
            }
        }
Esempio n. 28
0
    // Use this for initialization
    void Start()
    {
        if (sRefCount == 0)
        {
            TrackingWrapper.Initialize ();
            sSingleton = this;
        }

        sRefCount++;

        if( NumberOfPlayers == 0 )
            NumberOfPlayers = PlayerPrefs.GetInt ("NumPlayers", 1);

        mPlayerThrowing = new bool[NumberOfPlayers];
        mPlayerXs = new LinkedList<float>[NumberOfPlayers];
        mPlayerPositions = new Vector3[NumberOfPlayers];
        mLastFire = new float[NumberOfPlayers];
    }
Esempio n. 29
0
 public StateContext(IProgramState internalState, UserInterfaceOutputFacade outputFacade, GameController gameController, TrackingManager trackingManager, TrackingResultProcessing trackingResultProcessing)
 {
     InternalState            = internalState;
     OutputFacade             = outputFacade;
     GameController           = gameController;
     TrackingManager          = trackingManager;
     TrackingResultProcessing = trackingResultProcessing;
 }
Esempio n. 30
0
 private void Awake()
 {
     Instance = this;
 }
Esempio n. 31
0
        /// <summary>
        /// Procedure invoked by Kinect when new data are available
        /// </summary>
        private void MultisourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            if (KinectSensor == null || Reader == null)
            {
                return;
            }

            // acquire frame data
            MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame();

            // if the Frame has expired by the time we process this event, return.
            if (multiSourceFrame == null)
            {
                return;
            }

            // Continue only if buffer is empty
            if (!Buffer.IsEmpty())
            {
                return;
            }

            // declare variables for data from sensor
            ColorFrame    colorFrame    = null;
            DepthFrame    depthFrame    = null;
            InfraredFrame infraredFrame = null;

            byte[]             colorFrameData                 = null;
            ushort[]           depthData                      = null;
            ushort[]           infraredData                   = null;
            DepthSpacePoint[]  pointsFromColorToDepth         = null;
            ColorSpacePoint[]  pointsFromDepthToColor         = null;
            CameraSpacePoint[] cameraSpacePointsFromDepthData = null;

            try
            {
                // get frames from sensor
                colorFrame    = multiSourceFrame.ColorFrameReference.AcquireFrame();
                depthFrame    = multiSourceFrame.DepthFrameReference.AcquireFrame();
                infraredFrame = multiSourceFrame.InfraredFrameReference.AcquireFrame();

                // If any frame has expired by the time we process this event, return.
                if (colorFrame == null || depthFrame == null || infraredFrame == null)
                {
                    return;
                }

                // use frame data to fill arrays
                colorFrameData = new byte[ColorFrameDescription.LengthInPixels * 4];
                depthData      = new ushort[DepthFrameDescription.LengthInPixels];
                infraredData   = new ushort[InfraredFrameDescription.LengthInPixels];

                colorFrame.CopyConvertedFrameDataToArray(colorFrameData, ColorImageFormat.Bgra);
                depthFrame.CopyFrameDataToArray(depthData);
                infraredFrame.CopyFrameDataToArray(infraredData);

                pointsFromColorToDepth         = new DepthSpacePoint[ColorFrameDescription.LengthInPixels];
                pointsFromDepthToColor         = new ColorSpacePoint[DepthFrameDescription.LengthInPixels];
                cameraSpacePointsFromDepthData = new CameraSpacePoint[DepthFrameDescription.LengthInPixels];

                using (KinectBuffer depthFrameData = depthFrame.LockImageBuffer())
                {
                    CoordinateMapper.MapColorFrameToDepthSpaceUsingIntPtr(
                        depthFrameData.UnderlyingBuffer,
                        depthFrameData.Size,
                        pointsFromColorToDepth);

                    CoordinateMapper.MapDepthFrameToColorSpaceUsingIntPtr(
                        depthFrameData.UnderlyingBuffer,
                        depthFrameData.Size,
                        pointsFromDepthToColor);

                    CoordinateMapper.MapDepthFrameToCameraSpaceUsingIntPtr(
                        depthFrameData.UnderlyingBuffer,
                        depthFrameData.Size,
                        cameraSpacePointsFromDepthData);
                }
            }
            finally
            {
                // dispose frames so that Kinect can continue processing
                colorFrame?.Dispose();
                depthFrame?.Dispose();
                infraredFrame?.Dispose();

                // send data futher
                if (
                    colorFrameData != null &&
                    depthData != null &&
                    infraredData != null &&
                    cameraSpacePointsFromDepthData != null
                    )
                {
                    // store data to buffer and notify processing thread
                    Buffer.Store(
                        new KinectData(
                            colorFrameData,
                            depthData,
                            infraredData,
                            cameraSpacePointsFromDepthData,
                            pointsFromColorToDepth,
                            pointsFromDepthToColor
                            )
                        );

                    TrackingManager.SendKinectUpdate();
                }
            }
        }
Esempio n. 32
0
 // Use this for initialization
 //get the key components
 void Start()
 {
     agent            = GetComponent <NavMeshAgent>();
     _trackingManager = FindObjectOfType <TrackingManager>();
 }
Esempio n. 33
0
        public override async Task <IWorkbook> ConfigureAsync(Frame rootFrame)
        {
            if (rootFrame == null)
            {
                throw new ArgumentNullException(nameof(rootFrame));
            }

            bool sendAnalytics = WinSettings.Instance.GetValue <bool>(CoreSettings.SendAnalytics);

            string deviceId = "n/a";

            try
            {
                var settings = WinSettings.Instance;
                if (!settings.HasValue(CoreSettings.DeviceId) || settings.GetValue <string>(CoreSettings.DeviceId) == "N/A")
                {
                    string id = this.ComputeDeviceId();
                    settings.SetValue(CoreSettings.DeviceId, id);
                }

                deviceId = settings.GetValue <string>(CoreSettings.DeviceId);
            }
            catch (Exception ex)
            {
                TrackingManagerHelper.Exception(ex, "Error while setting device id");
            }

            var platformService = new PlatformService(this.version, deviceId, () => CrashHandler.GetDiagnosticsInformation());

            Ioc.RegisterInstance <IPlatformService, PlatformService>(platformService);

            TrackingManager trackingManager = new TrackingManager(sendAnalytics, platformService.DeviceFamily);

            Ioc.RegisterInstance <ITrackingManager, TrackingManager>(trackingManager);

            HttpClientHandler.Setup();

            ResourcesLocator.Initialize("ms-appx://", UriKind.Absolute);
            if (!WinSettings.Instance.GetValue <bool>(CoreSettings.UseDarkTheme))
            {
                ResourcesLocator.UpdateTheme(true);
            }

            var persistence = Ioc.RegisterInstance <IPersistenceLayer, WinPersistenceLayer>(new WinPersistenceLayer(automaticSave: true));

            LogService.Log("Bootstraper", string.Format("Version: {0}", ApplicationVersion.GetAppVersion()));

            var navigationService = new NavigationService(rootFrame, platformService);

            Ioc.RegisterInstance <INavigationService, NavigationService>(navigationService);

            var messageBoxService = new MessageBoxService(navigationService);

            Ioc.RegisterInstance <IMessageBoxService, MessageBoxService>(messageBoxService);

            Ioc.RegisterInstance <ISpeechService, SpeechService>(new SpeechService(messageBoxService));

            var workbook = this.InitializeWorkbook(persistence, platformService);

            // we just read the latest value of data from the DB, so even if there was a background sync
            // we now have the latest version, so we remove the background sync flag here
            workbook.Settings.SetValue(CoreSettings.SyncBackgroundOccured, false);

            this.keyboardShortcutManager = new KeyboardShortcutManager(workbook, rootFrame, navigationService, trackingManager);

            var backgroundTaskManager = new BackgroundTaskManager(workbook);

            backgroundTaskManager.InitializeAsync();
            Ioc.RegisterInstance <IBackgroundTaskManager, BackgroundTaskManager>(backgroundTaskManager);

            var notificationService = new NotificationService();

            Ioc.RegisterInstance <INotificationService, NotificationService>(notificationService);

            var startupManager = Ioc.Build <StartupManager>();

            Ioc.RegisterInstance <IStartupManager, StartupManager>(startupManager);

            Ioc.RegisterInstance <IAlarmManager, AlarmManager>(new AlarmManager(workbook));

            var tileManager = new TileManager(workbook, trackingManager, notificationService, false);

            tileManager.LoadSecondaryTilesAsync();
            Ioc.RegisterInstance <ITileManager, TileManager>(tileManager);

            var synchronizationManager = await InitializeSyncAsync(workbook, platformService, trackingManager);

            // it is important to remove old task after sync is initialized otherwise changes would not
            // tracked and put in the changelog for the next sync
            workbook.RemoveOldTasks();

            var cortanaService = new CortanaRuntimeService(workbook);

            // no need to await this call because it can runs in the background
            Task.Run(() =>
            {
                JumpListManager.SetupJumpListAsync();
                cortanaService.SetupDefinitionsAsync();
            });
            Ioc.RegisterInstance <ICortanaRuntimeService, CortanaRuntimeService>(cortanaService);

            return(workbook);
        }
Esempio n. 34
0
 public DocumentTrackingController(ILogger <DocumentTrackingController> logger, TrackingManager manager, IMapper mapper)
 {
     _logger  = logger;
     _manager = manager;
     _mapper  = mapper;
 }