public ActionResult Post(MessageCreate message) { if (message == null || message.DateTime == null || message.Content == null) { return(BadRequest()); } conn.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO message (datetime, content, sender, recipient)" + "VALUES(@datetime, @content, @sender, @recipient);", conn); cmd.Parameters.AddWithValue("@datetime", message.DateTime); cmd.Parameters.AddWithValue("@content", message.Content); cmd.Parameters.AddWithValue("@sender", message.SenderId); cmd.Parameters.AddWithValue("@recipient", message.RecipientId); int affected = cmd.ExecuteNonQuery(); if (affected == 0) { return(NotFound()); } cmd.ExecuteNonQuery(); conn.Close(); conn.Dispose(); return(Ok()); }
public int CreateDocumentFromJob(MessageCreate model, string fileName) { new DocumentService(); string docString = "/Content/docs/"; string fullFileName = fileName; fileName = fileName.Substring(fileName.Length - 8, 8); var entity = new Document() { OwnerId = _userId, DocName = fileName, DocString = docString + fullFileName, DocType = docType.Image, DateCreated = DateTimeOffset.Now, LocationId = model.LocationId }; using (var ctx = new ApplicationDbContext()) { ctx.Documents.Add(entity); ctx.SaveChanges(); } return(entity.DocumentId); }
public ActionResult Create(MessageCreate model, HttpPostedFileBase file) { //var coopService = new CooperatorService(); //ViewBag.cooperators = coopService.GetCooperators().Where(e => e.ContactType == contact.Employee).OrderBy(e => e.FullName); //var locService = new LocationService(); I think this is copypasta accident ? //ViewBag.locations = locService.GetLocations().OrderBy(e => e.LocationCode); var userId = Guid.Parse(User.Identity.GetUserId()); var docService = new DocumentService(userId); string path = ""; string fileName = ""; if (ModelState.IsValid) { var service = new MessageService(Guid.Parse(User.Identity.GetUserId())); int?docId = null; if (file != null) { fileName = Path.GetFileName(file.FileName); path = Path.Combine(Server.MapPath("~/Content/docs"), fileName); file.SaveAs(path); docId = docService.CreateDocumentFromJob(model, fileName); } service.CreateMessage(model, docId); return(RedirectToAction("Index")); } return(View(model)); }
public async Task <IActionResult> AddMessage([FromBody] MessageCreate msg, string username) { //Create a new message from logged in user //TODO if user not logged in if (!CookieHandler.LoggedIn(Request) && !(Request.Headers.TryGetValue("Authorization", out var header) && header.Equals(AuthorizationConstants.terribleHackAuth))) { return(Unauthorized()); } switch (Request.Method) { case "POST": _logger.LogInformation($"User: {username} posted msg: {msg.content}"); _timelineRepository.PostMessage(username, msg.content); return(NoContent()); case "GET": _logger.LogInformation($"GET request to msgs/{username} - This end point should not be called... Typically?"); _timelineRepository.GetUserTimeline(username); return(NoContent()); } return(NoContent()); }
//Create public bool CreateMessage(MessageCreate message) //This needs changed to something that will send the ReceiverHouseId and SenderHouseId in from the Body. { HouseService houseService = new HouseService(); int senderHouseId; using (var ctx = new ApplicationDbContext()) { senderHouseId = houseService.GetHouseIdByOwnerId(_userId); } var entity = new Message() { OwnerId = _userId, SenderHouseId = senderHouseId, ReceiverHouseId = message.ReceiverHouseId, MessageContent = message.MessageContent, DateCreated = DateTimeOffset.Now, }; using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }
/// <summary> /// Post a message to a guild text or DM channel. /// If operating on a guild channel, this endpoint requires the SEND_MESSAGES permission to be present on the current user. /// If the tts field is set to true, the SEND_TTS_MESSAGES permission is required for the message to be spoken. /// See <a href="https://discord.com/developers/docs/resources/channel#create-message">Create Message</a> /// </summary> /// <param name="client">Client to use</param> /// <param name="message">Content of the message</param> /// <param name="callback">Callback with the created message</param> /// <param name="error">Callback when an error occurs with error information</param> public void CreateMessage(DiscordClient client, string message, Action <DiscordMessage> callback = null, Action <RestError> error = null) { MessageCreate createMessage = new MessageCreate { Content = message }; CreateMessage(client, createMessage, callback, error); }
/// <summary> /// Post a message to a guild text or DM channel. /// If operating on a guild channel, this endpoint requires the SEND_MESSAGES permission to be present on the current user. /// If the tts field is set to true, the SEND_TTS_MESSAGES permission is required for the message to be spoken. /// See <a href="https://discord.com/developers/docs/resources/channel#create-message">Create Message</a> /// </summary> /// <param name="client">Client to use</param> /// <param name="embeds">Embeds to be send in the message</param> /// <param name="callback">Callback with the created message</param> /// <param name="error">Callback when an error occurs with error information</param> public void CreateMessage(DiscordClient client, List <DiscordEmbed> embeds, Action <DiscordMessage> callback = null, Action <RestError> error = null) { MessageCreate createMessage = new MessageCreate { Embeds = embeds }; CreateMessage(client, createMessage, callback, error); }
/// <summary> /// Send a Discord Message to an IPlayer if they're registered /// </summary> /// <param name="player">Player to send the discord message to</param> /// <param name="client">Client to use for sending the message</param> /// <param name="message">Message to send</param> public static void SendDiscordMessage(this IPlayer player, DiscordClient client, string message) { MessageCreate create = new MessageCreate { Content = message }; player.SendDiscordMessage(client, create); }
/// <summary> /// Send a Discord Message to an IPlayer if they're registered /// </summary> /// <param name="player">Player to send the discord message to</param> /// <param name="client">Client to use for sending the message</param> /// <param name="embeds">Embeds to send</param> public static void SendDiscordMessage(this IPlayer player, DiscordClient client, List <DiscordEmbed> embeds) { MessageCreate create = new MessageCreate { Embeds = embeds }; player.SendDiscordMessage(client, create); }
public async Task <IActionResult> Create(MessageCreate messageCreate) { var user = await _userManager.GetUserAsync(User); messageCreate.UserID = user.Id; await _createMessage.Execute(messageCreate); return(Ok()); }
public bool CreateMessage(MessageCreate model, int?docId) { var locationService = new LocationService(); var entity = new Message() { Comment = model.Comment, OwnerId = _userId, DateCreated = DateTimeOffset.Now, LocationId = model.LocationId, HumanGrowthStage = model.HumanGrowthStage, IsRequest = noYes.No, JobOne = model.JobOne, JobTwo = model.JobTwo, JobThree = model.JobThree, CooperatorId = model.CooperatorId, FullName = model.FullName, DocumentId = docId, Rating = model.Rating //LocationCode = model.LocationCode, //PredictedGrowthStage = model.PredictedGrowthStage }; if (model.Rating != rating.NoRating) { locationService.SetLocationRating(model.LocationId, model.Rating); } if (model.JobOne == job.Planting || model.JobTwo == job.Planting || model.JobThree == job.Planting) { locationService.SetLocationIsPlantedToYes(model.LocationId); } if (model.JobOne == job.Staking || model.JobTwo == job.Staking || model.JobThree == job.Staking) { locationService.SetLocationIsStakedToYes(model.LocationId); } if (model.JobOne == job.Rowbanding || model.JobTwo == job.Rowbanding || model.JobThree == job.Rowbanding) { locationService.SetLocationIsRowbandedToYes(model.LocationId); } if (model.JobOne == job.Harvesting || model.JobTwo == job.Harvesting || model.JobThree == job.Harvesting) { locationService.SetLocationIsHarvestedToYes(model.LocationId); } locationService.SetLastVisitor(model.LocationId, model.FullName); using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }
static async Task ListDirectMessagesAsync(TwitterContext twitterCtx) { int count = 10; // intentionally set to a low number to demo paging string cursor = ""; List <DMEvent> allDmEvents = new List <DMEvent>(); // you don't have a valid cursor until after the first query DirectMessageEvents dmResponse = await (from dm in twitterCtx.DirectMessageEvents where dm.Type == DirectMessageEventsType.List && dm.Count == count select dm) .SingleOrDefaultAsync(); allDmEvents.AddRange(dmResponse.Value.DMEvents); cursor = dmResponse.Value.NextCursor; while (!string.IsNullOrWhiteSpace(cursor)) { dmResponse = await (from dm in twitterCtx.DirectMessageEvents where dm.Type == DirectMessageEventsType.List && dm.Count == count && dm.Cursor == cursor select dm) .SingleOrDefaultAsync(); allDmEvents.AddRange(dmResponse.Value.DMEvents); cursor = dmResponse.Value.NextCursor; } if (!allDmEvents.Any()) { Console.WriteLine("No items returned"); return; } Console.WriteLine($"Response Count: {allDmEvents.Count}"); Console.WriteLine("Responses:"); allDmEvents.ForEach(evt => { MessageCreate msgCreate = evt.MessageCreate; if (evt != null && msgCreate != null) { Console.WriteLine( "From ID: {0}\nTo ID: {1}\nMessage Text: {2}", msgCreate.SenderID ?? "None", msgCreate.Target?.RecipientID ?? "None", msgCreate.MessageData?.Text ?? "None"); } }); }
public IHttpActionResult Post(MessageCreate model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var messageService = new MessageService(Guid.Parse(User.Identity.GetUserId())); return(Ok(messageService.CreateMessage(model))); }
/// <summary> /// Invoked when a MESSAGE_CREATE event is fired from Discord's WebSocket server. /// </summary> /// <param name="response">JSON response.</param> public void MessageReceived(string response) { MessageCreate message = serializer.Deserialize <MessageCreate>(response); DiscordOnMessageEventArgs args = new DiscordOnMessageEventArgs() { Message = message.EventData }; OnMessageNotify(args); }
public async Task Execute(MessageCreate request) { Context.Messages.Add(new DataAccess.Message { Text = request.Text, UserID = request.UserID, }); await Context.SaveChangesAsync(); }
private void SendCreate() { var message = new MessageCreate() { Type = Types.Create, Name = Name, Password = Password }; Send(message); }
public ActionResult Create(MessageCreate message) { if (ModelState.IsValid) { _userId = User.Identity.GetUserId(); _messageService = new MessageService(_userId); _messageService.CreateMessage(message); return(RedirectToAction("Index")); } return(View(message)); }
public void PostMessage_Success() { var service = new Mock <IMessageService>(); service.Setup(S => S.CreateMessage(It.IsAny <MessageCreate>())).Returns(true); var controller = new MessageController(service.Object); var model = new MessageCreate(); var result = controller.Post(model); Assert.IsInstanceOfType(result, typeof(OkResult)); }
public async Task <IActionResult> Create([FromBody] MessageCreate model) { try { var result = await _messageService.Create(model); return(Ok(result)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public void PostMessage_Failure_CreateMessageFailed() { var service = new Mock <IMessageService>(); service.Setup(S => S.CreateMessage(It.IsAny <MessageCreate>())).Returns(false); var controller = new MessageController(service.Object); var model = new MessageCreate(); var result = controller.Post(model); Assert.IsInstanceOfType(result, typeof(InternalServerErrorResult)); }
// api/Message/Create public IHttpActionResult Post(MessageCreate message) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!_messageService.CreateMessage(message)) { return(InternalServerError()); } return(Ok()); }
public ActionResult Create(MessageCreate model) { if (!ModelState.IsValid) { return(View(model)); } var userId = Guid.Parse(User.Identity.GetUserId()); var service = new MessageService(userId); service.CreateMessage(model); return(RedirectToAction("Index")); }
public bool CreateMessage(MessageCreate messageCreate) { var entity = new Message() { Content = messageCreate.Content, SenderId = _userId, RecipientId = messageCreate.RecipientId, SentDate = DateTimeOffset.UtcNow, ModifiedDate = DateTimeOffset.UtcNow }; _ctx.Messages.Add(entity); return(_ctx.SaveChanges() == 1); }
public bool CreateMessage(MessageCreate model) { var entity = new Message() { MessageId = model.MessageId, NewMessage = model.NewMessage }; using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }
public async Task <Result <MessageCreate> > Send(string toScreenName, string messageText) { //TODO: Provide a generic class to make Twitter API Requests. if (string.IsNullOrEmpty(messageText)) { throw new TweetyException("You can't send an empty message."); } if (messageText.Length > 140) { throw new TweetyException("You can't send more than 140 char using this end point, use SendAsync instead."); } messageText = Uri.EscapeDataString(messageText); string resourceUrl = $"https://api.twitter.com/1.1/direct_messages/new.json?text={messageText}&screen_name={toScreenName}"; HttpResponseMessage response; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", AuthHeaderBuilder.Build(AuthContext, HttpMethod.Post, resourceUrl)); response = await client.PostAsync(resourceUrl, new StringContent("")); } if (response.StatusCode == HttpStatusCode.OK) { string msgCreateJson = await response.Content.ReadAsStringAsync(); MessageCreate mCreateObj = JsonConvert.DeserializeObject <MessageCreate>(msgCreateJson); return(new Result <MessageCreate>(mCreateObj)); } string jsonResponse = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(jsonResponse)) { TwitterError err = JsonConvert.DeserializeObject <TwitterError>(jsonResponse); return(new Result <MessageCreate>(err)); } else { //TODO: Provide a way to return httpstatus code return(new Result <MessageCreate>()); } }
public bool CreateMessage(MessageCreate model) { var entity = new Message() { OwnerId = _userId, Title = model.Title, Content = model.Content, CreatedUtc = DateTimeOffset.Now }; using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }
public bool CreateMessage(MessageCreate model) { var entity = new Message() { CreatorId = _userId, Title = model.Title, Content = model.Content, DateCreated = model.DateCreated }; using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }
private static void SendMessage(DiscordClient client, Snowflake?id, MessageCreate message) { if (!id.HasValue || !id.Value.IsValid()) { return; } DiscordChannel channel = client.Bot.DirectMessagesByUserId[id.Value]; if (channel != null) { channel.CreateMessage(client, message); return; } DiscordUser.CreateDirectMessageChannel(client, id.Value, newChannel => newChannel.CreateMessage(client, message)); }
public ActionResult Create(MessageCreate model) { if (!ModelState.IsValid) { return(View(model)); } if (_messageService.Value.CreateMessage(model)) { TempData["SaveResult"] = "Your Message Was Sent"; return(RedirectToAction("Index")); } ModelState.AddModelError("", "Message Could Not Be Created"); return(View(model)); }
public bool CreateMessage(MessageCreate model) { var entity = new Message() { CreatorId = _userId, Subject = model.Subject, Content = model.Content, DateCreated = DateTime.Now // ModifiedDateCreated = model.ModifiedDateCreated }; using (var ctx = new ApplicationDbContext()) { ctx.Messages.Add(entity); return(ctx.SaveChanges() == 1); } }