Skip to content

Instantly share code, notes, and snippets.

@sakapon
Created November 4, 2016 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/29ceb474beef6ca8f686b54f3b4e9f5c to your computer and use it in GitHub Desktop.
Save sakapon/29ceb474beef6ca8f686b54f3b4e9f5c to your computer and use it in GitHub Desktop.
BotSample / FactorizationBotApi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Connector;
namespace FactorizationBotApi
{
[BotAuthentication]
public class MessagesController : ApiController
{
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type != ActivityTypes.Message)
return Request.CreateResponse(HttpStatusCode.OK);
if (string.IsNullOrWhiteSpace(activity.Text))
return Request.CreateResponse(HttpStatusCode.OK);
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
var echoMessage = $"You sent \"{activity.Text}\".";
await Reply(connector, activity, echoMessage);
var mainMessage = Factorize(activity.Text);
await Reply(connector, activity, mainMessage);
return Request.CreateResponse(HttpStatusCode.OK);
}
static string Factorize(string text)
{
int i;
if (!int.TryParse(text, out i)) return "Send an integer.";
var factorized = MathHelper.Factorize2(Math.Abs(i));
var factorizedString = string.Join(" · ", factorized.Select(p => $"{p.Key}{(p.Value == 1 ? "" : $"^{p.Value}")}"));
return $"{i} = {(i >= 0 ? "" : "-")}{factorizedString}";
}
static async Task Reply(ConnectorClient connector, Activity activity, string message)
{
var reply = activity.CreateReply(message);
await connector.Conversations.ReplyToActivityAsync(reply);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment