public async Task <string> UpsertRow(ReminderEntry entry)
        {
            try
            {
                ReminderEntity entity = this.ToEntity(entry);

                var response = await ExecuteWithRetries(() =>
                {
                    var pk = new PartitionKey(ReminderEntity.ConstructPartitionKey(this._serviceId, entry.GrainRef));

                    return(this._container.UpsertItemAsync(
                               entity,
                               pk,
                               new ItemRequestOptions {
                        IfMatchEtag = entry.ETag
                    }
                               ));
                }).ConfigureAwait(false);

                return(response.Resource.ETag);
            }
            catch (Exception exc)
            {
                this._logger.LogError(exc, $"Failure to upsert reminder for Service {this._serviceId}.");
                throw;
            }
        }
Пример #2
0
        private void StartAndAddTimer(ReminderEntry entry)
        {
            // it might happen that we already have a local reminder with a different eTag
            // if so, stop the local timer for the old reminder, and start again with new info
            // Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it
            var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
            LocalReminderData prevReminder;

            if (localReminders.TryGetValue(key, out prevReminder)) // if found locally
            {
                if (Logger.IsVerbose)
                {
                    Logger.Verbose(ErrorCode.RS_LocalStop, "Localy stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry);
                }
                prevReminder.StopReminder(Logger);
                localReminders.Remove(prevReminder.Identity);
            }

            var newReminder = new LocalReminderData(entry);

            localTableSequence++;
            newReminder.LocalSequenceNumber = localTableSequence;
            localReminders.Add(newReminder.Identity, newReminder);
            newReminder.StartTimer(this.RuntimeClient.Scheduler, AsyncTimerCallback, Logger);
            if (Logger.IsVerbose)
            {
                Logger.Verbose(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString());
            }
        }
        public async Task Reminders_AzureTable_InsertNewRowAndReadBack()
        {
            string clusterId      = NewClusterId();
            var    clusterOptions = Options.Create(new ClusterOptions {
                ClusterId = clusterId, ServiceId = this.serviceId
            });
            var storageOptions = Options.Create(new AzureTableReminderStorageOptions());

            storageOptions.Value.ConfigureTestDefaults();
            IReminderTable table = new AzureBasedReminderTable(this.fixture.Services.GetRequiredService <GrainReferenceKeyStringConverter>(), this.loggerFactory, clusterOptions, storageOptions);
            await table.Init();

            ReminderEntry[] rows = (await GetAllRows(table)).ToArray();
            Assert.Empty(rows); // "The reminder table (sid={0}, did={1}) was not empty.", ServiceId, clusterId);

            ReminderEntry expected = NewReminderEntry();
            await table.UpsertRow(expected);

            rows = (await GetAllRows(table)).ToArray();

            Assert.Single(rows); // "The reminder table (sid={0}, did={1}) did not contain the correct number of rows (1).", ServiceId, clusterId);
            ReminderEntry actual = rows[0];

            Assert.Equal(expected.GrainRef, actual.GrainRef);         // "The newly inserted reminder table (sid={0}, did={1}) row did not contain the expected grain reference.", ServiceId, clusterId);
            Assert.Equal(expected.ReminderName, actual.ReminderName); // "The newly inserted reminder table (sid={0}, did={1}) row did not have the expected reminder name.", ServiceId, clusterId);
            Assert.Equal(expected.Period, actual.Period);             // "The newly inserted reminder table (sid={0}, did={1}) row did not have the expected period.", ServiceId, clusterId);
            // the following assertion fails but i don't know why yet-- the timestamps appear identical in the error message. it's not really a priority to hunt down the reason, however, because i have high confidence it is working well enough for the moment.
            /*Assert.Equal(expected.StartAt,  actual.StartAt); // "The newly inserted reminder table (sid={0}, did={1}) row did not contain the correct start time.", ServiceId, clusterId);*/
            Assert.False(string.IsNullOrWhiteSpace(actual.ETag), $"The newly inserted reminder table (sid={this.serviceId}, did={clusterId}) row contains an invalid etag.");
        }
Пример #4
0
        /// <summary>
        /// Remove a row from the table
        /// </summary>
        /// <param name="grainRef"></param>
        /// <param name="reminderName"></param>
        /// /// <param name="eTag"></param>
        /// <returns>true if a row with <paramref name="grainRef"/> and <paramref name="reminderName"/> existed and was removed successfully, false otherwise</returns>
        public bool RemoveRow(GrainReference grainRef, string reminderName, string eTag)
        {
            Dictionary <string, ReminderEntry> data = null;
            ReminderEntry e = null;

            // assuming the calling grain executes one call at a time, so no need to lock
            if (!reminderTable.TryGetValue(grainRef, out data))
            {
                return(false);
            }

            data.TryGetValue(reminderName, out e); // check if eTag matches
            if (e == null || !e.ETag.Equals(eTag))
            {
                return(false);
            }

            if (!data.Remove(reminderName))
            {
                return(false);
            }

            if (data.Count == 0)
            {
                reminderTable.Remove(grainRef);
            }
            return(true);
        }
Пример #5
0
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            if (this.logger.IsVerbose3)
            {
                this.logger.Verbose3(
                    string.Format(
                        "ReminderTable.UpsertRow called with serviceId {0}.",
                        this.serviceId));
            }

            try
            {
                return(await this.repository.UpsertReminderRowAsync(this.serviceId,
                                                                    entry.GrainRef,
                                                                    entry.ReminderName,
                                                                    entry.StartAt,
                                                                    entry.Period));
            }
            catch (Exception ex)
            {
                if (this.logger.IsVerbose)
                {
                    this.logger.Verbose("ReminderTable.UpsertRow failed: {0}", ex);
                }

                throw;
            }
        }
