Beispiel #1
0
 /* SaveRunningInfo - Insert a RunningInfo into the database.
  * @param info - RunningInfo to be inserted.
  * return - Autoincrement Id of the RunningInfo.
  */
 public int SaveRunningInfo(RunningInfo info)
 {
     lock (locker)
     {
         if (info.Id != -1)
         {
             try
             {
                 database.Insert(info);
                 SQLiteCommand cmd = database.CreateCommand("SELECT last_insert_rowid()");
                 cmd.CommandText = "SELECT last_insert_rowid()";
                 Int64 LastRowID64 = cmd.ExecuteScalar <Int64>();
                 int   LastRowID   = (int)LastRowID64;
                 return(LastRowID);
             }
             catch (Exception e)
             {
                 database.Update(info);
                 return(info.Id);
             }
         }
         else
         {
             return(-1);
         }
     }
 }
 /*
  * OnResume - Override for onResume to store in the database when the applications resumes.
  */
 protected override void OnResume()
 {
     base.OnResume();
     info            = database.getRunningInfo(1);
     info.background = false;
     database.UpdateRunningInfo(info);
 }
        /*
         * CheckNotifications - Check if a notification is needed, push the notification if needed.
         */
        protected void CheckNotifications()
        {
            while (true)
            {
                info = database.getRunningInfo(1);
                if (info.notificationNeeded == true && info.background == true)
                {
                    var contentIntent = PendingIntent.GetActivity(this, 0, new Intent(this, this.GetType()), 0);
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                         .SetAutoCancel(true)
                                                         .SetContentIntent(contentIntent)
                                                         .SetContentTitle("Hey there")
                                                         .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                                         .SetVibrate(new long[] { 1000, 1000 })
                                                         .SetSmallIcon(Resource.Drawable.notti_icon)
                                                         .SetContentText(String.Format("We need your attention over here"));

                    NotificationManager notificationManager =
                        (NotificationManager)GetSystemService(Context.NotificationService);
                    notificationManager.Notify(ButtonClickNotificationId, builder.Build());
                    info.notificationNeeded = false;
                    database.UpdateRunningInfo(info);
                }
                Thread.Sleep(10000);
            }
        }
Beispiel #4
0
 /*
  * askLocation - View session live for more details.
  */
 private async void askLocation()
 {
     await Task.Delay(100).ContinueWith(async(arg) => {
         Task.Delay(GlobalUtilities.locationTime).Wait();
         while (getlocation)
         {
             gettingLocation = true;
             var change      = GetLocation();
             change.Wait();
             bool realChange = change.Result;
             if (!realChange)
             {
                 getlocation                 = false;
                 interrupt                   = new Interrupts();
                 interrupt.reason            = "Change location";
                 DateTime toBeClonedDateTime = DateTime.Now;
                 interrupt.start             = toBeClonedDateTime;
                 var answer                  = Task.FromResult(false);
                 bool realAnwser             = false;
                 RunningInfo info            = database.getRunningInfo(1);
                 if (info.background)
                 {
                     info.notificationNeeded = true;
                     database.UpdateRunningInfo(info);
                 }
                 Device.BeginInvokeOnMainThread(
                     async() =>
                 {
                     realAnwser = await DisplayAlert("Location Change", "Hey there your location change, are you still working?", "Yes.", "No, pause.");
                     if (!realAnwser)
                     {
                         interrupt.Id = database.SaveInterrupt(interrupt);
                         getlocation  = false;
                     }
                     else
                     {
                         getlocation = true;
                     }
                     gettingLocation = false;
                 });
             }
             else
             {
                 gettingLocation = false;
             }
             while (gettingLocation)
             {
                 ;
             }
             Task.Delay(GlobalUtilities.locationTime).Wait();
         }
     });
 }
Beispiel #5
0
 /* UpdateRunningInfo - Update specific running info.
  * @param info - RunningInfo to be update.
  */
 public void UpdateRunningInfo(RunningInfo info)
 {
     lock (locker)
     {
         if (database.Table <RunningInfo>().Count() == 0)
         {
             return;
         }
         else
         {
             database.Update(info);
         }
     }
 }
