Exemple #1
0
        public bool Start()
        {
            Context             context = Android.App.Application.Context;
            AlarmManager        am      = (AlarmManager)context.GetSystemService(Context.AlarmService);
            NotificationManager nm      = (NotificationManager)context.GetSystemService(Context.NotificationService);

            _penint = PendingIntent.GetBroadcast(context, 0, new Intent(context, typeof(RepeatingAlarm)), 0);
            am.SetAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 3 * 60 * 1000, _penint);

            var notIntent     = new Intent(context, typeof(MainActivity));
            var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            //// Build the notification:
            //var builderOld = new Notification.Builder(context, MainActivity.cn)
            //              .SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
            //              .SetContentIntent(contentIntent) // Start up this activity when the user clicks the intent.
            //              .SetContentTitle("title") // Set the title
            //              //.SetNumber(count) // Display the count in the Content Info
            //              .SetSmallIcon(Resource.Drawable.Icon_Notify) // This is the icon to display
            //              .SetContentText("message start"); // the message to display.
            //                                        // Finally, publish the notification:
            //nm.Notify(1000, builderOld.Build());

            // Build the notification:
            var builder = new NotificationCompat.Builder(context, MainActivity.cn)
                          .SetAutoCancel(true)                         // Dismiss the notification from the notification area when the user clicks on it
                          .SetContentIntent(contentIntent)             // Start up this activity when the user clicks the intent.
                          .SetContentTitle("Title")                    // Set the title
                                                                       //.SetNumber(count) // Display the count in the Content Info
                          .SetSmallIcon(Resource.Drawable.Icon_Notify) // This is the icon to display
                          .SetContentText($"Notificatin start");       // the message to display.

            // Finally, publish the notification:
            nm.Notify(1000, builder.Build());

            return(true);
        }
Exemple #2
0
        /// <summary>
        /// Creates new alarm according to settings from alarmInfo values. If the Delay value is greater than 0,
        /// the alarm type is set to "delay" alarm type. Otherwise it is "exact date/time" alarm type.
        /// </summary>
        /// <param name="alarmInfo">Alarm object.</param>
        /// <returns>Created Alarm ID.</returns>
        public int SetAlarm(AlarmInfoViewModel alarmInfo)
        {
            AppControl appControl = new AppControl {
                ApplicationId = alarmInfo.AppInfo.AppId
            };
            Alarm createdAlarm;

            RemoveAlarm(alarmInfo.AlarmReference);

            try
            {
                if (alarmInfo.Delay > 0) // Delay alarm version.
                {
                    createdAlarm = AlarmManager.CreateAlarm(alarmInfo.Delay, appControl);
                }
                else // Exact date/time alarm version.
                {
                    if (alarmInfo.IsRepeatEnabled && alarmInfo.DaysFlags.IsAny())
                    {
                        createdAlarm = AlarmManager.CreateAlarm(alarmInfo.Date, DaysOfWeek2AlarmWeek(alarmInfo.DaysFlags), appControl);
                    }
                    else
                    {
                        createdAlarm = AlarmManager.CreateAlarm(alarmInfo.Date, appControl);
                    }
                }

                return(createdAlarm.AlarmId);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Cannot create alarm. Exception message: " + e.Message);
            }

            return(-1);
        }
Exemple #3
0
            public static void Start(Context ctx)
            {
                ISharedPreferences prefs    = PreferenceManager.GetDefaultSharedPreferences(ctx);
                String             sTimeout = prefs.GetString(ctx.GetString(Resource.String.app_timeout_key), ctx.GetString(Resource.String.clipboard_timeout_default));

                long timeout;

                if (!long.TryParse(sTimeout, out timeout))
                {
                    timeout = DefaultTimeout;
                }

                if (timeout == -1)
                {
                    // No timeout don't start timeout service
                    return;
                }

                long         triggerTime = Java.Lang.JavaSystem.CurrentTimeMillis() + timeout;
                AlarmManager am          = (AlarmManager)ctx.GetSystemService(Context.AlarmService);

                Kp2aLog.Log("Timeout start");
                am.Set(AlarmType.Rtc, triggerTime, BuildIntent(ctx));
            }
        public void SetSpecificReminder(string title, string message, DateTime dateTime)
        {
            Context context = Android.App.Application.Context;

            var noteIntent = new Intent(context, typeof(LocalNoteService_droid));

            // TODO look into why the string extra has to be a string literal
            noteIntent.PutExtra(NOTIFICATION_TITLE, "" + title);
            noteIntent.PutExtra(NOTIFICATION_MESSAGE, "" + message);
            var pendingIntent = PendingIntent.GetBroadcast(context, 0, noteIntent, 0);

            Calendar cal = Calendar.GetInstance(Java.Util.TimeZone.Default, Locale.Us);

            cal.Set(CalendarField.Date, dateTime.Day);
            cal.Set(CalendarField.HourOfDay, dateTime.Hour);
            cal.Set(CalendarField.Minute, dateTime.Minute);
            cal.Set(CalendarField.Second, dateTime.Second);

            AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);

            // TODO use Set or SetExact here?
            //alarmManager.Set(AlarmType.Rtc, cal.TimeInMillis, pendingIntent);
            alarmManager.SetExact(AlarmType.Rtc, cal.TimeInMillis, pendingIntent);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            CheckAppPermissions();
            CreateNotificationChannel();
            Intent        alarmIntent = new Intent(this, typeof(AlarmReceiver));
            PendingIntent pending     = PendingIntent.GetBroadcast(Application.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);

            am = GetSystemService(AlarmService).JavaCast <AlarmManager>();

            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab);

            fab.Click += FabOnClick;
            Button send = FindViewById <Button>(Resource.Id.Send);

            send.Click += SendOnClick;
            Button generate = FindViewById <Button>(Resource.Id.Generate);

            generate.Click += GenerateOnClick;
        }
        /// <summary>
        /// 重启应用
        /// </summary>
        /// <param name="packageName">APP程序包名</param>
        /// <param name="delayMillis">延时启动时间(默认3000ms)</param>
        public void RestartApp(string packageName, long delayMillis = 3000)
        {
            int requestCode = 123456 + System.DateTime.Now.Millisecond;

            using (Intent iStartActivity = PackageManager.GetLaunchIntentForPackage(packageName))
            {
                iStartActivity.AddCategory(Intent.CategoryLauncher);
                iStartActivity.SetAction(Intent.ActionMain);
                iStartActivity.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                iStartActivity.PutExtra("mode", "restart");
                if (delayMillis > 0)
                {
                    using (PendingIntent operation = PendingIntent.GetActivity(this, requestCode, iStartActivity, PendingIntentFlags.OneShot))
                        using (AlarmManager am = GetSystemService(Context.AlarmService) as AlarmManager)
                        {
                            am.Set(AlarmType.Rtc, System.DateTime.Now.Millisecond + delayMillis, operation);
                        }
                }
                else
                {
                    StartActivity(iStartActivity);
                }
            }
        }
Exemple #7
0
        public static void StartPendingAlarm(this Context that, Class IntentClass, long delay = 1000 * 5, long repeat = 1000 * 25)
        {
            that.CancelPendingAlarm(IntentClass);

            var myIntent      = new Intent(that, IntentClass);
            var pendingIntent = PendingIntent.getService(that, 0, myIntent, 0);

            AlarmManager alarmManager = (AlarmManager)that.getSystemService(Context.ALARM_SERVICE);


            if (repeat > 0)
            {
                alarmManager.setInexactRepeating(
                    AlarmManager.RTC,
                    delay,
                    repeat,
                    pendingIntent
                    );
            }
            else
            {
                alarmManager.set(AlarmManager.RTC, delay, pendingIntent);
            }
        }
        public async Task <bool> ScheduleNotificationAsync(DateTime dateTime, NotificationTypes notificationType, string entity, string entityId)
        {
            AlarmManager alarmManager = AppContext.GetSystemService(Context.AlarmService) as AlarmManager;

            if (alarmManager == null)
            {
                return(false);
            }
            Intent intent = new Intent(AppContext, this.Class);

            intent.PutExtra(NotificationType, (int)notificationType);
            int entityIdHashCode = entityId.GetHashCode();

            Logger.Debug("Hash code for the entity id is " + entityIdHashCode);
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(AppContext, entityIdHashCode, intent, 0);

            long triggerTime = GetTriggerTime(dateTime);

            alarmManager.Set
            (
                AlarmType.RtcWakeup, triggerTime, pendingIntent
            );
            return(true);
        }