Пример #6
0
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            try
            {
                if (logger.IsVerbose)
                {
                    logger.Verbose("UpsertRow entry = {0}", entry.ToString());
                }
                ReminderTableEntry remTableEntry = ConvertToTableEntry(entry, remTableManager.ServiceId, remTableManager.DeploymentId);

                string result = await remTableManager.UpsertRow(remTableEntry);

                if (result == null)
                {
                    logger.Warn(ErrorCode.AzureTable_45, String.Format("Upsert failed on the reminder table. Will retry. Entry = {0}", entry.ToString()));
                }
                return(result);
            }
            catch (Exception exc)
            {
                logger.Warn(ErrorCode.AzureTable_42, String.Format("Intermediate error upserting reminder entry {0} to the table {1}.",
                                                                   entry.ToString(), remTableManager.TableName), exc);
                throw;
            }
        }
Пример #7
0
        public Task <string> UpsertRow(ReminderEntry entry)
        {
            var eTag = Guid.NewGuid();

            return(session.ExecuteAsync(queries.UpsertReminderRow(entry, eTag, grainReferenceConversionProvider))
                   .ContinueWith(t => t.IsCompleted ? eTag.ToString() : throw t.Exception));
        }
Пример #8
0
            public string UpsertRow(ReminderEntry entry)
            {
                entry.ETag = Guid.NewGuid().ToString();
                Dictionary <string, ReminderEntry> d;

                if (!reminderTable.ContainsKey(entry.GrainRef))
                {
                    d = new Dictionary <string, ReminderEntry>();
                    reminderTable.Add(entry.GrainRef, d);
                }

                d = reminderTable[entry.GrainRef];

                ReminderEntry old;                          // tracing purposes only

                d.TryGetValue(entry.ReminderName, out old); // tracing purposes only
                                                            // add or over-write
                d[entry.ReminderName] = entry;
                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.LogTrace("Upserted entry {Updated}, replaced {Replaced}", entry, old);
                }

                return(entry.ETag);
            }