Beispiel #6
0
 public static void RegisterInfo(Transaction tran)
 {
     if (alreadyRegistered)
     {
         return;
     }
     alreadyRegistered = true;
     if (RunningInfo.EspaceName == "ContactManager")
     {
         Reset(tran);
         RunningInfo.RegisterEntryPoint(tran, "Home", true);
     }
     RegisterAssembly(tran, "ContactManager", ConfigurationManager.AppSettings["OutSystems.HubEdition.EspaceCompilationHash"], false, "1", "WbpDBplEq0WV9cLtjo9DNg:IIeE5bweh2x5P3TkcSgJyw\nR5jTByrm4ESUvnM+_9raCw:Rfq1vcifDI83qHvb9+mtfA\nSEJUCNmtZkKDQZaGFGnuCQ:islUpcXpwRYPZke1jBcYrw\nbNIUEN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EAw");
 }
Beispiel #7
0
 public static void RegisterInfo(Transaction tran)
 {
     if (alreadyRegistered)
     {
         return;
     }
     alreadyRegistered = true;
     if (RunningInfo.EspaceName == "Address_CS")
     {
         Reset(tran);
     }
     RegisterAssembly(tran, "Address_CS", ConfigurationManager.AppSettings["OutSystems.HubEdition.EspaceCompilationHash"], false, "1", "WK8dCdPZhUSoqVMa8mDZjQ:cqbwXmvrVneU2hm+6cAoGQ\n4Mq+Y8Ogz0ijgylaJ7wVkQ:iPqk6it65xL+lq9bd+apaQ\nptGCa4RnlESpXSVw3+_Gtg:ABzQdaaKGfAKrvADOtEBrQ\npk8tmXeXqkqQi+OSq3X6xQ:o1bNagfsn9yKXjz_jdSAfA\nhIWpySV1SUqfbfcJA4FVQg:+3YEtzq4Csr8cLK4OOIdlA\nliSz1aQ6akWLFwxTvi_KDg:p9zJseTp4y2mHVL1iY+K6A");
     RunningInfo.InvokeRegister(tran, "ssBusiness_CS._RunningInfo, Business_CS");
     RunningInfo.RegisterAssemblyDependency(tran, "Address_CS", "Business_CS", "_LZkxnqGQUibtaYHV6m08w:JrEA8PENBZITKbtkSQKDfA");
 }
Beispiel #8
0
        /// <summary>
        /// 获取数据状态
        /// </summary>
        /// <returns></returns>
        public BasicResponse <bool> GetDbState()
        {
            BasicResponse <bool> response = new BasicResponse <bool>();

            RunningInfo runningInfo = new RunningInfo();

            GetDbInfo(runningInfo);
            if (runningInfo.DbState == 1)
            {
                response.Data = true;
            }
            else
            {
                response.Data = false;
            }
            return(response);
        }
