public async Task <IActionResult> PostStudentData(StudentModel studentModel)
        {
            RestMessage <StudentModel> response = new RestMessage <StudentModel>();

            try
            {
                AuthenticationResult authenticationResult = await GetAuthenticationResult();

                ServiceInterface serviceInterface = ServiceInterface.Instance;

                response = await serviceInterface.PostDataToAPI <StudentModel>(authenticationResult, "student", studentModel);

                if (!response.Success)
                {
                    response.StatusText = "Error saving data";
                }
            }
            catch (Exception e)
            {
                response.Exception = e;
                response.SetAsBadRequest();
                response.StatusText = "Error saving data";
            }

            return(Json(response));
        }
예제 #2
0
        public RestMessage <Dictionary <string, string> > Get(string name)
        {
            var data   = new Dictionary <string, string>();
            var result = new RestMessage <Dictionary <string, string> >(data);

            try
            {
                var values = Enum.GetValues(enumMap[name]);
                var names  = Enum.GetNames(enumMap[name]);
                for (int i = 0; i < names.Length; i++)
                {
                    data[names[i]] = values.GetValue(i).ToString();
                }
            }
            catch (Exception err)
            {
                this.logger.LogError(err, "error during enum resolution");
                result.Errors.Add(new Error()
                {
                    Code        = "001",
                    Title       = "Error getting enum",
                    Description = err.Message
                });
            }
            return(result);
        }
        public async Task <IActionResult> GetStudents()
        {
            RestMessage <List <StudentModel> > response = new RestMessage <List <StudentModel> >();

            try
            {
                AuthenticationResult authenticationResult = await GetAuthenticationResult();

                ServiceInterface serviceInterface = ServiceInterface.Instance;

                response = await serviceInterface.GetDataAsync <List <StudentModel> >(authenticationResult, "student");

                if (!response.Success)
                {
                    response.StatusText = "Error fetching Student data";
                }
            }
            catch (Exception e)
            {
                response.Exception = e;
                response.SetAsBadRequest();
                response.StatusText = "Error fetching Student data";
            }

            return(Json(response));
        }
예제 #4
0
        public RestMessage <bool> Delete(string collection, string id)
        {
            RestMessage <bool> response = new RestMessage <bool>(false);

            try
            {
                bool result = service.Delete(collection, id);
                response.Data = true;
                return(response);
            }
            catch (ValidationException err)
            {
                response.Errors = err.Errors;
            }
            catch (Exception untrapped)
            {
                //TODO: log here
                response.Errors.Add(new Library.Core.Error()
                {
                    Code        = "UNEXPEXTED",
                    Title       = $"{collection} produces an unexpexted error",
                    Description = untrapped.Message,
                });
            }
            return(response);
        }
예제 #5
0
        public RestMessage <bool> Put(string collection, string id, [FromBody] JObject value)
        {
            RestMessage <bool> response = new RestMessage <bool>(false);

            try
            {
                value["_id"] = id;
                service.Update(collection, value, true);
                response.Data = true;
                return(response);
            }
            catch (ValidationException err)
            {
                response.Errors = err.Errors;
            }
            catch (Exception untrapped)
            {
                //TODO: log here
                response.Errors.Add(new Library.Core.Error()
                {
                    Code        = "UNEXPEXTED",
                    Title       = $"{collection} produces an unexpexted error",
                    Description = untrapped.Message,
                });
            }
            return(response);
        }
예제 #6
0
        public RestMessage <JObject> Post(string collection, [FromBody] JObject value, bool omitPayload = false)
        {
            RestMessage <JObject> response = new RestMessage <JObject>(new JObject());

            try
            {
                var added = service.Insert(collection, value);
                if (omitPayload)
                {
                    response.Data["_id"] = added["_id"];
                }
                else
                {
                    response.Data = added;
                }
                return(response);
            }
            catch (ValidationException err)
            {
                response.Errors = err.Errors;
            }
            catch (Exception untrapped)
            {
                //TODO: log here
                response.Errors.Add(new Library.Core.Error()
                {
                    Code        = "UNEXPEXTED",
                    Title       = $"{collection} produces an unexpexted error",
                    Description = untrapped.Message,
                });
            }
            return(response);
        }