Пример #9
0
        private static ReminderTableEntry ConvertToTableEntry(ReminderEntry remEntry, Guid serviceId, string deploymentId)
        {
            string partitionKey = ReminderTableEntry.ConstructPartitionKey(serviceId, remEntry.GrainRef);
            string rowKey = ReminderTableEntry.ConstructRowKey(remEntry.GrainRef, remEntry.ReminderName);
            string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(serviceId);

            var consistentHash = remEntry.GrainRef.GetUniformHashCode();

            return new ReminderTableEntry
            {
                PartitionKey = partitionKey,
                RowKey = rowKey,

                ServiceId = serviceIdStr,
                DeploymentId = deploymentId,
                GrainReference = remEntry.GrainRef.ToKeyString(),
                ReminderName = remEntry.ReminderName,

                StartAt = LogFormatter.PrintDate(remEntry.StartAt),
                Period = remEntry.Period.ToString(),

                GrainRefConsistentHash = String.Format("{0:X8}", consistentHash),
                ETag = remEntry.ETag,
            };
        }
        protected async Task ReminderSimple(GrainReference grainRef, string reminderName)
        {
            ReminderEntry reminder = CreateReminder(grainRef, reminderName);
            await remindersTable.UpsertRow(reminder);

            ReminderEntry readReminder = await remindersTable.ReadRow(reminder.GrainRef, reminder.ReminderName);

            string etagTemp = reminder.ETag = readReminder.ETag;

            Assert.Equal(JsonConvert.SerializeObject(readReminder), JsonConvert.SerializeObject(reminder));

            Assert.NotNull(etagTemp);

            reminder.ETag = await remindersTable.UpsertRow(reminder);

            bool removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, etagTemp);

            Assert.False(removeRowRes, "should have failed. Etag is wrong");
            removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, "bla", reminder.ETag);

            Assert.False(removeRowRes, "should have failed. reminder name is wrong");
            removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, reminder.ETag);

            Assert.True(removeRowRes, "should have succeeded. Etag is right");
            removeRowRes = await remindersTable.RemoveRow(reminder.GrainRef, reminder.ReminderName, reminder.ETag);

            Assert.False(removeRowRes, "should have failed. reminder shouldn't exist");
        }
Пример #11
0
 public void Run(IrcMessage theMessage)
 {
     if (theMessage.CommandArgs.Count > 1)
     {
         using (var context = new BotContext())
         {
             if (theMessage.ServerConnetion.IrcClient.IsMe(theMessage.CommandArgs[0]))
             {
                 theMessage.Answer("Wieso sollte ich mich selbst an etwas erinnern ;) ?");
                 return;
             }
             User u = context.GetUser(theMessage.CommandArgs[0]);
             if (u != null)
             {
                 ReminderEntry r = new ReminderEntry();
                 r.Created = DateTime.Now;
                 r.Creator = context.GetUser(theMessage.Nickname);
                 r.Message = theMessage.CommandArgs.Skip(1).Join(" ");
                 r.User    = u;
                 context.ReminderEntries.Add(r);
                 context.SaveChanges();
                 theMessage.Answer("Okay ich werde es sobald wie möglich zustellen");
             }
             else
             {
                 theMessage.Answer("Den Benutzer habe ich aber noch nie gesehen");
             }
         }
     }
     else
     {
         theMessage.Answer("Die Eingabe war nicht korrekt: !remind <Benutzer> <Nachricht>");
     }
 }