Beispiel #9
0
        /// <summary>
        /// 获取数据库信息
        /// </summary>
        /// <param name="runInfo"></param>
        private void GetDbInfo(RunningInfo runInfo)
        {
            var repository = _Repository as ConfigRepository;

            string dbName = _Repository.DatebaseName;
            string sql    = @"SELECT
	                        concat(
		                        round(
			                        sum(data_length / 1024 / 1024),
			                        2
		                        ),
		                        ''
	                        ) AS data_length_MB,
	                        concat(
		                        round(
			                        sum(index_length / 1024 / 1024),
			                        2
		                        ),
		                        ''
	                        ) AS index_length_MB
                        FROM
	                        information_schema.TABLES
                        WHERE
	                        table_schema = '{0}'"    ;

            sql = string.Format(sql, dbName);

            try
            {
                System.Data.DataTable dt = repository.QueryTableBySql(sql);

                if (dt != null && dt.Rows.Count > 0)
                {
                    runInfo.DbState = 1;
                    runInfo.DbSize  = TypeConvert.ToDecimal(dt.Rows[0]["data_length_MB"]);
                }
            }
            catch (Exception ex)
            {
                runInfo.DbState = 0;

                LogHelper.Error(ex);
            }
        }
        RunningInfo info;             // Running info.

        /*
         * OnCreate - Constructor for the activity.
         */
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            Forms.Init(this, bundle);
            LoadApplication(new App());
            Xamarin.FormsMaps.Init(this, bundle);
            myThreadDelegate        = new ThreadStart(CheckNotifications);
            myThread                = new Thread(myThreadDelegate);
            database                = new Database_Controller();
            info                    = new RunningInfo();
            info.Id                 = 1;
            info.background         = false;
            info.notificationNeeded = false;
            database.SaveRunningInfo(info);
            myThread.Start();
        }
        /*
         * OnPause - Override for onPause to store in the database when the applications sleeps.
         */
        protected override void OnPause()
        {
            base.OnPause();
            info            = database.getRunningInfo(1);
            info.background = true;
            database.UpdateRunningInfo(info);

            /*
             * var contentIntent = PendingIntent.GetActivity(this, 0, new Intent(this, this.GetType()), 0);
             * NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
             * .SetAutoCancel(true)
             * .SetContentIntent(contentIntent)
             * .SetContentTitle("Button Clicked")
             * .SetNumber(5)
             * .SetSmallIcon(Resource.Drawable.notti_icon)
             * .SetContentText(String.Format(
             *      "The button has been clicked {0} times.", 5));
             *
             * NotificationManager notificationManager =
             * (NotificationManager)GetSystemService(Context.NotificationService);
             * notificationManager.Notify(ButtonClickNotificationId, builder.Build());*/
        }