Exemple #9
0
        public void SetAlarm(int hour, int minute, string title, string message, int mode)
        {
            Intent myintent;

            if (mode == 1)
            {
                myintent = new Intent(Android.App.Application.Context, typeof(NotificationAlarmReceiver));
            }
            else
            {
                myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
            }

            myintent.PutExtra("message", message);
            myintent.PutExtra("title", title);
            int _id = DateTime.Now.Millisecond;

            TimeSpan ts     = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
            long     millis = (long)ts.TotalMilliseconds;
            int      i      = (int)millis;

            PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, i, myintent, PendingIntentFlags.OneShot);

            Java.Util.Date     date = new Java.Util.Date();
            Java.Util.Calendar cal  = Java.Util.Calendar.Instance;
            cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
            cal.Set(Java.Util.CalendarField.HourOfDay, hour);
            cal.Set(Java.Util.CalendarField.Minute, minute);
            cal.Set(Java.Util.CalendarField.Second, 0);

            AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;

            alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);

            Toast.MakeText(Android.App.Application.Context, "Alarm Created!", ToastLength.Long).Show();
        }
Exemple #10
0
        public void CreaNotifica(Posizione posizione, DateTime dateTime)
        {
            if (!channelInitialized)
            {
                CreateNotificationChannel();
            }

            Intent intent = new Intent(AndroidApp.Context, typeof(NotificationReceiver));

            intent.PutExtra(TitleKey, CostantiDominio.TITOLO_NOTIFICA);
            intent.PutExtra(MessageKey, CostantiDominio.MESSAGGIO_NOTIFICA);
            intent.PutExtra(IdNotifica, posizione.Id);

            PendingIntent pendingIntent = PendingIntent.GetBroadcast(AndroidApp.Context, pendingIntentId, intent, PendingIntentFlags.OneShot);

            Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
            calendar.Set(Java.Util.CalendarField.HourOfDay, dateTime.Hour);
            calendar.Set(Java.Util.CalendarField.Minute, dateTime.Minute);
            calendar.Set(Java.Util.CalendarField.Second, 0);

            AlarmManager alarmManager = AndroidApp.Context.GetSystemService(Context.AlarmService) as AlarmManager;

            alarmManager.Set(AlarmType.RtcWakeup, calendar.TimeInMillis, pendingIntent);
        }
 private void clearReminders(Guid localAccountId, CancellationToken token, AlarmManager alarmManager, Context context)
 {
     // For cancelling a pending alarm, the action, data, type, class, and categories of the intent need to be the same.
 }
Exemple #12
0
 public int Wakeup(AlarmManager manager, Object state, long due)
 {
     //Console.WriteLine(" In wakeup");
     CloseDelivery();
     return(0);
 }
Exemple #13
0
        public void SetAlarm(Context context, int reminderID, DateTime alarmTime, string message, ConstantsAndTypes.ALARM_INTERVALS alarmInterval = _defaultAlarmInterval, ConstantsAndTypes.DAYS_OF_THE_WEEK dayOfWeek = ConstantsAndTypes.DAYS_OF_THE_WEEK.Undefined, bool repeating = false)
        {
            try
            {
                AlarmManager alarmManager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);

                Log.Info(TAG, "SetAlarm: Created AlarmManager");

                if (alarmManager != null)
                {
                    Intent intent = new Intent(_activity, typeof(AlarmReceiver));
                    intent.PutExtra("message", message);
                    Log.Info(TAG, "SetAlarm: Added to intent, message - " + message);
                    intent.PutExtra("reminderID", reminderID);
                    Log.Info(TAG, "SetAlarm: Added to intent, reminderID - " + reminderID.ToString());
                    Log.Info(TAG, "SetAlarm: Created Intent of type AlarmHelper (this)");

                    PendingIntent pendingIntent = PendingIntent.GetBroadcast(_activity, reminderID, intent, PendingIntentFlags.UpdateCurrent);
                    Log.Info(TAG, "SetAlarm: Created PendingIntent with reminderID - " + reminderID.ToString());

                    Calendar calendar = Calendar.GetInstance(Locale.Default);
                    calendar.TimeInMillis = JavaSystem.CurrentTimeMillis();
                    Log.Info(TAG, "SetAlarm: Set Calendar time in millis to current time - " + calendar.TimeInMillis.ToString());

                    calendar.Set(CalendarField.HourOfDay, alarmTime.Hour);
                    Log.Info(TAG, "SetAlarm: Set calendar HourOfDay to " + alarmTime.Hour.ToString());
                    calendar.Set(CalendarField.Minute, alarmTime.Minute);
                    Log.Info(TAG, "SetAlarm: Set calendar Minute to " + alarmTime.Minute.ToString());

                    if (alarmInterval == ConstantsAndTypes.ALARM_INTERVALS.Daily)
                    {
                        //most are going to be daily - however, currently, if you set a daily alarm for a time that has already passed
                        //e.g it is currently 2.00pm when you set an alarm for 08.30am, then the alarm will sound immediately
                        //this is not desirable behaviour, so we are going to take the current time and compare to the alarm time
                        //and then add 1 day to the alarm time if it has already elapsed (effectively setting the NEXT scheduled alarm time)
                        if (JavaSystem.CurrentTimeMillis() - calendar.TimeInMillis > 0)
                        {
                            Log.Info(TAG, "SetAlarm: Alarm set was in the past - adding 1 day to ensure NEXT scheduled alarm time!");
                            calendar.TimeInMillis += (long)ConstantsAndTypes.ALARM_INTERVALS.Daily;
                        }
                        Log.Info(TAG, "SetAlarm: Setting repeating alarm for (approx) time in millis - " + calendar.TimeInMillis.ToString() + ", alarm interval - " + (AlarmManager.IntervalDay).ToString());
                        alarmManager.SetRepeating(AlarmType.RtcWakeup, calendar.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);
                    }
                    if (alarmInterval == ConstantsAndTypes.ALARM_INTERVALS.Weekly)
                    {
                        calendar.Set(CalendarField.DayOfWeek, (int)dayOfWeek);
                        Log.Info(TAG, "SetAlarm: Set day of the week to " + StringHelper.DayStringForConstant(dayOfWeek));
                        Log.Info(TAG, "SetAlarm: Setting repeating alarm for (approx) time in millis - " + calendar.TimeInMillis.ToString() + ", alarm interval - " + (AlarmManager.IntervalDay * 7).ToString());
                        alarmManager.SetRepeating(AlarmType.RtcWakeup, calendar.TimeInMillis, AlarmManager.IntervalDay * 7, pendingIntent);
                    }
                }
                else
                {
                    Log.Error(TAG, "SetAlarm: AlarmManager is NULL!");
                }
            }
            catch (System.Exception e)
            {
                Log.Error(TAG, "SetAlarm: Exception - " + e.Message);
                if (GlobalData.ShowErrorDialog)
                {
                    ErrorDisplay.ShowErrorAlert(_activity, e, "Setting Alarm", "AlarmHelper.SetAlarm");
                }
            }
        }