Пример #12
0
        private static ReminderTableEntry ConvertToTableEntry(ReminderEntry remEntry, Guid serviceId, string deploymentId)
        {
            string partitionKey = ReminderTableEntry.ConstructPartitionKey(serviceId, remEntry.GrainRef);
            string rowKey       = ReminderTableEntry.ConstructRowKey(remEntry.GrainRef, remEntry.ReminderName);
            string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(serviceId);

            var consistentHash = remEntry.GrainRef.GetUniformHashCode();

            return(new ReminderTableEntry
            {
                PartitionKey = partitionKey,
                RowKey = rowKey,

                ServiceId = serviceIdStr,
                DeploymentId = deploymentId,
                GrainReference = remEntry.GrainRef.ToKeyString(),
                ReminderName = remEntry.ReminderName,

                StartAt = LogFormatter.PrintDate(remEntry.StartAt),
                Period = remEntry.Period.ToString(),

                GrainRefConsistentHash = String.Format("{0:X8}", consistentHash),
                ETag = remEntry.ETag,
            });
        }
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.Debug("UpsertRow entry = {0}, etag = {1}", entry.ToString(), entry.ETag);
            }

            (string etag, string value) = ConvertFromEntry(entry);
            (string from, string to)    = GetFilter(entry.GrainRef, entry.ReminderName);

            ITransaction tx = _db.CreateTransaction();

            _db.SortedSetRemoveRangeByValueAsync(RemindersRedisKey, from, to).Ignore();
            _db.SortedSetAddAsync(RemindersRedisKey, value, 0).Ignore();
            bool success = await tx.ExecuteAsync();

            if (success)
            {
                return(etag);
            }
            else
            {
                _logger.Warn(ErrorCode.ReminderServiceBase,
                             $"Intermediate error updating entry {entry} to Redis.");
                throw new ReminderException("Failed to upsert reminder");
            }
        }
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            var key  = CreateKey(entry.GrainRef, entry.ReminderName);
            var bins = ToBins(entry);
            var ops  = bins.Select(p => new Operation(Operation.Type.WRITE, p.name, p.value)).ToList();

            ops.Add(new Operation(Operation.Type.READ_HEADER, "", Value.AsNull));

            if (!string.IsNullOrEmpty(entry.ETag))
            {
                var record = await _client.Operate(new WritePolicy(_clientPolicy.writePolicyDefault)
                {
                    sendKey          = true,
                    generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL,
                    generation       = int.Parse(entry.ETag),
                }, Task.Factory.CancellationToken, key, ops.ToArray());

                return(record.generation.ToString());
            }
            else
            {
                var record = await _client.Operate(new WritePolicy(_clientPolicy.writePolicyDefault) { sendKey = true },
                                                   Task.Factory.CancellationToken, key, ops.ToArray());

                return(record.generation.ToString());
            }
        }
Пример #15
0
        private static string ConvertToRow(ReminderEntry entry, SqlCommand command, string serviceId)
        {
            var newETag = Guid.NewGuid().ToString();

            command.Parameters.Add(new SqlParameter {
                ParameterName = "@id", DbType = DbType.String, Value = serviceId
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@grainid", DbType = DbType.String, Value = entry.GrainRef.ToKeyString()
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@name", DbType = DbType.String, Value = entry.ReminderName
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@starttime", DbType = DbType.DateTime, Value = entry.StartAt
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@period", DbType = DbType.Int32, Value = entry.Period.TotalMilliseconds
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@hash", DbType = DbType.Int32, Value = (int)entry.GrainRef.GetUniformHashCode()
            });
            command.Parameters.Add(new SqlParameter {
                ParameterName = "@newetag", DbType = DbType.String, Value = newETag
            });
            return(newETag);
        }