Beispiel #12
0
        /// <summary>
        /// 获取双机热备信息
        /// </summary>
        /// <param name="runInfo"></param>
        private void GetHAInfo(RunningInfo runInfo)
        {
            //20170315 适应新监控系统架构

            //获取双机热备目录
            try
            {
                string haConfigPath = ConfigurationManager.FileConfiguration.GetString("HAPath", @"HA\BackConfig.ini");
                if (!haConfigPath.StartsWith(@"\"))
                {
                    haConfigPath = @"\" + haConfigPath;
                }

                var dr = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                if (dr != null && dr.Parent != null)
                {
                    //获取双机热备的完整目录
                    haConfigPath = dr.Parent.FullName + haConfigPath;
                }

                if (!File.Exists(haConfigPath))
                {
                    runInfo.IsUseHA = false;
                    return;
                }

                string haFlag = "0"; //
                //从ini配置文件里去读
                haFlag = IniFileHelper.IniReadValue("Backupdb", "isbackup", haConfigPath);

                if (string.IsNullOrEmpty(haFlag) || haFlag != "1")
                {
                    runInfo.IsUseHA = false;
                }
                else
                {
                    runInfo.IsUseHA = true;
                }

                //获取当前是主机还是备机  20171109
                string ismasterorbackup = "0"; //
                //从ini配置文件里去读
                ismasterorbackup = IniFileHelper.IniReadValue("Backupdb", "BackupZbj", haConfigPath);

                if (string.IsNullOrEmpty(ismasterorbackup) || ismasterorbackup == "1")
                {
                    runInfo.IsMasterOrBackup = 1;
                }
                else
                {
                    runInfo.IsMasterOrBackup = 2;
                }

                //获取双机热备工作状态  20180123
                //从ini配置文件里去读
                string backUpWorkState = IniFileHelper.IniReadValue("Backupdb", "BackUpWorkState", haConfigPath);
                if (string.IsNullOrEmpty(backUpWorkState))
                {
                    runInfo.BackUpWorkState = -1;//未知状态
                }
                else
                {
                    runInfo.BackUpWorkState = int.Parse(backUpWorkState);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                runInfo.IsUseHA = false;
                return;
            }
        }
Beispiel #13
0
        public Task SaveAsync(RunningInfo running)
        {
            var conn = new SQLiteAsyncConnection(DbName, true);

            return(running.Id == 0 ? conn.InsertAsync(running) : conn.UpdateAsync(running));
        }
 private void UpdateInfo(RunningInfo info)
 {
     Info = info;
     OnPropertyChanged(nameof(Info));
 }
Beispiel #15
0
        public async Task Run(RunningInfo runningInfo, CancellationToken ct)
        {
            if (runningInfo == null)
            {
                throw new ArgumentNullException("runningInfo");
            }

            var rawEntryPointUrl   = runningInfo.InitialEntryPointUrl;
            var entryPointUrl      = runningInfo.CurrentEntryPointUrl ?? rawEntryPointUrl;
            var mode               = runningInfo.Mode;
            var expirationDate     = runningInfo.CurrentExpirationDate;
            var lastCycleStartTime = DateTime.Now;
            var fetchQueue         = new Queue <PageFetchRequest>();

            _retryCounter = new Dictionary <string, int>();
            _pageSaveJobRunner.Run();
            var watch = Stopwatch.StartNew();

            try
            {
                var oldestReplyDateTillNow = DateTime.MaxValue;
                for (; ;)
                {
                    ct.ThrowIfCancellationRequested();
                    if (string.IsNullOrEmpty(entryPointUrl))
                    {
                        if (mode == RunningInfo.RunningMode.Single)
                        {
                            runningInfo.IsCompleted = true;
                            return;
                        }
                        else
                        {
                            entryPointUrl  = rawEntryPointUrl;
                            expirationDate = lastCycleStartTime;
                            _outputAction(string.Format("运行完成,等待{0}分钟后重新开始。", CycleInterval));
                            await Task.Delay(CycleInterval * 60 * 1000, ct);

                            lastCycleStartTime = DateTime.Now;
                        }
                    }

                    runningInfo.CurrentEntryPointUrl  = entryPointUrl;
                    runningInfo.CurrentExpirationDate = expirationDate;
                    try
                    {
                        await _runningInfoRepository.SaveAsync(runningInfo);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e);
                    }//即使保存失败也没关系
                    _outputAction(string.Format("正在获取论坛第 {0} 页,截止时间:{1}。", entryPointUrl.GetPageIndex(), expirationDate));

                    var entryPointHtmlContent = await FetchPageContent(entryPointUrl, ForumPageMaxRetryTimes, ct);

                    if (entryPointHtmlContent == null)
                    {
                        var error = string.Format("无法获取论坛第 {0} 页,URL:{1}\r\n退出运行。", entryPointUrl.GetPageIndex(), entryPointUrl);
                        Logger.Error(error);
                        _outputAction(error);
                        throw new Exception("erorr");
                    }

                    MillResult <List <ThreadHeader> > forumPageMillResult;
                    var processStatus = _pageProcessor.TryProcessPage(new MillRequest {
                        Url = entryPointUrl, HtmlContent = entryPointHtmlContent
                    },
                                                                      out forumPageMillResult);

                    if (processStatus != MillStatus.Success)
                    {
                        HandleForumPageMillError(entryPointUrl, processStatus);
                        return;
                    }
                    ct.ThrowIfCancellationRequested();
                    var threadHeaders = forumPageMillResult.Result.Where(t => !_excludedThreadIds.Contains(t.Id)).ToList();
                    var currentIndex  = 0;
                    while (currentIndex < threadHeaders.Count)
                    {
                        ct.ThrowIfCancellationRequested();
                        var requests = new List <PageFetchRequest>(PageFetchBatchSize);
                        for (var i = 0; i < PageFetchBatchSize && currentIndex < threadHeaders.Count; i++, currentIndex++)
                        {
                            var header = threadHeaders[currentIndex];
                            requests.Add(new PageFetchRequest(header.Url.ChangePageIndex(header.GetLastPageIndex()),
                                                              header.ToDescription().ChangePageIndexInDescription(header.GetLastPageIndex())));
                        }
                        var oldestReplyDate = await ProcessThreadPageRequests(requests, expirationDate, fetchQueue, ct);

                        if ((oldestReplyDate != DateTime.MaxValue) && oldestReplyDateTillNow == DateTime.MaxValue || (oldestReplyDateTillNow - oldestReplyDate).TotalHours < 24)//如果最新发现的回复比上一次发现的回复晚一天之内是正常的,否则说明有删帖,忽视该异常回复即可
                        {
                            oldestReplyDateTillNow = oldestReplyDate;
                            if (oldestReplyDate < expirationDate)
                            {
                                //以下的肯定是更旧的贴,无需再看了,跳出while循环,处理fetchQueue。
                                //但有时因为删帖的原因,一个最后回复非常早的贴会出现在正常列表中,导致提前终止运行。
                                entryPointUrl = null;
                                break;
                            }
                        }
                        //TODO:Delay
                    } //while
                    if (currentIndex >= threadHeaders.Count)
                    {
                        //curentIndex达到了最大,说明这一页的全部thread都是新的,有必要看下一页
                        entryPointUrl = forumPageMillResult.NextPageUrl;
                    }
                    //开始处理fetchQueue中
                    while (fetchQueue.Count > 0)
                    {
                        var requests = new List <PageFetchRequest>(PageFetchBatchSize);
                        for (var i = 0; i < PageFetchBatchSize && fetchQueue.Count > 0; i++)
                        {
                            requests.Add(fetchQueue.Dequeue());
                        }
                        await ProcessThreadPageRequests(requests, expirationDate, fetchQueue, ct);

                        //TODO:Delay
                    }
                }
            }
            catch (TaskCanceledException)//CancellationTokenSource is canceled.
            {
                ct.ThrowIfCancellationRequested();
            }
            finally
            {
                Stop();
                watch.Stop();
                runningInfo.IsCompleted = true;
                SaveRunningInfo(runningInfo);
                _outputAction(string.Format("运行完成,耗时 {0} 秒,约{1:0.0}分钟", watch.Elapsed.TotalSeconds, watch.Elapsed.TotalSeconds / 60.0));
            }
        }
Beispiel #16
0
 /*
  * askLocation - Method that handles the location change,
  * an infinite looping thread is created, a Boolean is used to
  * allow the reading of the GPS, once inside the method
  * a second Boolean signal every other method that GPS is
  * taking a reading, while the reading is been done the accelerometer
  * is blocked, also the user cannot leave this screen.
  *
  * Once the location is obtained the method check is a change occurred,
  * if this was the case an alert will pop up stating that location
  * change was detected, and the user need to resolve this, an interrupt
  * will be created but it will only be stored in the database if the user
  * agrees that the change in location was an interrupt to their work else,
  * it will be discarded.
  * If the application is in background a request to the OS will be made
  * to push a notification outside the application.
  */
 private async void askLocation()
 {
     await Task.Delay(10).ContinueWith(async(arg) => {
         while (true)
         {
             while (getlocation)
             {
                 gettingLocation = true;
                 var change      = GetLocation();
                 change.Wait();
                 bool realChange = change.Result;
                 if (!realChange)
                 {
                     getlocation                 = false;
                     interrupt                   = new Interrupts();
                     interrupt.reason            = "Change Location";
                     DateTime toBeClonedDateTime = DateTime.Now;
                     interrupt.start             = toBeClonedDateTime;
                     bool realAnwser             = false;
                     RunningInfo info            = database.getRunningInfo(1);
                     if (info.background)
                     {
                         info.notificationNeeded = true;
                         database.UpdateRunningInfo(info);
                     }
                     Device.BeginInvokeOnMainThread(
                         async() =>
                     {
                         realAnwser = await DisplayAlert("Location Change", "Hey there your location change, are you still working?", "Yes.", "No, pause.");
                         if (!realAnwser)
                         {
                             interrupt.sessionId = current.Id;
                             interrupt.Id        = database.SaveInterrupt(interrupt);
                             getlocation         = false;
                             //Timer_Counter.Text = "Session is paused";
                             Start.Text        = "Resume";
                             accelometeractive = false;
                             GlobalUtilities.accelerometer.ReadingAvailable -= Accelerometer_ReadingAvailable;
                             GlobalUtilities.moving = 0;
                             GlobalUtilities.still  = 0;
                         }
                         else
                         {
                             getlocation = true;
                         }
                         gettingLocation = false;
                     });
                 }
                 else
                 {
                     gettingLocation = false;
                 }
                 while (gettingLocation)
                 {
                     ;
                 }
                 Task.Delay(GlobalUtilities.locationTime).Wait();
             }
         }
     });
 }
Beispiel #17
0
        /// <summary>
        /// 获取平台运情况
        /// </summary>
        /// <returns></returns>
        public BasicResponse <RunningInfo> GetRunningInfo()
        {
            RunningInfo runInfo = new RunningInfo();

            try
            {
                if (Basic.Framework.Data.PlatRuntime.Items.Keys.Contains("CustomerInfo"))
                {
                    runInfo.CustomerInfo = Basic.Framework.Data.PlatRuntime.Items["CustomerInfo"].ToString();
                }
                if (Basic.Framework.Data.PlatRuntime.Items.Keys.Contains("AuthorizationExpires"))
                {
                    runInfo.AuthorizationExpires = (bool)Basic.Framework.Data.PlatRuntime.Items["AuthorizationExpires"];
                }
                //IPant service = ServiceFactory.CreateService<IPant>();
                //1.获取服务端到数据采的状态
                //2.获取数采到服务端的状态,数据采的数据最后接收时间
                //runInfo.LastReceiveTime = service.GetLastReceiveTime();
                //service.CheckServerState();
                var remoteStateService = ServiceFactory.Create <IRemoteStateService>();
                runInfo.LastReceiveTime = remoteStateService.GetLastReciveTime().Data;
                if (remoteStateService.GetRemoteState().Data)
                {
                    runInfo.SlaveServerState = 1;
                }
                else
                {
                    runInfo.SlaveServerState = 0;
                }


                //备机服务器状态
                //if (Basic.CBF.Common.Service.ComPantService.RemoteState)
                //{
                //    runInfo.SlaveServerState = 1;
                //}
                //else
                //{
                //    runInfo.SlaveServerState = 0;
                //}

                //主网关状态
                if (remoteStateService.GetGatewayState().Data)
                {
                    runInfo.MasterDataCollectorState = 1;
                }
                else
                {
                    runInfo.MasterDataCollectorState = 0;
                }

                //备网关状态
                //if (Basic.CBF.Common.Service.ComPantService.StandbyFrontendState)
                //{
                //    runInfo.SlaveDataCollectorState = 1;
                //}
                //else
                //{
                //    runInfo.SlaveDataCollectorState = 0;
                //}

                //(数采到服务端的状态,暂时写死(只要客户端能访问到服务端,即认为数采到服务端也是正常的))
                runInfo.MasterServerState = 1;
            }
            catch (Exception ex)
            {
                runInfo.MasterServerState = 0;
                LogHelper.Error(ex);
            }

            //3.获取数据库连接状态,获取数据库占用磁盘空间
            GetDbInfo(runInfo);
            //4.获取是否启用双机热备
            GetHAInfo(runInfo);

            return(new BasicResponse <RunningInfo>()
            {
                Data = runInfo
            });
            //return runInfo;
        }
        protected void Application_AcquireRequestState(Object sender, EventArgs e)
        {
            Context.Items["osCurrentPTAName"]     = RequestPtaName;
            Context.Items["osCurrentPTAUserName"] = RequestPtaUserName;
            Context.Items["osIsLoadingScreen"]    = false;
            RunningInfo.InitializeRunningInfo();
            RunningInfo.ESpaceHash         = ConfigurationManager.AppSettings["OutSystems.HubEdition.EspaceCompilationHash"];
            RunningInfo.ESpaceVersionToken = ConfigurationManager.AppSettings["OutSystems.HubEdition.EspaceVersionToken"];
            RunningInfo.ESpaceVersionId    = int.Parse(ConfigurationManager.AppSettings["OutSystems.HubEdition.EspaceVersionID"]);
            RunningInfo.DebugMode          = false;
            // Skips internal pages
            if (Request.FilePath.ToLowerInvariant().EndsWith("/_ping.aspx") || Request.FilePath.ToLowerInvariant().EndsWith("/_queriescoverage.aspx") || Request.FilePath.ToLower().EndsWith("/_debugger.asmx") || Request.FilePath.ToLower().EndsWith("/_debuggerevents.ashx"))
            {
                return;
            }

            if (App == null)
            {
                // Try again
                Application_Start(sender, e);
                if (Application["ApplicationStartError"] != null)
                {
                    ApplicationStartErrorRedirect();
                }
            }

            if (App.Tenant.PhoneConfigException != null)
            {
                Application["ApplicationStartError"] = App.Tenant.PhoneConfigException;
                ApplicationStartErrorRedirect();
            }

            // Session Start
            HeContext heContext = Global.App.OsContext;

            heContext.InitSession();

            var sessionCookieKey = Response.Cookies.AllKeys.FirstIfSingleOrDefault(c => c == CookieActions.GetSessionCookieName());

            if (sessionCookieKey != null)
            {
                var sessionCookie = Response.Cookies.Get(sessionCookieKey);
                if (sessionCookie != null && Settings.GetBool(Settings.Configs.EnforceSessionCookiesSecure))
                {
                    sessionCookie.Secure = true;
                }
            }

            if (Context.Session == null || heContext.Session.NeedsSessionStart(App.eSpaceName))
            {
                if (Request.Path.ToLowerInvariant().EndsWith("_SmsHandler.aspx"))
                {
                    Global.App.OsContext.Session["TerminalType"] = "SMS";
                    Global.App.OsContext.Session["MSISDN"]       = Global.App.OsContext.MOMsg.MSISDN;
                }
                else if (Request.Path.ToLowerInvariant().EndsWith("smshandler.asmx"))
                {
                    Global.App.OsContext.Session["TerminalType"] = "SMS";
                    Global.App.OsContext.Session["MSISDN"]       = Request.Headers["MSISDN"];
                }
                else
                {
                    Global.App.OsContext.Session["TerminalType"] = "WEB";
                    Global.App.OsContext.Session["MSISDN"]       = "";
                }

                if (Application["ApplicationStartError"] != null)
                {
                    // Try again
                    Application_Start(sender, e);
                }

                if (Application["ApplicationStartError"] != null)
                {
                    ApplicationStartErrorRedirect();
                }
                if (Context.Session != null)
                {
                    ExtendedActions.AutoLogin(App, App.OsContext.Session);
                    RunOnSessionStart();
                }
            }            /*
                          * else {
                          *
                          * } */

            // Process visit cookies
            if (RuntimePlatformUtils.ShouldCreateCookieForRequest())
            {
                if (Request.CurrentExecutionFilePath.ToLowerInvariant().EndsWith(".aspx"))
                {
                    var osVisitorCookie = Request.Cookies["osVisitor"];
                    var osVisitCookie   = Request.Cookies["osVisit"];

                    if (osVisitorCookie == null || !GuidUtils.IsGuid(osVisitorCookie.Value))
                    {
                        osVisitorCookie         = new HttpCookie("osVisitor", Guid.NewGuid().ToString());
                        osVisitorCookie.Expires = DateTime.Now.AddYears(100);                         // forever
                        SecureCookieUtils.setSecureCookie(osVisitorCookie, heContext.Context.Response);
                    }

                    if (osVisitCookie == null || !GuidUtils.IsGuid(osVisitCookie.Value))
                    {
                        osVisitCookie = new HttpCookie("osVisit", Guid.NewGuid().ToString());
                        heContext.Session["osIsNewVisit"] = true;
                    }
                    osVisitCookie.Expires = DateTime.Now.AddMinutes(30);
                    SecureCookieUtils.setSecureCookie(osVisitCookie, heContext.Context.Response);

                    Context.Items["osVisitor"] = osVisitorCookie.Value;
                    Context.Items["osVisit"]   = osVisitCookie.Value;
                }
            }

            App.OsContext.Session[GenericExtendedActions.ReqAuditCountSessionName] = 0;

            // Default Multilingual state
            if (!App.MultilingualEnabled)
            {
                GenericExtendedActions.SetCurrentLocale(heContext, "");
            }
            else
            {
                string localeHeader = heContext.OsISAPIFilter.GetLocale(Request);
                if (localeHeader != null)
                {
                    try {
                        GenericExtendedActions.SetCurrentLocale(heContext, localeHeader);
                    } catch {}
                }
            }
        }
Beispiel #19
0
        /*
         * Accelerometer_ReadingAvailable - View session live for more details.
         */
        private async void Accelerometer_ReadingAvailable(object sender, XLabs.EventArgs <XLabs.Vector3> e)
        {
            await Task.Delay(100).ContinueWith(async(arg) =>
            {
                if (!gettingLocation)
                {
                    if (onlyOne == false)
                    {
                        onlyOne = true;
                        semaphoreObject.WaitOne();
                        GlobalUtilities.accelerometer.ReadingAvailable -= Accelerometer_ReadingAvailable;

                        XLabs.Vector3 Currentreading = e.Value;
                        if (GlobalUtilities.LastMovement is null)
                        {
                            GlobalUtilities.LastMovement = Currentreading;
                        }
                        else
                        {
                            if (Math.Round(Currentreading.X, 1) != Math.Round(GlobalUtilities.LastMovement.X, 1) || Math.Round(Currentreading.Y, 1) != Math.Round(GlobalUtilities.LastMovement.Y, 1) || Math.Round(Currentreading.Z, 1) != Math.Round(GlobalUtilities.LastMovement.Z, 1))
                            {
                                GlobalUtilities.moving += 1;
                                if (GlobalUtilities.moving > GlobalUtilities.MovementTicks)
                                {
                                    accelworking           = true;
                                    getlocation            = false;
                                    GlobalUtilities.moving = 0;
                                    GlobalUtilities.still  = 0;
                                    movement                    = true;
                                    interrupt                   = new Interrupts();
                                    interrupt.reason            = "Movement detected.";
                                    DateTime toBeClonedDateTime = DateTime.Now;
                                    interrupt.start             = toBeClonedDateTime;
                                    bool realAnwser             = false;
                                    RunningInfo info            = database.getRunningInfo(1);
                                    if (info.background)
                                    {
                                        info.notificationNeeded = true;
                                        database.UpdateRunningInfo(info);
                                    }
                                    Device.BeginInvokeOnMainThread(
                                        async() =>
                                    {
                                        realAnwser = await DisplayAlert("Movement detected", "Are you still working?", "Yes.", "No, pause.");
                                        if (!realAnwser)
                                        {
                                            interrupt.sessionId = live.Id;
                                            interrupt.Id        = database.SaveInterrupt(interrupt);
                                            getlocation         = false;
                                            accelometeractive   = false;
                                        }
                                        else
                                        {
                                            getlocation       = true;
                                            accelometeractive = true;
                                        }
                                        movement = false;
                                    });
                                    accelworking = true;
                                }
                            }
                            else
                            {
                                GlobalUtilities.still += 1;
                                if (GlobalUtilities.still > GlobalUtilities.StillTicks)
                                {
                                    GlobalUtilities.moving = 0;
                                    GlobalUtilities.still  = 0;
                                }
                            }
                        }
                        while (movement)
                        {
                            ;
                        }
                        GlobalUtilities.LastMovement = Currentreading;
                        Thread.Sleep(GlobalUtilities.aceelTime);
                        if (accelometeractive)
                        {
                            GlobalUtilities.accelerometer.ReadingAvailable += Accelerometer_ReadingAvailable;
                        }
                        semaphoreObject.Release();
                        onlyOne      = false;
                        accelworking = false;
                    }
                }
            });
        }
Beispiel #20
0
 private void SaveRunningInfo(RunningInfo running)
 {
     running.LastSavedTime = DateTime.Now;
     _runningInfoRepository.SaveAsync(running);
 }