Exemple #14
0
    public bool SetData(NrTableData kData)
    {
        NrTableData.eResourceType typeIndex = kData.GetTypeIndex();
        int    num      = (int)typeIndex;
        string kDataKey = string.Empty;

        switch (typeIndex)
        {
        case NrTableData.eResourceType.eRT_WEAPONTYPE_INFO:
        {
            WEAPONTYPE_INFO wEAPONTYPE_INFO = kData as WEAPONTYPE_INFO;
            int             weaponType      = NrTSingleton <NkWeaponTypeInfoManager> .Instance.GetWeaponType(wEAPONTYPE_INFO.WEAPONCODE);

            kDataKey = weaponType.ToString();
            NrTSingleton <NkWeaponTypeInfoManager> .Instance.SetWeaponTypeInfo(weaponType, ref wEAPONTYPE_INFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_ATTACKINFO:
        {
            CHARKIND_ATTACKINFO cHARKIND_ATTACKINFO = kData as CHARKIND_ATTACKINFO;
            cHARKIND_ATTACKINFO.nWeaponType = NrTSingleton <NkWeaponTypeInfoManager> .Instance.GetWeaponType(cHARKIND_ATTACKINFO.WEAPONCODE);

            kDataKey = cHARKIND_ATTACKINFO.ATTACKTYPE.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetAttackTypeCodeInfo(cHARKIND_ATTACKINFO.ATTACKTYPE, cHARKIND_ATTACKINFO.ATTACKCODE);

            NrCharDataCodeInfo charDataCodeInfo = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharDataCodeInfo();

            if (charDataCodeInfo != null)
            {
                cHARKIND_ATTACKINFO.nJobType = charDataCodeInfo.GetCharJobType(cHARKIND_ATTACKINFO.JOBTYPE);
            }
            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_CLASSINFO:
        {
            CHARKIND_CLASSINFO cHARKIND_CLASSINFO = kData as CHARKIND_CLASSINFO;
            long num2       = 1L;
            int  cLASSINDEX = cHARKIND_CLASSINFO.CLASSINDEX;
            cHARKIND_CLASSINFO.CLASSTYPE = num2 << cLASSINDEX - 1;
            kDataKey = cHARKIND_CLASSINFO.CLASSTYPE.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetClassTypeCodeInfo(cHARKIND_CLASSINFO.CLASSCODE, cHARKIND_CLASSINFO.CLASSTYPE);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_INFO:
        {
            CHARKIND_INFO cHARKIND_INFO = kData as CHARKIND_INFO;
            kDataKey = cHARKIND_INFO.CHARKIND.ToString();
            cHARKIND_INFO.nClassType = NrTSingleton <NrCharKindInfoManager> .Instance.GetClassType(cHARKIND_INFO.CLASSTYPE);

            cHARKIND_INFO.nAttackType = NrTSingleton <NrCharKindInfoManager> .Instance.GetAttackType(cHARKIND_INFO.ATTACKTYPE);

            cHARKIND_INFO.nATB = NrTSingleton <NkATB_Manager> .Instance.ParseCharATB(cHARKIND_INFO.ATB);

            NrTSingleton <NrCharKindInfoManager> .Instance.SetCharKindInfo(ref cHARKIND_INFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_STATINFO:
        {
            CHARKIND_STATINFO cHARKIND_STATINFO = kData as CHARKIND_STATINFO;
            int charKindByCode = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_STATINFO.CharCode);

            kDataKey = charKindByCode.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetStatInfo(charKindByCode, ref cHARKIND_STATINFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_MONSTERINFO:
        {
            CHARKIND_MONSTERINFO cHARKIND_MONSTERINFO = kData as CHARKIND_MONSTERINFO;
            int charKindByCode2 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_MONSTERINFO.CharCode);

            kDataKey = charKindByCode2.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetMonsterInfo(charKindByCode2, ref cHARKIND_MONSTERINFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_MONSTATINFO:
        {
            CHARKIND_MONSTATINFO cHARKIND_MONSTATINFO = kData as CHARKIND_MONSTATINFO;
            kDataKey = NkUtil.MakeLong(cHARKIND_MONSTATINFO.MonType, (long)cHARKIND_MONSTATINFO.LEVEL).ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_NPCINFO:
        {
            CHARKIND_NPCINFO cHARKIND_NPCINFO = kData as CHARKIND_NPCINFO;
            int charKindByCode3 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_NPCINFO.CHARCODE);

            kDataKey = charKindByCode3.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetNPCInfo(charKindByCode3, ref cHARKIND_NPCINFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_ANIINFO:
        {
            CHARKIND_ANIINFO cHARKIND_ANIINFO = kData as CHARKIND_ANIINFO;
            kDataKey = cHARKIND_ANIINFO.BUNDLENAME.ToString();
            NrTSingleton <NrCharAniInfoManager> .Instance.SetAniInfo(ref cHARKIND_ANIINFO);

            NrTSingleton <NrCharKindInfoManager> .Instance.SetAniInfo(ref cHARKIND_ANIINFO);

            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_LEGENDINFO:
        {
            CHARKIND_LEGENDINFO cHARKIND_LEGENDINFO = kData as CHARKIND_LEGENDINFO;
            int charKindByCode4 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_LEGENDINFO.CharCode);

            cHARKIND_LEGENDINFO.i32Element_LegendCharkind = charKindByCode4;
            for (int i = 0; i < 5; i++)
            {
                int charKindByCode5 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_LEGENDINFO.i32Base_LegendCharCode[i]);

                cHARKIND_LEGENDINFO.i32Base_CharKind[i] = charKindByCode4;
            }
            kDataKey = charKindByCode4.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_SOLDIERINFO:
        {
            CHARKIND_SOLDIERINFO cHARKIND_SOLDIERINFO = kData as CHARKIND_SOLDIERINFO;
            for (int j = 0; j < 5; j++)
            {
                int charKindByCode6 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_SOLDIERINFO.kElement_CharData[j].Element_CharCode);

                cHARKIND_SOLDIERINFO.kElement_CharData[j].SetChar(charKindByCode6);
            }
            int charKindByCode7 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(cHARKIND_SOLDIERINFO.CharCode);

            cHARKIND_SOLDIERINFO.i32BaseCharKind = charKindByCode7;
            kDataKey = charKindByCode7.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_CHARKIND_SOLGRADEINFO:
        {
            BASE_SOLGRADEINFO bASE_SOLGRADEINFO = kData as BASE_SOLGRADEINFO;
            int charKindByCode8 = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(bASE_SOLGRADEINFO.CharCode);

            kDataKey = charKindByCode8.ToString();
            NrTSingleton <NrCharKindInfoManager> .Instance.SetSolGradeInfo(charKindByCode8, ref bASE_SOLGRADEINFO);

            break;
        }

        case NrTableData.eResourceType.eRT_ITEMTYPE_INFO:
        {
            ITEMTYPE_INFO iTEMTYPE_INFO = kData as ITEMTYPE_INFO;
            iTEMTYPE_INFO.OPTION1 = NrTSingleton <ItemManager> .Instance.GetItemOption(iTEMTYPE_INFO.szOption1);

            iTEMTYPE_INFO.OPTION2 = NrTSingleton <ItemManager> .Instance.GetItemOption(iTEMTYPE_INFO.szOption2);

            iTEMTYPE_INFO.ITEMPART = NrTSingleton <ItemManager> .Instance.GetItemPart(iTEMTYPE_INFO.szItemPart);

            iTEMTYPE_INFO.ITEMTYPE = NrTSingleton <ItemManager> .Instance.GetItemType(iTEMTYPE_INFO.ITEMTYPECODE);

            iTEMTYPE_INFO.ATB = NrTSingleton <NkATB_Manager> .Instance.ParseItemTypeATB(iTEMTYPE_INFO.szATB);

            iTEMTYPE_INFO.ATTACKTYPE = NrTSingleton <NrCharKindInfoManager> .Instance.GetAttackType(iTEMTYPE_INFO.szAttackTypeCode);

            CHARKIND_ATTACKINFO charAttackInfo = NrTSingleton <NrBaseTableManager> .Instance.GetCharAttackInfo(iTEMTYPE_INFO.ATTACKTYPE.ToString());

            if (charAttackInfo != null)
            {
                iTEMTYPE_INFO.WEAPONTYPE = charAttackInfo.nWeaponType;
            }
            else
            {
                iTEMTYPE_INFO.WEAPONTYPE = 0;
            }
            iTEMTYPE_INFO.EQUIPCLASSTYPE = NrTSingleton <NrCharKindInfoManager> .Instance.ParseClassTypeCode(iTEMTYPE_INFO.szClassTypeCode);

            kDataKey = iTEMTYPE_INFO.ITEMTYPE.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_QUEST_NPC_POS_INFO:
        {
            QUEST_NPC_POS_INFO qUEST_NPC_POS_INFO = kData as QUEST_NPC_POS_INFO;
            kDataKey = qUEST_NPC_POS_INFO.strUnique;
            break;
        }

        case NrTableData.eResourceType.eRT_ECO_TALK:
        {
            ECO_TALK eCO_TALK = kData as ECO_TALK;
            kDataKey = eCO_TALK.strCharCode;
            break;
        }

        case NrTableData.eResourceType.eRT_ECO:
        {
            ECO eCO = kData as ECO;
            kDataKey = eCO.GroupUnique.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_MAP_INFO:
        {
            MAP_INFO mAP_INFO = kData as MAP_INFO;
            mAP_INFO.MAP_ATB = NrTSingleton <NkATB_Manager> .Instance.ParseMapATB(mAP_INFO.strMapATB);

            ICollection gateInfo_Col = NrTSingleton <NrBaseTableManager> .Instance.GetGateInfo_Col();

            foreach (GATE_INFO gATE_INFO in gateInfo_Col)
            {
                if (mAP_INFO.MAP_INDEX == gATE_INFO.SRC_MAP_IDX)
                {
                    mAP_INFO.AddGateInfo(gATE_INFO);
                }
                if (mAP_INFO.MAP_INDEX == gATE_INFO.DST_MAP_IDX)
                {
                    mAP_INFO.AddDSTGateInfo(gATE_INFO);
                }
            }
            kDataKey = mAP_INFO.MAP_INDEX.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_MAP_UNIT:
        {
            MAP_UNIT mAP_UNIT = kData as MAP_UNIT;
            kDataKey = mAP_UNIT.MAP_UNIQUE.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_GATE_INFO:
        {
            GATE_INFO gATE_INFO2 = kData as GATE_INFO;
            kDataKey = gATE_INFO2.GATE_IDX.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ITEM_ACCESSORY:
        {
            ITEM_ACCESSORY pkItem = kData as ITEM_ACCESSORY;
            NrTSingleton <ItemManager> .Instance.AddAccessory(pkItem);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_ARMOR:
        {
            ITEM_ARMOR iTEM_ARMOR = kData as ITEM_ARMOR;
            NrTSingleton <ItemManager> .Instance.AddArmor(iTEM_ARMOR);

            kDataKey = iTEM_ARMOR.ITEMUNIQUE.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ITEM_BOX:
        {
            ITEM_BOX pkItem2 = kData as ITEM_BOX;
            NrTSingleton <ItemManager> .Instance.AddBox(pkItem2);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_MATERIAL:
        {
            ITEM_MATERIAL pkItem3 = kData as ITEM_MATERIAL;
            NrTSingleton <ItemManager> .Instance.AddMaterial(pkItem3);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_QUEST:
        {
            ITEM_QUEST pkItem4 = kData as ITEM_QUEST;
            NrTSingleton <ItemManager> .Instance.AddQuest(pkItem4);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_SECONDEQUIP:
        {
            ITEM_SECONDEQUIP pkItem5 = kData as ITEM_SECONDEQUIP;
            NrTSingleton <ItemManager> .Instance.AddSecondEquip(pkItem5);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_SUPPLIES:
        {
            ITEM_SUPPLIES pkItem6 = kData as ITEM_SUPPLIES;
            NrTSingleton <ItemManager> .Instance.AddSupply(pkItem6);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_WEAPON:
        {
            ITEM_WEAPON pkItem7 = kData as ITEM_WEAPON;
            NrTSingleton <ItemManager> .Instance.AddWeapon(pkItem7);

            return(true);
        }

        case NrTableData.eResourceType.eRT_INDUN_INFO:
        {
            INDUN_INFO iNDUN_INFO = kData as INDUN_INFO;
            iNDUN_INFO.m_eIndun_Type = INDUN_DEFINE.GetIndunType(iNDUN_INFO.strIndunType);
            iNDUN_INFO.m_nNpcCode    = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(iNDUN_INFO.strNpcCode);

            kDataKey = iNDUN_INFO.m_nIndunIDX.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_GAMEGUIDE:
        {
            TableData_GameGuideInfo tableData_GameGuideInfo = kData as TableData_GameGuideInfo;
            if (tableData_GameGuideInfo.gameGuideInfo.m_eType == GameGuideType.DEFAULT)
            {
                NrTSingleton <GameGuideManager> .Instance.AddDefaultGuid(tableData_GameGuideInfo.gameGuideInfo);
            }
            else
            {
                NrTSingleton <GameGuideManager> .Instance.AddGameGuide(tableData_GameGuideInfo.gameGuideInfo);
            }
            return(true);
        }

        case NrTableData.eResourceType.eRT_LOCALMAP_INFO:
        {
            LOCALMAP_INFO lOCALMAP_INFO = kData as LOCALMAP_INFO;
            kDataKey = lOCALMAP_INFO.LOCALMAP_IDX.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_WORLDMAP_INFO:
        {
            WORLDMAP_INFO wORLDMAP_INFO = kData as WORLDMAP_INFO;
            if (wORLDMAP_INFO.TEXTKEY != string.Empty)
            {
                wORLDMAP_INFO.WORLDMAP_NAME = NrTSingleton <NrTextMgr> .Instance.GetTextFromInterface(wORLDMAP_INFO.TEXTKEY);
            }
            kDataKey = wORLDMAP_INFO.WORLDMAP_IDX.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ADVENTURE:
        {
            TableData_AdventureInfo tableData_AdventureInfo = kData as TableData_AdventureInfo;
            NrTSingleton <NkAdventureManager> .Instance.AddAdventure(tableData_AdventureInfo.adventure);

            return(true);
        }

        case NrTableData.eResourceType.eRT_SOLDIER_EVOLUTIONEXP:
        {
            Evolution_EXP evolution_EXP = kData as Evolution_EXP;
            kDataKey = (evolution_EXP.Grade - 1).ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_SOLDIER_TICKETINFO:
        {
            Ticket_Info ticket_Info = kData as Ticket_Info;
            kDataKey = (ticket_Info.Grade - 1).ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_CHARSOL_GUIDE:
        {
            SOL_GUIDE sOL_GUIDE = kData as SOL_GUIDE;
            kDataKey = sOL_GUIDE.m_i32CharKind.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ITEM_REDUCE:
        {
            ItemReduceInfo itemReduceInfo = kData as ItemReduceInfo;
            kDataKey = itemReduceInfo.iGroupUnique.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_RECOMMEND_REWARD:
        {
            RECOMMEND_REWARD rECOMMEND_REWARD = kData as RECOMMEND_REWARD;
            kDataKey = rECOMMEND_REWARD.i8RecommendCount.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_SUPPORTER_REWARD:
        {
            SUPPORTER_REWARD sUPPORTER_REWARD = kData as SUPPORTER_REWARD;
            kDataKey = sUPPORTER_REWARD.i8SupporterLevel.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_GMHELPINFO:
        {
            GMHELP_INFO gMHELP_INFO = kData as GMHELP_INFO;
            kDataKey = gMHELP_INFO.m_bGMKind.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_SOLWAREHOUSE:
        {
            SolWarehouseInfo solWarehouseInfo = kData as SolWarehouseInfo;
            kDataKey = solWarehouseInfo.iWarehouseNumber.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_CHARSPEND:
        {
            charSpend charSpend = kData as charSpend;
            kDataKey = charSpend.iLevel.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_REINCARNATIONINFO:
        {
            ReincarnationInfo reincarnationInfo = kData as ReincarnationInfo;
            for (int k = 0; k < 6; k++)
            {
                reincarnationInfo.iCharKind[k] = NrTSingleton <NrCharKindInfoManager> .Instance.GetCharKindByCode(reincarnationInfo.strText[k]);
            }
            kDataKey = reincarnationInfo.iType.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ITEM_BOX_GROUP:
        {
            ITEM_BOX_GROUP_DATA pkItemBoxGroupData = kData as ITEM_BOX_GROUP_DATA;
            NrTSingleton <ItemManager> .Instance.AddBoxGroup(pkItemBoxGroupData);

            return(true);
        }

        case NrTableData.eResourceType.eRT_ITEM_TICKET:
        {
            ITEM_TICKET pkItem8 = kData as ITEM_TICKET;
            NrTSingleton <ItemManager> .Instance.AddTicket(pkItem8);

            return(true);
        }

        case NrTableData.eResourceType.eRT_AGIT_INFO:
        {
            AgitInfoData agitInfoData = kData as AgitInfoData;
            kDataKey = agitInfoData.i16Level.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_AGIT_NPC:
        {
            AgitNPCData agitNPCData = kData as AgitNPCData;
            kDataKey = agitNPCData.ui8NPCType.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_AGIT_MERCHNAT:
        {
            AgitMerchantData agitMerchantData = kData as AgitMerchantData;
            kDataKey = agitMerchantData.i16SellType.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_LEVELUPGUIDE:
        {
            LEVELUPGUIDE_INFO lEVELUPGUIDE_INFO = kData as LEVELUPGUIDE_INFO;
            for (int l = 0; l < lEVELUPGUIDE_INFO.explainList.Count; l++)
            {
                if (lEVELUPGUIDE_INFO.explainList[l] == "0")
                {
                    break;
                }
                AlarmManager.GetInstance().SetLevelupInfo(lEVELUPGUIDE_INFO.LEVEL, "1", lEVELUPGUIDE_INFO.explainList[l]);
            }
            break;
        }

        case NrTableData.eResourceType.eRT_MYTHRAIDINFO:
        {
            MYTHRAIDINFO_DATA mYTHRAIDINFO_DATA = kData as MYTHRAIDINFO_DATA;
            CHARKIND_INFO     baseCharKindInfo  = NrTSingleton <NrCharKindInfoManager> .Instance.GetBaseCharKindInfo(mYTHRAIDINFO_DATA.GetBossCode());

            if (baseCharKindInfo == null)
            {
                Debug.LogError("BossCode Wrong : " + mYTHRAIDINFO_DATA.GetBossCode());
            }
            else
            {
                mYTHRAIDINFO_DATA.nMainBossCharKind = baseCharKindInfo.CHARKIND;
                kDataKey = mYTHRAIDINFO_DATA.nRaidSeason.ToString() + mYTHRAIDINFO_DATA.nRaidType.ToString();
            }
            break;
        }

        case NrTableData.eResourceType.eRT_MYTHRAIDCLEARREWARD:
        {
            MYTHRAID_CLEAR_REWARD_INFO mYTHRAID_CLEAR_REWARD_INFO = kData as MYTHRAID_CLEAR_REWARD_INFO;
            kDataKey = MYTHRAID_CLEAR_REWARD_INFO.setDataKey(mYTHRAID_CLEAR_REWARD_INFO.CLEARMODE, mYTHRAID_CLEAR_REWARD_INFO.ROUND).ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_MYTHRAIDRANKREWARD:
            kDataKey = this.m_dicResourceInfo[num].Count.ToString();
            break;

        case NrTableData.eResourceType.eRT_MYTHRAIDGUARDIANANGEL:
        {
            MYTHRAID_GUARDIANANGEL_INFO mYTHRAID_GUARDIANANGEL_INFO = kData as MYTHRAID_GUARDIANANGEL_INFO;
            kDataKey = mYTHRAID_GUARDIANANGEL_INFO.UNIQUE.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_AUTOSELL:
        {
            AutoSell_info autoSell_info = kData as AutoSell_info;
            kDataKey = autoSell_info.i32SellNumber.ToString();
            break;
        }

        case NrTableData.eResourceType.eRT_ITEM_GROUP_SOL_TICKET:
        {
            GROUP_SOL_TICKET gROUP_SOL_TICKET = kData as GROUP_SOL_TICKET;
            if (kData != null)
            {
                NrTSingleton <ItemManager> .Instance.Add_GroupSolTicket(gROUP_SOL_TICKET.i64GroupUnique, gROUP_SOL_TICKET);
            }
            break;
        }

        case NrTableData.eResourceType.eRT_MYTH_EVOLUTION_SPEND:
        {
            MYTH_EVOLUTION mYTH_EVOLUTION = kData as MYTH_EVOLUTION;
            kDataKey = mYTH_EVOLUTION.m_bSeason.ToString();
            break;
        }
        }
        return(this.AddResourceInfo(num, kDataKey, kData));
    }
Exemple #15
0
        public override void OnCreate()
        {
            base.OnCreate();

            try
            {
                context  = Android.App.Application.Context;
                partLoad = new PartLoad();
                settings = Settings.Instance;

                #region Layout notification
                LayoutNotificationResourceInit();
                #endregion

                #region Notify Receivers
                NotifyReceiver notifyReceiver = new NotifyReceiver();

                IntentFilter notifyIntentFilter = new IntentFilter("com.arbuz.widram.notifyreceiver");
                notifyIntentFilter.AddAction(Info.IntentActionStopService);
                notifyIntentFilter.AddAction(Info.IntentActionRestartServiceRam);
                notifyIntentFilter.AddAction(Info.IntentActionUpdateSettings);

                context.RegisterReceiver(notifyReceiver, notifyIntentFilter);
                #endregion

                #region  Loading Receivers
                LoadingReceiver loadingReceiver     = new LoadingReceiver();
                IntentFilter    loadingIntentFilter = new IntentFilter(Android.Content.Intent.ActionBootCompleted);
                context.RegisterReceiver(loadingReceiver, loadingIntentFilter);
                #endregion

                #region  Alarm Receivers
                AlarmReceiver alarmReceiver = new AlarmReceiver();

                IntentFilter alarmIntentFilter = new IntentFilter("com.arbuz.widram.alarmreceiver");
                alarmIntentFilter.AddAction(Info.IntentActionAlarm);

                context.RegisterReceiver(alarmReceiver, alarmIntentFilter);

                Intent intentAlarm = new Intent(context, typeof(AlarmReceiver));
                intentAlarm.SetAction(Info.IntentActionAlarm);

                pendingIntentAlarm = PendingIntent.GetBroadcast(context, 0, intentAlarm, PendingIntentFlags.UpdateCurrent);

                alarmManager = (AlarmManager)context.GetSystemService(AlarmService);
                alarmManager.SetRepeating(AlarmType.ElapsedRealtime, 1000, 1000, pendingIntentAlarm); //API 19 Timer not working for setup number
                #endregion

                #region Main
                handler              = new Handler();
                action               = new Action(async() => await OnWork());
                partLoad.RamUpdated += Updated;
                #endregion
            }
            catch (System.Exception ex)
            {
                #region Logging
                LogRuntimeAttribute.InLogFiles(typeof(NotifyService), ex);
                #endregion
            }

            finally { }
        }
        private void handleRegistration(Context context, Intent intent)
        {
            var registrationId = intent.GetStringExtra(Constants.EXTRA_REGISTRATION_ID);
            var error          = intent.GetStringExtra(Constants.EXTRA_ERROR);
            var unregistered   = intent.GetStringExtra(Constants.EXTRA_UNREGISTERED);

            Logger.Debug("handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered);

            // registration succeeded
            if (registrationId != null)
            {
                GcmClient.ResetBackoff(context);
                GcmClient.SetRegistrationId(context, registrationId);
                OnRegistered(context, registrationId);
                return;
            }

            // unregistration succeeded
            if (unregistered != null)
            {
                // Remember we are unregistered
                GcmClient.ResetBackoff(context);
                var oldRegistrationId = GcmClient.ClearRegistrationId(context);
                OnUnRegistered(context, oldRegistrationId);
                return;
            }

            // last operation (registration or unregistration) returned an error;
            Logger.Debug("Registration error: " + error);
            // Registration failed
            if (Constants.ERROR_SERVICE_NOT_AVAILABLE.Equals(error))
            {
                var retry = OnRecoverableError(context, error);

                if (retry)
                {
                    int backoffTimeMs = GcmClient.GetBackoff(context);
                    int nextAttempt   = backoffTimeMs / 2 + sRandom.Next(backoffTimeMs);

                    Logger.Debug("Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");

                    var retryIntent = new Intent(Constants.INTENT_FROM_GCM_LIBRARY_RETRY);
                    retryIntent.PutExtra(EXTRA_TOKEN, TOKEN);

                    var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot);

                    var am = AlarmManager.FromContext(context);
                    am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent);

                    // Next retry should wait longer.
                    if (backoffTimeMs < MAX_BACKOFF_MS)
                    {
                        GcmClient.SetBackoff(context, backoffTimeMs * 2);
                    }
                }
                else
                {
                    Logger.Debug("Not retrying failed operation");
                }
            }
            else
            {
                // Unrecoverable error, notify app
                OnError(context, error);
            }
        }
Exemple #17
0
 public virtual void ResetAlarms()
 {
     AlarmManager.AcknowledgeAlarms();
 }
Exemple #18
0
 public AlarmUtil(Context context)
 {
     this.context = context;
     alarmManager = context.GetSystemService(Context.AlarmService).JavaCast <AlarmManager> ();
 }
Exemple #19
0
 void SetAlarmManager(AlarmManager alarmManager)
 {
     this.alarmManager = alarmManager;
 }
Exemple #20
0
        static void Main(string[] argList)
        {
            var ver = AssemblyUtility.GetVersion();

            Console.Write("HydrometServer " + ver + " " + AssemblyUtility.CreationDate() + "   System Time = " + DateTime.Now);
            Console.WriteLine();
            if (argList.Length == 0)
            {
                ShowHelp();
                return;
            }

            Arguments args = new Arguments(argList);


            string      errorFileName = "errors.txt";
            Performance perf          = new Performance();
            //   try
            {
                if (args.Contains("debug"))
                {
                    Logger.EnableLogger();
                    Reclamation.TimeSeries.Parser.SeriesExpressionParser.Debug = true;
                }

                if (args.Contains("import-rating-tables"))
                {// --import-rating-tables=site_list.csv  [--generateNewTables]     : updates usgs,idahopower, and owrd rating tables
                    ApplicationTrustPolicy.TrustAll();
                    var cfg = args["import-rating-tables"];
                    if (File.Exists(cfg))
                    {
                        RatingTableDownload.UpdateRatingTables(cfg, args.Contains("generateNewTables"));
                    }
                    else
                    {
                        Console.WriteLine("Error: File not found: " + cfg);
                    }
                    return;
                }

                if (args.Contains("run-crop-charts"))
                {
                    var str_yr = args["run-crop-charts"].Trim();
                    int year   = DateTime.Now.Year;
                    if (str_yr != "")
                    {
                        year = Convert.ToInt32(str_yr);
                    }

                    var server = PostgreSQL.GetPostgresServer("agrimet", "", "agrimet");
                    CropDatesDataSet.DB = server;
                    string dir = CropDatesDataSet.GetCropOutputDirectory(year);
                    Logger.WriteLine("output dir = " + dir);

                    CropChartGenerator.CreateCropReports(year, dir, HydrometHost.PNLinux);
                    return;
                }



                var db = TimeSeriesDatabase.InitDatabase(args);

                if (args.Contains("cli"))
                {
                    TimeInterval interval = TimeInterval.Irregular;
                    if (args["cli"] == "daily")
                    {
                        interval = TimeInterval.Daily;
                    }

                    Console.WriteLine();
                    HydrometServer.CommandLine.PiscesCommandLine cmd = new CommandLine.PiscesCommandLine(db, interval);
                    cmd.PiscesPrompt();

                    return;
                }


                if (args.Contains("processAlarms"))
                {
                    try
                    {
                        Logger.EnableLogger();
                        Logger.WriteLine("Checking for new or unconfirmed Alarms ");
                        var aq = new AlarmManager(db);
                        Logger.WriteLine("Processing Alarms");
                        aq.ProcessAlarms();
                    }
                    catch (Exception e)
                    {
                        Logger.WriteLine(e.Message);
                    }
                    return;
                }


                if (args.Contains("error-log"))
                {
                    errorFileName = args["error-log"];
                    File.AppendAllText(errorFileName, "HydrometServer.exe:  Started " + DateTime.Now.ToString() + "\n");
                }

                string propertyFilter = "";
                if (args.Contains("property-filter"))
                {
                    propertyFilter = args["property-filter"];
                }

                string filter = "";
                if (args.Contains("filter"))
                {
                    filter = args["filter"];
                }

                if (args.Contains("inventory"))
                {
                    db.Inventory();
                }



                if (args.Contains("import")) // import and process data from files
                {
                    bool computeDependencies    = args.Contains("computeDependencies");
                    bool computeDailyOnMidnight = args.Contains("computeDailyOnMidnight");


                    string searchPattern = args["import"];

                    if (searchPattern == "")
                    {
                        searchPattern = "*";
                    }

                    string       incomingPath = ConfigurationManager.AppSettings["incoming"];
                    FileImporter importer     = new FileImporter(db, DatabaseSaveOptions.Upsert);
                    importer.Import(incomingPath, computeDependencies, computeDailyOnMidnight, searchPattern);
                }



                DateTime t1;
                DateTime t2;

                SetupDates(args, out t1, out t2);

                if (args.Contains("import-hydromet-instant"))
                {
                    HydrometHost host = HydrometHost.PN;
                    if (args["import-hydromet-instant"] != "")
                    {
                        host = (HydrometHost)Enum.Parse(typeof(HydrometHost), args["import-hydromet-instant"]);
                    }

                    File.AppendAllText(errorFileName, "begin: import-hydromet-instant " + DateTime.Now.ToString() + "\n");
                    ImportHydrometInstant(host, db, t1.AddDays(-2), t2.AddDays(1), filter, propertyFilter);
                }

                if (args.Contains("import-hydromet-daily"))
                {
                    HydrometHost host = HydrometHost.PN;
                    if (args["import-hydromet-daily"] != "")
                    {
                        host = (HydrometHost)Enum.Parse(typeof(HydrometHost), args["import-hydromet-daily"]);
                    }

                    File.AppendAllText(errorFileName, "begin: import-hydromet-daily " + DateTime.Now.ToString() + "\n");
                    ImportHydrometDaily(host, db, t1, t2, filter, propertyFilter);
                }

                if (args.Contains("import-hydromet-monthly"))
                {
                    File.AppendAllText(errorFileName, "begin: import-hydromet-monthly " + DateTime.Now.ToString() + "\n");
                    ImportHydrometMonthly(db, t1.AddYears(-5), t2.AddDays(1), filter, propertyFilter);
                }


                if (args.Contains("calculate-daily"))
                {
                    DailyTimeSeriesCalculator calc = new DailyTimeSeriesCalculator(db, TimeInterval.Daily,
                                                                                   filter, propertyFilter);
                    File.AppendAllText(errorFileName, "begin: calculate-daily " + DateTime.Now.ToString() + "\n");
                    calc.ComputeDailyValues(t1, t2, errorFileName);
                }

                if (args.Contains("calculate-monthly"))
                {
                    MonthlyTimeSeriesCalculator calc = new MonthlyTimeSeriesCalculator(db, TimeInterval.Monthly,
                                                                                       filter, propertyFilter);
                    File.AppendAllText(errorFileName, "begin: calculate-monthly " + DateTime.Now.ToString() + "\n");
                    //calc.ComputeDailyValues(t1, t2, errorFileName);
                    calc.ComputeMonthlyValues(t1, t2, errorFileName);
                }


                if (args.Contains("copy-daily"))
                {
                    var tablename = args["copy-daily"];

                    if (tablename == "" || args["source"] == "")
                    {
                        Console.WriteLine("Error: --copy-daily=tablename requires tablename, and requires --source=connectionString");
                        ShowHelp();
                        return;
                    }
                    bool   compare          = args.Contains("compare");
                    string connectionString = args["source"];

                    Copy(TimeInterval.Daily, connectionString, tablename, (PostgreSQL)db.Server, t1, t2, compare);
                    return;
                }


                if (args.Contains("update-period-of-record"))
                {
                    var sc = db.GetSeriesCatalog("isfolder=0");

                    var prop = db.GetSeriesProperties(true);
                    for (int i = 0; i < sc.Count; i++)
                    {
                        var s   = db.GetSeries(sc[i].id);
                        var por = s.GetPeriodOfRecord();

                        s.Properties.Set("count", por.Count.ToString());

                        if (por.Count == 0)
                        {
                            s.Properties.Set("t1", "");
                            s.Properties.Set("t2", "");
                        }
                        else
                        {
                            s.Properties.Set("t1", por.T1.ToString("yyyy-MM-dd"));
                            s.Properties.Set("t2", por.T2.ToString("yyyy-MM-dd"));
                        }
                        Console.WriteLine(s.Name);
                    }
                    db.Server.SaveTable(prop);
                }

                db.Server.Cleanup();


                File.AppendAllText(errorFileName, "HydrometServer.exe:  Completed " + DateTime.Now.ToString() + "\n");
            }
            //catch (Exception e )
            //{
            //    Logger.WriteLine(e.Message);
            //    File.AppendAllText(errorFileName, "Error: HydrometServer.exe: \n"+e.Message);
            //    // Console.ReadLine();
            //    throw e;
            //}

            var  mem = GC.GetTotalMemory(true);
            long mb  = mem / 1024 / 1024;

            Console.WriteLine("Memory Usage: " + mb.ToString() + " Mb");
            perf.Report("HydrometServer: finished ");
        }
Exemple #21
0
 private void Awake()
 {
     Instance = this;
 }
        CommandMsgV2 _StartAdapter(ICommunicationMessage message)
        {
            try
            {
                CommandMsgV2 resp = new CommandMsgV2();
                resp.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                resp.SeqID          = CommandProcessor.AllocateID();
                resp.SetValue("ClientID", message.GetValue("ClientID"));
                resp.SetValue(Constants.MSG_PARANAME_RESPONSE_TO, message.SeqID);


                long adapterid = Convert.ToInt64(message.GetValue(Constants.MSG_PARANAME_ADAPTER_ID));

                C5.HashDictionary <long, AdapterInfo> ads = new C5.HashDictionary <long, AdapterInfo>();
                AlarmManager.instance().GetAdaptersInfo(ads);
                if (!ads.Contains(adapterid))
                {
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK");
                    resp.SetValue(Constants.MSG_PARANAME_REASON, "采集器不存在.");
                    return(resp);
                }

                try
                {
                    CommandMsgV2 cmd = new CommandMsgV2();
                    cmd.SeqID          = CommandProcessor.AllocateID();
                    cmd.TK_CommandType = Constants.TK_CommandType.ADAPTER_START;
                    cmd.SetValue("ClientID", adapterid);
                    cmd.SetValue(Constants.MSG_PARANAME_ADAPTER_NAME, ads[adapterid].Name);

                    System.Net.IPEndPoint end = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ads[adapterid].Address), ads[adapterid].ControllerPort);
                    if (end.Port == 0)
                    {
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK");
                        resp.SetValue(Constants.MSG_PARANAME_REASON, "不可远程控制的采集器");
                    }
                    else
                    {
                        ICommClient comm = CommManager.instance().CreateCommClient <CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>("控制器",
                                                                                                                                            end.Address.ToString(), end.Port, 30, false, false);

                        comm.Start();
                        ICommunicationMessage r2 = comm.SendCommand(cmd);
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, r2.GetValue(Constants.MSG_PARANAME_RESULT));
                        comm.Close();
                    }
                }
                catch (Exception ex)
                {
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK");
                    resp.SetValue(Constants.MSG_PARANAME_REASON, ex.Message);
                }

                return(resp);
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog(ex.ToString());
                return(null);
            }
        }
Exemple #23
0
        public static void ShowErrorDialog(Exception ex)
        {
            AppDomain.CurrentDomain.UnhandledException  -= OnCurrentDomainUnhandledException;
            AndroidEnvironment.UnhandledExceptionRaiser -= OnUnhandledExceptionRaiser;

            try {
                StringBuilder sb = new StringBuilder();

                // Append simple header
                // ToDo: Remove this hardcoded title
                sb.AppendLine("<big><font color=\"#000000\"><b>" + /*App.AssemblyTitle*/ "Jazz² Resurrection" + "</b> has exited unexpectedly!</font></big>");
                sb.AppendLine("<br><br><hr><small>");

                // Obtain debugging information
                Exception innerException = ex.InnerException;
                if (innerException != null)
                {
                    sb.Append("<b>");
                    sb.Append(WebUtility.HtmlEncode(innerException.Message).Replace("\n", "<br>"));
                    sb.Append("</b> (");
                    sb.Append(WebUtility.HtmlEncode(ex.Message).Replace("\n", "<br>"));
                    sb.AppendLine(")<br>");

                    do
                    {
                        ParseStackTrace(sb, innerException);
                        innerException = innerException.InnerException;
                    } while (innerException != null);
                }
                else
                {
                    sb.Append("<b>");
                    sb.Append(WebUtility.HtmlEncode(ex.Message).Replace("\n", "<br>"));
                    sb.AppendLine("</b><br>");
                }

                ParseStackTrace(sb, ex);

                // Append additional information
                sb.AppendLine("</small>");
                sb.AppendLine("<br><br>Please report this issue to developer (<a>https://github.com/deathkiller/jazz2</a>).");

                // Start new activity in separate process
                //Context context = Application.Context;
                //Context context = DualityActivity.Current.ApplicationContext;
                Context context = currentActivity;
                Intent  intent  = new Intent(context, typeof(CrashHandlerActivity));
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask | ActivityFlags.ClearTop);
                intent.PutExtra("ExceptionData", sb.ToString());
                //context.StartActivity(intent);

                PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);

                AlarmManager mgr = (AlarmManager)context.GetSystemService(Context.AlarmService);
                mgr.Set(AlarmType.Rtc, Java.Lang.JavaSystem.CurrentTimeMillis() + 200, pendingIntent);

                // Try to close current activity
                //DualityActivity activity = DualityActivity.Current;
                Activity activity = currentActivity;
                if (activity != null)
                {
                    activity.Finish();
                }

                Java.Lang.JavaSystem.Exit(2);
            } catch (Exception ex2) {
                Console.WriteLine("CrashHandlerActivity failed: " + ex2);
            }
        }
Exemple #24
0
 protected override void OnUpdateAfterStagePrework()
 {
     AlarmManager.GetInstance().LevelUpAlarmUpdate();
 }
        private void SaveVisit(object sender, EventArgs e)
        {
            eventToEdit.Date = new DateTime(year, month, day, hour, minute, 0);

            if (eventToEdit.ReminderType == ReminderType.Measurement)
            {
                eventToEdit.Title = measurementSpinner.SelectedItem.ToString();
            }
            else if (eventToEdit.ReminderType == ReminderType.Visit)
            {
                eventToEdit.Title = eventTitle.Text;

                if (!int.TryParse(remindBeforeValue.Text, out remindMinutesBefore))
                {
                    remindMinutesBefore = 0;
                }
                else
                {
                    switch (remindBeforeSpinner.SelectedItemPosition)
                    {
                    case 0:
                        remindBeforeMultiplier = 1;
                        break;

                    case 1:
                        remindBeforeMultiplier = 60;
                        break;

                    case 2:
                        remindBeforeMultiplier = 60 * 24;
                        break;

                    default:
                        break;
                    }

                    remindMinutesBefore = remindMinutesBefore * remindBeforeMultiplier;
                }

                eventToEdit.MinutesBefore = remindMinutesBefore;
            }
            else if (eventToEdit.ReminderType == ReminderType.Medicine)
            {
                eventToEdit.Title = eventTitle.Text;

                if (!int.TryParse(medicineCount.Text, out int count)) //jesli sie nie uda (pole puste)
                {
                    Toast.MakeText(this.Activity, $"Dawka leku nie może być pusta", ToastLength.Short).Show();
                    return;
                }

                if (count < 1)
                {
                    Toast.MakeText(this.Activity, $"Minimalna dawka to 1", ToastLength.Short).Show();
                    return;
                }

                eventToEdit.Count = count;
            }

            eventToEdit.Description = eventDescription.Text;



            if (eventToEdit.Title != string.Empty)
            {
                //database connection
                var db = new SQLiteConnection(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "zdrowieplus.db"));
                db.CreateTable <Reminder>();
                db.Update(eventToEdit);

                Toast.MakeText(this.Activity, $"Zapisano", ToastLength.Short).Show();

                if (eventToEdit.Date > DateTime.Now)
                {
                    //Notification
                    Intent notificationIntent = new Intent(Application.Context, typeof(NotificationReceiver));

                    if (eventToEdit.ReminderType == ReminderType.Visit)
                    {
                        notificationIntent.PutExtra("title", "Wizyta");
                        notificationIntent.PutExtra("message", $"{eventToEdit.Title}. {eventToEdit.Date.ToString("dd.MM.yyyy HH:mm")}");
                        eventToEdit.Date = eventToEdit.Date.AddMinutes(remindMinutesBefore * (-1)); //change the date to publish notification by chosen minutes before
                    }
                    else if (eventToEdit.ReminderType == ReminderType.Medicine)
                    {
                        notificationIntent.PutExtra("title", "Leki");
                        notificationIntent.PutExtra("message", $"{eventToEdit.Title} dawka: {eventToEdit.Count}. {eventToEdit.Date.ToString("HH:mm")}");
                    }
                    else if (eventToEdit.ReminderType == ReminderType.Measurement)
                    {
                        notificationIntent.PutExtra("title", "Pomiar");
                        notificationIntent.PutExtra("message", $"{eventToEdit.Title}. {eventToEdit.Date.ToString("HH:mm")}");
                        notificationIntent.PutExtra("type", measurementSpinner.SelectedItemPosition);
                    }
                    notificationIntent.PutExtra("id", eventToEdit.Id);

                    var timer = (long)eventToEdit.Date.ToUniversalTime().Subtract(
                        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                        ).TotalMilliseconds;

                    PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, eventToEdit.Id, notificationIntent, PendingIntentFlags.UpdateCurrent);
                    AlarmManager  alarmManager  = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
                    alarmManager.Set(AlarmType.RtcWakeup, timer, pendingIntent);
                }

                //go to list after save
                var trans = FragmentManager.BeginTransaction();
                trans.Replace(Resource.Id.fragmentContainer, reminderListFragment);
                //trans.AddToBackStack(null);
                trans.Commit();
            }
            else
            {
                Toast.MakeText(this.Activity, "Tytuł nie może być pusty", ToastLength.Short).Show();
            }
        }
Exemple #26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            filename = Path.Combine(path, "data.txt");
            SaveData(filename, "");
            File.WriteAllLines(filename,
                               File.ReadLines(filename).Where(l => false).ToList());

            listView         = FindViewById <ListView>(Resource.Id.listView);
            lst              = new List <string>();
            adapt            = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, lst);
            listView.Adapter = adapt;
            CalendarView calendar = FindViewById <CalendarView>(Resource.Id.calendar);

            alarmManager = GetSystemService(AlarmService).JavaCast <AlarmManager>();
            pIntents     = new List <PendingIntent>();
            count        = 0;

            raw  = DateTimeOffset.FromUnixTimeMilliseconds(calendar.Date).DateTime;
            date = raw.ToString("dd/MM/yyyy");
            calendar.DateChange += (ob, ev) =>
            {
                raw  = new DateTime(ev.Year, ev.Month + 1, ev.DayOfMonth);
                date = raw.ToString("dd/MM/yyyy");
                GoList(date);
            };

            Button add = FindViewById <Button>(Resource.Id.add);

            add.Click          += (o, e) => AddPrompt();
            listView.ItemClick += (o, e) =>
            {
                Intent newact = new Intent(this, typeof(EditActivity));
                newact.PutExtra("date", date);
                var line = File.ReadLines(filename).Where(l => l.StartsWith(date))
                           .Select(l => { return(l.Substring(11)); })
                           .First(l => l == listView.GetItemAtPosition(e.Position).ToString());
                var msg = line.Split('|');
                newact.PutExtra("time", msg[0]);
                newact.PutExtra("message", msg[1]);
                newact.PutExtra("id", int.Parse(msg[2]));
                StartActivityForResult(newact, 23);
            };

            var    edit = FindViewById <EditText>(Resource.Id.inputsearch);
            string txt  = null;

            edit.TextChanged += (o, e) => txt = e.Text.ToString();
            FindViewById <Button>(Resource.Id.searchbtn).Click += (o, e) =>
            {
                List <string> list = File.ReadLines(filename)
                                     .Where(l => l.ToLower().Contains(txt.ToLower())).ToList();
                if (list.Count > 0)
                {
                    adapt.Clear();
                    lst = list;
                    adapt.AddAll(lst);
                    listView.LayoutParameters.Height = (adapt.Count + 1) * 130;
                    adapt.NotifyDataSetChanged();
                }
                else
                {
                    Snackbar.Make(FindViewById(Resource.Id.perm), "Not found.", Snackbar.LengthShort).Show();
                }
            };
        }
Exemple #27
0
        private void HandleRegistration(Context context, Intent intent)
        {
            var registrationId = intent.GetStringExtra(Constants.ExtraRegistrationId);
            var error          = intent.GetStringExtra(Constants.ExtraError);
            var unregistered   = intent.GetStringExtra(Constants.ExtraUnregistered);

            //Logger.Debug("handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered);

            // registration succeeded
            if (registrationId != null)
            {
                GcmClient.ResetBackoff(context);
                GcmClient.SetRegistrationId(context, registrationId);
                OnRegistered(context, registrationId);
                return;
            }

            // unregistration succeeded
            if (unregistered != null)
            {
                // Remember we are unregistered
                GcmClient.ResetBackoff(context);
                var oldRegistrationId = GcmClient.ClearRegistrationId(context);
                OnUnRegistered(context, oldRegistrationId);
                return;
            }

            // last operation (registration or unregistration) returned an error;
            //Logger.Debug("Registration error: " + error);
            // Registration failed
            if (Constants.ErrorServiceNotAvailable.Equals(error))
            {
                var retry = OnRecoverableError(context, error);

                if (retry)
                {
                    var backoffTimeMs = GcmClient.GetBackoff(context);
                    var nextAttempt   = backoffTimeMs / 2 + sRandom.Next(backoffTimeMs);

                    //Logger.Debug("Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");

                    var retryIntent = new Intent(Constants.IntentFromGcmLibraryRetry);
                    retryIntent.PutExtra(ExtraToken, token);

                    var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot);

                    var am = AlarmManager.FromContext(context);
                    am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent);

                    // Next retry should wait longer.
                    if (backoffTimeMs < MaxBackoffMs)
                    {
                        GcmClient.SetBackoff(context, backoffTimeMs * 2);
                    }
                }
            }
            else
            {
                // Unrecoverable error, notify app
                OnError(context, error);
            }
        }
Exemple #28
0
 protected new void Add(T item)
 {
     base.Add(item);
     AlarmManager.RegisterForStatusChange(item.Alarm);
 }
 public AndroidTaskScheduler(Context context)
 {
     alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
 }
Exemple #30
0
 protected new void Remove(T item)
 {
     base.Remove(item);
     AlarmManager.UnregisterForStatusChange(item.Alarm);
 }