예제 #7
0
        public DiscordMessage(RestMessage message)
        {
            MessageId = message.Id;
            AuthorId  = message.Author.Id;
            ChannelId = message.Channel.Id;
            Source    = message.Source;
            Content   = message.Content;
            CreatedAt = message.CreatedAt;
            IsPinned  = message.IsPinned;

            MentionedChannelIDs = new List <ulong>();
            foreach (var channel in message.MentionedChannelIds)
            {
                MentionedChannelIDs.Add(channel);
            }

            MentionedRoleIDs = new List <ulong>();
            foreach (var role in message.MentionedRoleIds)
            {
                MentionedRoleIDs.Add(role);
            }

            MentionedUserIDs = new List <ulong>();
            foreach (var user in message.MentionedUsers)
            {
                MentionedUserIDs.Add(user.Id);
            }

            AttachmentIDs = new List <ulong>();
            foreach (var attachment in message.Attachments)
            {
                AttachmentIDs.Add(attachment.Id);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RawApiDataEventArgs" /> class
 /// </summary>
 /// <param name="uri">The <see cref="Uri"/> used to get the api data</param>
 /// <param name="restMessage">The rest message</param>
 /// <param name="requestParams">The parameters associated with the request</param>
 /// <param name="requestTime">The time needed to execute request</param>
 /// <param name="language">The language associated with the request</param>
 public RawApiDataEventArgs(Uri uri, RestMessage restMessage, string requestParams, TimeSpan requestTime, string language)
 {
     Uri           = uri;
     RestMessage   = restMessage;
     RequestParams = requestParams;
     RequestTime   = requestTime;
     Language      = language;
 }
예제 #9
0
            public async Task GetPinAsync()
            {
                if (!Context.Channel.HasPins(out IReadOnlyCollection <RestMessage> pins))
                {
                    await ReplyAsync(embed : EmbedData.Throw(Context, "This channel has no pinned messages."));

                    return;
                }

                RestMessage pin = pins.ToList()[RandomProvider.Instance.Next(1, pins.Count) - 1];
                await ModuleManager.TryExecute(Context.Channel, Context.Channel.SendRestMessageAsync(pin));
            }
 private void DispatchReceivedRawApiData(Uri uri, RestMessage restMessage, string requestParams, TimeSpan requestTime, string culture)
 {
     // send RawFeedMessage if needed
     try
     {
         var args = new RawApiDataEventArgs(uri, restMessage, requestParams, requestTime, culture);
         RawApiDataReceived?.Invoke(this, args);
     }
     catch (Exception e)
     {
         ExecutionLog.LogError(e, $"Error dispatching raw message for {uri}");
     }
     // continue normal processing
 }
예제 #11
0
 private void DispatchReceivedRawApiData(Uri uri, RestMessage restMessage)
 {
     // send RawFeedMessage if needed
     try
     {
         var args = new RawApiDataEventArgs(uri, restMessage);
         RawApiDataReceived?.Invoke(this, args);
     }
     catch (Exception e)
     {
         ExecutionLog.LogError($"Error dispatching raw message for {uri}", e);
     }
     // continue normal processing
 }
예제 #12
0
        private async Task HandleCommand(RestMessage message)
        {
            if (message == null)
            {
                return;
            }
            if (!(message.Content.StartsWith(_prefix)))
            {
                return;
            }

            Logger.Log($"{message.Author.Username}:  {message.Content}");

            await _commandManager.ExecuteCommandAsync(message);
        }
예제 #13
0
 public async Task ExecuteCommandAsync(RestMessage message)
 {
     await Task.Factory.StartNew(async() =>
     {
         string[] commands = message.Content.Split(" ");
         string command    = commands.FirstOrDefault()?.Substring(1);
         foreach (var module in _modules)
         {
             var type         = module.GetType();
             var methods      = type.GetMethods().Where(m => m.GetCustomAttributes(typeof(CommandAttribute)).Any());
             var methodToCall = methods
                                .FirstOrDefault(m =>
                                                ((MemberInfo)m).GetCustomAttributes()
                                                .Any(c => (c as CommandAttribute)?.Command == command));
             if (methodToCall == null)
             {
                 continue;
             }
             var instance = _modules.FirstOrDefault(m =>
                                                    m.GetType() == methodToCall.DeclaringType);
             if (instance == null)
             {
                 continue;
             }
             instance.SetContext(new CommandContext(_client, message));
             var parameters     = methodToCall.GetParameters();
             string[] splitArgs = commands.Skip(1).ToArray();
             var args           = new List <object>();
             int i = 0;
             foreach (var p in parameters)
             {
                 try
                 {
                     args.Add(Convert.ChangeType(splitArgs[i], p.ParameterType));
                     i++;
                 }
                 catch (Exception)
                 {
                     await _client.SendMessageAsync(message.Channel.Id, "Error bad args");
                 }
             }
             methodToCall.Invoke(instance, args.ToArray());
         }
     });
 }
예제 #14
0
        private async Task <ItemResult> GetPlanningResult(RestMessage message)
        {
            var yesReactions = await message.GetReactionsAsync(YesReaction);

            var maybeReactions = await message.GetReactionsAsync(MaybeReaction);

            var noReactions = await message.GetReactionsAsync(NoReaction);

            var result = new ItemResult()
            {
                Message        = message,
                YesUserNames   = SelectUserName(yesReactions),
                MaybeUserNames = SelectUserName(maybeReactions),
                NoUserNames    = SelectUserName(noReactions),
            };

            return(result);
        }
예제 #15
0
        private void DispatchHandler(NetworkFrame msg)
        {
            switch (msg.Type)
            {
            case "READY":
                HandleReadyEvent(msg);
                break;

            case "GUILD_CREATE":
                HandleGuildCreate(msg);
                break;

            case "MESSAGE_CREATE":
                var message = JsonConvert.DeserializeObject <Message>(msg.Data.ToString());
                OnMessageReceived(RestMessage.CreateMessage(message));
                break;

            default:
                Logger.Log("Other type");
                break;
            }
        }
예제 #16
0
 private Embed GetEmbedFromMessage(RestMessage message)
 {
     return(new EmbedBuilder
     {
         Author = new EmbedAuthorBuilder
         {
             IconUrl = message.Author.GetAvatarUrl(),
             Name = $"{message.Author.Username}#{message.Author.Discriminator}"
         },
         Color = GetRandomColor(),
         Fields = new List <EmbedFieldBuilder>
         {
             new EmbedFieldBuilder
             {
                 IsInline = false,
                 Name = "Content",
                 Value = message.Content
             },
             new EmbedFieldBuilder
             {
                 IsInline = false,
                 Name = "Attachments",
                 Value = message.Attachments.Count
             }
         },
         ImageUrl = message.Attachments.Count != 0
                 ? message.Attachments.ElementAt(0).Url
                 : string.Empty,
         Timestamp = message.Timestamp,
         Title = "Pinned Message",
         Url = message.GetJumpUrl(),
         Footer = new EmbedFooterBuilder
         {
             Text = message.Channel.Name,
             IconUrl = Context.Guild.IconUrl
         }
     }.Build());
 }
예제 #17
0
        public static async Task SendRestMessageAsync(this ISocketMessageChannel channel, RestMessage msg)
        {
            // safemessage class for rest messages to easily convert.
            string content = msg.Content ?? UnicodeIndex.Invisible.ToString();
            bool   tts     = msg.IsTTS;
            Embed  e       = null;

            if (msg.Embeds.Funct())
            {
                if (msg.Embeds.Any(x => x.IsPureEmbed()))
                {
                    e = msg.Embeds.Where(x => x.IsPureEmbed()).First();
                }
            }

            await channel.SendMessageAsync(content, tts, e);
        }
예제 #18
0
 private void OnMessageReceived(RestMessage msg)
 {
     MessageReceived?.Invoke(msg);
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="RawApiDataEventArgs" /> class
 /// </summary>
 /// <param name="uri">The <see cref="Uri" /> used to get the api data</param>
 /// <param name="restMessage">The rest message</param>
 public RawApiDataEventArgs(Uri uri, RestMessage restMessage)
 {
     Uri         = uri;
     RestMessage = restMessage;
 }
예제 #20
0
 public CommandContext(DiscordClient client, RestMessage message)
 {
     Client  = client;
     Message = message;
 }