Пример #16
0
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();

                using (var tx = conn.BeginTransaction())
                {
                    ReminderEntry result = await ReadRowInternal(entry.GrainRef, entry.ReminderName, conn, tx);

                    var doUpdate = result != null;
                    var command  = new SqlCommand(doUpdate ? UPDATE_ROW : INSERT_ROW);
                    if (doUpdate)
                    {
                        string eTagForWhere = entry.ETag ?? result.ETag;
                        command.Parameters.Add(new SqlParameter {
                            ParameterName = "@etag", DbType = DbType.String, Value = eTagForWhere
                        });
                    }
                    string newEtag = ConvertToRow(entry, command, serviceId);
                    command.Connection  = conn;
                    command.Transaction = tx;
                    await command.ExecuteNonQueryAsync();

                    tx.Commit();
                    return(newEtag);
                }
            }
        }
        public async Task Reminders_AzureTable_InsertNewRowAndReadBack()
        {
            log.Info(TestContext.TestName);

            string         deploymentId = NewDeploymentId();
            IReminderTable table        = new AzureBasedReminderTable();
            var            config       = new GlobalConfiguration()
            {
                ServiceId            = ServiceId,
                DeploymentId         = deploymentId,
                DataConnectionString = StorageTestConstants.DataConnectionString
            };
            await table.Init(config, log);

            ReminderEntry[] rows = (await GetAllRows(table)).ToArray();
            Assert.AreEqual(0, rows.Count(), "The reminder table (sid={0}, did={1}) was not empty.", ServiceId, deploymentId);

            ReminderEntry expected = NewReminderEntry();
            await table.UpsertRow(expected);

            rows = (await GetAllRows(table)).ToArray();

            Assert.AreEqual(1, rows.Count(), "The reminder table (sid={0}, did={1}) did not contain the correct number of rows (1).", ServiceId, deploymentId);
            ReminderEntry actual = rows[0];

            Assert.AreEqual(expected.GrainRef, actual.GrainRef, "The newly inserted reminder table (sid={0}, did={1}) row did not contain the expected grain reference.", ServiceId, deploymentId);
            Assert.AreEqual(expected.ReminderName, actual.ReminderName, "The newly inserted reminder table (sid={0}, did={1}) row did not have the expected reminder name.", ServiceId, deploymentId);
            Assert.AreEqual(expected.Period, actual.Period, "The newly inserted reminder table (sid={0}, did={1}) row did not have the expected period.", ServiceId, deploymentId);
            // the following assertion fails but i don't know why yet-- the timestamps appear identical in the error message. it's not really a priority to hunt down the reason, however, because i have high confidence it is working well enough for the moment.
            /*Assert.AreEqual(expected.StartAt, actual.StartAt, "The newly inserted reminder table (sid={0}, did={1}) row did not contain the correct start time.", ServiceId, deploymentId);*/
            Assert.IsFalse(string.IsNullOrWhiteSpace(actual.ETag), "The newly inserted reminder table (sid={0}, did={1}) row contains an invalid etag.", ServiceId, deploymentId);
        }
Пример #18
0
        public virtual async Task <string> UpsertRow(ReminderEntry entry)
        {
            var id = ReturnId(serviceId, entry.GrainRef, entry.ReminderName);

            var updatedEtag    = Guid.NewGuid().ToString();
            var updateDocument = MongoReminderDocument.Create(id, serviceId, entry, updatedEtag);

            try
            {
                await Collection.ReplaceOneAsync(x => x.Id == id,
                                                 updateDocument,
                                                 UpsertReplace);
            }
            catch (MongoException ex)
            {
                if (!ex.IsDuplicateKey())
                {
                    throw;
                }
            }

            entry.ETag = updatedEtag;

            return(entry.ETag);
        }
 /// <inheritdoc />
 public Task <string> UpsertRow(ReminderEntry entry)
 {
     return(DoAndLog(nameof(UpsertRow), () =>
     {
         return collection.UpsertRow(entry);
     }));
 }
Пример #20
0
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            var key  = CreateKey(entry.GrainRef, entry.ReminderName);
            var bins = ToBins(entry);

            if (string.IsNullOrEmpty(entry.ETag))
            {
                await _client.Put(new WritePolicy()
                {
                    sendKey = true
                }, Task.Factory.CancellationToken, key, bins);

                return("1");
            }
            else
            {
                var gen = int.Parse(entry.ETag);
                await _client.Put(
                    new WritePolicy()
                {
                    sendKey = true, generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL, generation = gen
                },
                    Task.Factory.CancellationToken,
                    key, bins);

                return((gen++).ToString());
            }
        }
Пример #21
0
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            try
            {
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    logger.Debug("UpsertRow entry = {0}", entry.ToString());
                }
                ReminderTableEntry remTableEntry = ConvertToTableEntry(entry, remTableManager.ServiceId, remTableManager.DeploymentId);

                string result = await remTableManager.UpsertRow(remTableEntry);

                if (result == null)
                {
                    logger.Warn((int)AzureUtils.Utilities.ErrorCode.AzureTable_45,
                                $"Upsert failed on the reminder table. Will retry. Entry = {entry.ToString()}");
                }
                return(result);
            }
            catch (Exception exc)
            {
                logger.Warn((int)AzureUtils.Utilities.ErrorCode.AzureTable_42,
                            $"Intermediate error upserting reminder entry {entry.ToString()} to the table {remTableManager.TableName}.", exc);
                throw;
            }
        }
Пример #22
0
        private Reminder.Entry EntryFromProto(ReminderEntry proto)
        {
            var repeatInterval = proto.RepeatInterval != 0
                ? (TimeSpan?)new TimeSpan(proto.RepeatInterval)
                : null;

            return(new Reminder.Entry(proto.TaskId, ActorPathFromProto(proto.Recipient), MessageFromProto(proto.Payload), new DateTime(proto.TriggerDate), repeatInterval));
        }
Пример #23
0
        public ActionResult AddReminderEntry(ReminderEntry data, int DietID)
        {
            EntryManager entry = new EntryManager(_context);

            data.ID = 0;
            entry.AddEntry(data, DietID);
            return(RedirectToAction("Show_Entry", new { ID = DietID }));
        }
Пример #24
0
 public ActionResult Edit_Reminder_Entry(ReminderEntry data, int DietID)
 {
     _context.ReminderEntries.Find(data.ID).Name        = data.Name;
     _context.ReminderEntries.Find(data.ID).Description = data.Description;
     _context.ReminderEntries.Find(data.ID).Time        = data.Time;
     _context.ReminderEntries.Find(data.ID).Email       = data.Email;
     _context.SaveChanges();
     return(RedirectToAction("Show_Entry", new { ID = DietID }));
 }
Пример #25
0
            internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests

            internal LocalReminderData(ReminderEntry entry)
            {
                Identity            = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
                firstTickTime       = entry.StartAt;
                period              = entry.Period;
                remindable          = entry.GrainRef.Cast <IRemindable>();
                ETag                = entry.ETag;
                LocalSequenceNumber = -1;
            }
Пример #26
0
        public Task <string> UpsertRow(ReminderEntry entry)
        {
            if (entry.StartAt.Kind is DateTimeKind.Unspecified)
            {
                entry.StartAt = new DateTime(entry.StartAt.Ticks, DateTimeKind.Utc);
            }

            return(this.orleansQueries.UpsertReminderRowAsync(this.serviceId, entry.GrainRef, entry.ReminderName, entry.StartAt, entry.Period));
        }
Пример #27
0
        /// <summary>
        /// Return all rows that have their GrainReference's.GetUniformHashCode() in the range (start, end]
        /// </summary>
        /// <param name="grainRef"></param>
        /// <param name="reminderName"></param>
        /// <returns></returns>
        public ReminderEntry ReadRow(GrainReference grainRef, string reminderName)
        {
            ReminderEntry r = reminderTable[grainRef][reminderName];

            if (logger.IsVerbose3)
            {
                logger.Verbose3("Read for grain {0} reminder {1} row {2}", grainRef, reminderName, r.ToString());
            }
            return(r);
        }
Пример #28
0
            internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests

            internal LocalReminderData(ReminderEntry entry, ILoggerFactory loggerFactory)
            {
                Identity            = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
                firstTickTime       = entry.StartAt;
                period              = entry.Period;
                remindable          = entry.GrainRef.Cast <IRemindable>();
                ETag                = entry.ETag;
                LocalSequenceNumber = -1;
                this.timerLogger    = loggerFactory.CreateLogger <GrainTimer>();
            }
Пример #29
0
        public async Task AddReminder([Remainder] string args)
        {
            string[] splittedArgs = null;
            if (args.Contains(" in "))
            {
                splittedArgs = args.Split(new string[] { " in " }, StringSplitOptions.None);
            }
            if (splittedArgs == null || splittedArgs.Length < 2)
            {
                await ReplyAsync("I think you are confused about how to use this command... aren't you?\n" +
                                 "Let me REMIND you it is: `remind DO THE THING! :rage: in 2d 23h 3m 12s`\n" +
                                 "And the ` in ` before the timeparameters is very important you little dumbo you...");

                return;
            }

            var timeString = splittedArgs[splittedArgs.Length - 1];

            if (timeString == "24h")
            {
                timeString = "1d";
            }

            splittedArgs[splittedArgs.Length - 1] = "";
            var reminderString = string.Join(" in ", splittedArgs, 0, splittedArgs.Length - 1);

            var timeDateTime = DateTime.UtcNow + TimeSpan.ParseExact(timeString, ReminderFormat.Formats, CultureInfo.CurrentCulture);

            var newReminder = new ReminderEntry(timeDateTime, reminderString);

            var account = GlobalUserAccounts.GetUserAccount(Context.User.Id);

            account.Reminders.Add(newReminder);
            GlobalUserAccounts.SaveAccounts(Context.User.Id);


            var          timezone  = account.TimeZone ?? "UTC";
            TimeZoneInfo tz        = TimeZoneInfo.FindSystemTimeZoneById($"{timezone}");
            var          localTime = TimeZoneInfo.ConvertTimeFromUtc(timeDateTime, tz);

            var bigmess2 =
                $"{reminderString}\n\n" +
                $"We will send you a DM in  __**{localTime}**__ `by {timezone}`\n";

            var embed = new EmbedBuilder();

            embed.WithAuthor(Context.User);
            embed.WithCurrentTimestamp();
            embed.WithColor(Color.Blue);
            embed.WithTitle("I will remind you through DM:");
            embed.AddField($"**____**", $"{bigmess2}");

            ReplyAsync("", false, embed.Build());
        }
 private static ReminderInfo ToReminderInfo(ReminderEntry entry)
 {
     return new ReminderInfo
     {
         PrimaryKey = entry.GrainRef.PrimaryKeyAsString(),
         GrainReference = entry.GrainRef.ToString(),
         Name = entry.ReminderName,
         StartAt = entry.StartAt,
         Period = entry.Period,
     };
 }
Пример #31
0
 internal LocalReminderData(ReminderEntry entry, LocalReminderService reminderService)
 {
     Identity             = new ReminderIdentity(entry.GrainRef, entry.ReminderName);
     firstTickTime        = entry.StartAt;
     period               = entry.Period;
     remindable           = entry.GrainRef.Cast <IRemindable>();
     ETag                 = entry.ETag;
     LocalSequenceNumber  = -1;
     this.reminderService = reminderService;
     this.timer           = reminderService.asyncTimerFactory.Create(period, "");
 }
Пример #32
0
        public string UpsertRow(ReminderEntry entry)
        {
            entry.ETag = Guid.NewGuid().ToString();
            Dictionary<string, ReminderEntry> d;
            if (!reminderTable.ContainsKey(entry.GrainRef))
            {
                d = new Dictionary<string, ReminderEntry>();
                reminderTable.Add(entry.GrainRef, d);
            }
            d = reminderTable[entry.GrainRef];

            ReminderEntry old; // tracing purposes only
            d.TryGetValue(entry.ReminderName, out old); // tracing purposes only
            // add or over-write
            d[entry.ReminderName] = entry;
            if (logger.IsVerbose3) logger.Verbose3("Upserted entry {0}, replaced {1}", entry, old);
            return entry.ETag;
        }
Пример #33
0
        public async Task<string> UpsertRow(ReminderEntry entry)
        {
            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();

                using (var tx = conn.BeginTransaction())
                {
                    ReminderEntry result = await ReadRowInternal(entry.GrainRef, entry.ReminderName, conn, tx);
                
                    var doUpdate = result != null;
                    var command = new SqlCommand(doUpdate ? UPDATE_ROW : INSERT_ROW);
                    if (doUpdate)
                    {
                        string eTagForWhere = entry.ETag ?? result.ETag;
                        command.Parameters.Add(new SqlParameter { ParameterName = "@etag", DbType = DbType.String, Value = eTagForWhere });
                    }
                    string newEtag = ConvertToRow(entry, command, serviceId);                    
                    command.Connection = conn;
                    command.Transaction = tx;
                    await command.ExecuteNonQueryAsync();

                    tx.Commit();
                    return newEtag;
                }
            }
        }
Пример #34
0
 public Task<string> UpsertRow(ReminderEntry entry)
 {
     return Task.FromResult(remTable.UpsertRow(entry));
 }
Пример #35
0
 public Task<string> UpsertRow(ReminderEntry entry)
 {
     return orleansQueries.UpsertReminderRowAsync(serviceId, entry.GrainRef, entry.ReminderName, entry.StartAt, entry.Period);            
 }
Пример #36
0
 public Task<string> UpsertRow(ReminderEntry entry)
 {
     var query = queryConstants.GetConstant(database.InvariantName, QueryKeys.UpsertReminderRowKey);
     return database.UpsertReminderRowAsync(query, serviceId, entry.GrainRef, entry.ReminderName, entry.StartAt, entry.Period);            
 }
Пример #37
0
 public Task<string> UpsertRow(ReminderEntry entry)
 {
     return database.UpsertReminderRowAsync(serviceId, entry.GrainRef, entry.ReminderName, entry.StartAt, entry.Period, entry.ETag);            
 }
Пример #38
0
 private static string ConvertToRow(ReminderEntry entry, SqlCommand command, string serviceId)
 {
     var newETag = Guid.NewGuid().ToString();
     command.Parameters.Add(new SqlParameter { ParameterName = "@id", DbType = DbType.String, Value = serviceId });
     command.Parameters.Add(new SqlParameter { ParameterName = "@grainid", DbType = DbType.String, Value = entry.GrainRef.ToKeyString() });
     command.Parameters.Add(new SqlParameter { ParameterName = "@name", DbType = DbType.String, Value = entry.ReminderName });
     command.Parameters.Add(new SqlParameter { ParameterName = "@starttime", DbType = DbType.DateTime, Value = entry.StartAt });
     command.Parameters.Add(new SqlParameter { ParameterName = "@period", DbType = DbType.Int32, Value = entry.Period.TotalMilliseconds });
     command.Parameters.Add(new SqlParameter { ParameterName = "@hash", DbType = DbType.Int32, Value = (int)entry.GrainRef.GetUniformHashCode() });
     command.Parameters.Add(new SqlParameter { ParameterName = "@newetag", DbType = DbType.String, Value = newETag });
     return newETag;
 }
Пример #39
0
        public async Task<string> UpsertRow(ReminderEntry entry)
        {
            try
            {
                if (logger.IsVerbose) logger.Verbose("UpsertRow entry = {0}", entry.ToString());
                ReminderTableEntry remTableEntry = ConvertToTableEntry(entry, remTableManager.ServiceId, remTableManager.DeploymentId);

                string result = await remTableManager.UpsertRow(remTableEntry);
                if (result == null)
                {
                    logger.Warn(ErrorCode.AzureTable_45, String.Format("Upsert failed on the reminder table. Will retry. Entry = {0}", entry.ToString()));
                }
                return result;
            }
            catch (Exception exc)
            {
                logger.Warn(ErrorCode.AzureTable_42, String.Format("Intermediate error upserting reminder entry {0} to the table {1}.",
                    entry.ToString(), remTableManager.TableName), exc);
                throw;
            }
        }
Пример #40
0
 public async Task<string> UpsertRow(ReminderEntry entry)
 {
     await Task.Delay(delay);
     return MOCK_E_TAG;
 }