private static async Task ApproveOrRejectLeaveRequest(IDialogContext context, Activity activity, string type, Employee employee)
        {
            var managerResponse = JsonConvert.DeserializeObject <ManagerResponse>(activity.Value.ToString());
            var leaveDetails    = await DocumentDBRepository.GetItemAsync <LeaveDetails>(managerResponse.LeaveId);

            var appliedByEmployee = await DocumentDBRepository.GetItemAsync <Employee>(leaveDetails.AppliedByEmailId);

            // Check the leave type and reduce in DB.
            leaveDetails.Status         = type == Constants.ApproveLeave ? LeaveStatus.Approved : LeaveStatus.Rejected;
            leaveDetails.ManagerComment = managerResponse.ManagerComment;
            await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);

            var conunt = EchoBot.GetDayCount(leaveDetails);

            var employeeView = EchoBot.EmployeeViewCard(appliedByEmployee, leaveDetails);
            UpdateMessageInfo managerMessageIds = leaveDetails.UpdateMessageInfo;

            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            var managerCardUpdate = activity.CreateReply();
            var managerView       = EchoBot.ManagerViewCard(appliedByEmployee, leaveDetails);

            managerCardUpdate.Attachments.Add(managerView);

            if (!string.IsNullOrEmpty(managerMessageIds.Manager))
            {
                await connector.Conversations.UpdateActivityAsync(managerCardUpdate.Conversation.Id, managerMessageIds.Manager, managerCardUpdate);
            }

            bool isGroup = !string.IsNullOrEmpty(leaveDetails.ChannelId);

            if (!isGroup)
            {
                var messageId = await SendNotification(context, isGroup?leaveDetails.ChannelId : appliedByEmployee.UserUniqueId, null, employeeView, managerMessageIds.Employee, isGroup);  // Update card.

                var msg = $"Your {conunt} days leave has been {leaveDetails.Status.ToString()} by your manager.";
                messageId = await SendNotification(context, isGroup?leaveDetails.ChannelId : appliedByEmployee.UserUniqueId, msg, null, null, isGroup);   // Send message.

                if (string.IsNullOrEmpty(messageId))
                {
                    var reply = activity.CreateReply();
                    reply.Text = $"Failed to notify {appliedByEmployee.DisplayName}. Please try again later.";
                    await context.PostAsync(reply);
                }
            }
            else
            {
                var msg       = $" - Your {conunt} days leave has been {leaveDetails.Status.ToString()} by your manager.";
                var messageId = await SendChannelNotification(context, leaveDetails.ChannelId, null, employeeView, appliedByEmployee, managerMessageIds.Employee, leaveDetails.ConversationId, false); // Update card.

                messageId = await SendChannelNotification(context, leaveDetails.ChannelId, msg, null, appliedByEmployee, null, leaveDetails.ConversationId, true);                                     // Send message.

                if (string.IsNullOrEmpty(messageId))
                {
                    var reply = activity.CreateReply();
                    reply.Text = $"Failed to notify {appliedByEmployee.DisplayName}. Please try again later.";
                    await context.PostAsync(reply);
                }
            }
        }
        private async Task HandleActions(IDialogContext context, Activity activity)
        {
            var reply = activity.CreateReply();

            reply.Attachments.Add(EchoBot.CreateSiteRequest());
            await context.PostAsync(reply);
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else if (activity.GetTextWithoutMentions().ToLower().Trim() == "score")
                {
                    await connector.Conversations.ReplyToActivityWithRetriesAsync(activity.CreateReply(tracker.GetScore().ToString()));

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
                else
                {
                    //if (tracker.GetScore() < 0.4) await EchoBot.SendMessage(connector, activity, "Cheer up buddy!");
                    await EchoBot.EchoMessage(connector, activity, tracker.GetScore(), tracker);

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
            }
        }
        private async Task ShowPendingApprovals(IDialogContext context, Activity activity, Employee employee)

        {
            var pendingLeaves = await DocumentDBRepository.GetItemsAsync <LeaveDetails>(l => l.Type == LeaveDetails.TYPE);

            pendingLeaves = pendingLeaves.Where(l => l.ManagerEmailId == employee.EmailId && l.Status == LeaveStatus.Pending);

            if (pendingLeaves.Count() == 0)

            {
                var reply = activity.CreateReply();

                reply.Text = "No pending leaves for approval.";

                await context.PostAsync(reply);
            }
            else

            {
                var reply = activity.CreateReply();

                reply.Text = "Here are all the leaves pending for approval:";

                foreach (var leave in pendingLeaves)

                {
                    var attachment = EchoBot.ManagerViewCard(employee, leave);

                    reply.Attachments.Add(attachment);
                }

                await context.PostAsync(reply);
            }
        }
        private static async Task SendSetManagerCard(IDialogContext context, Activity activity, Employee employee, string message)

        {
            //Ask for manager details.

            var card = EchoBot.SetManagerCard(); // WelcomeLeaveCard(employee.Name.Split(' ').First());

            if (message.Contains("@"))

            {
                var emailId = ExtractEmails(message).FirstOrDefault();

                if (!string.IsNullOrEmpty(emailId))

                {
                    await SetEmaployeeManager(context, activity, employee, emailId);

                    return;
                }
            }

            var msg = context.MakeMessage();

            msg.Text = "Please enter manager email ID for leave approval";

            msg.Attachments.Add(card);

            await context.PostAsync(msg);
        }
Beispiel #6
0
        public async Task <JsonResult> GetEditCard(string leaveId)
        {
            var leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(leaveId);

            var card = EchoBot.LeaveRequest(leaveDetails);

            return(Json(card, JsonRequestBehavior.AllowGet));
        }
        private static async Task WithdrawLeave(IDialogContext context, Activity activity, Employee employee, string leaveCategory)
        {
            var managerId = await GetManagerId(employee);

            if (managerId == null)
            {
                var reply = activity.CreateReply();
                reply.Text = "Unable to fetch your manager details. Please make sure that your manager has installed the Leave App.";
                await context.PostAsync(reply);
            }
            else
            {
                EditLeaveDetails vacationDetails = JsonConvert.DeserializeObject <EditLeaveDetails>(activity.Value.ToString());
                LeaveDetails     leaveDetails    = await DocumentDBRepository.GetItemAsync <LeaveDetails>(vacationDetails.LeaveId);

                leaveDetails.Status = LeaveStatus.Withdrawn;
                var attachment = EchoBot.ManagerViewCard(employee, leaveDetails);

                // Manger Updates.
                var conversationId = await SendNotification(context, managerId, null, attachment, leaveDetails.UpdateMessageInfo.Manager, false);

                if (!String.IsNullOrEmpty(conversationId))
                {
                    leaveDetails.UpdateMessageInfo.Manager = conversationId;
                }

                if (!String.IsNullOrEmpty(conversationId))
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var employeeCardReply = activity.CreateReply();
                    var employeeView      = EchoBot.EmployeeViewCard(employee, leaveDetails);
                    employeeCardReply.Attachments.Add(employeeView);

                    if (!string.IsNullOrEmpty(leaveDetails.UpdateMessageInfo.Employee))
                    {
                        await connector.Conversations.UpdateActivityAsync(employeeCardReply.Conversation.Id, leaveDetails.UpdateMessageInfo.Employee, employeeCardReply);
                    }
                    else
                    {
                        var reply = activity.CreateReply();
                        reply.Text = "Your leave request has been successfully withdrawn!";
                        await context.PostAsync(reply);

                        var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(employeeCardReply);
                    }
                }
                else
                {
                    var reply = activity.CreateReply();
                    reply.Text = "Failed to send notification to your manger. Please try again later.";
                    await context.PostAsync(reply);
                }
                // Update DB for all the message Id realted changes
                await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
            }
        }
        public async Task WelcomeDialogAsync(IDialogContext context)
        {
            var        replyMessage = context.MakeMessage();
            Attachment attachment   = null;

            attachment = EchoBot.WelcomeCard();
            replyMessage.Attachments = new List <Attachment> {
                attachment
            };
            await context.PostAsync(replyMessage);
        }
        public async Task SiteProvisioningSettingDialogAsync(IDialogContext context)
        {
            var        replyMessage = context.MakeMessage();
            Attachment attachment   = null;

            attachment = EchoBot.ShowTeamSiteRequestProvisoning();
            replyMessage.Attachments = new List <Attachment> {
                attachment
            };
            await context.PostAsync(replyMessage);

            this.DisplayOptionsAsync(context);
        }
Beispiel #10
0
 public StartUp(
     BotListener botListener,
     BotCommander botCommander,
     BotLogger botLogger,
     EchoBot bot,
     TranslateBot translateBot)
 {
     _botListener  = botListener;
     _botCommander = botCommander;
     _botLogger    = botLogger;
     _echoBot      = bot;
     _translateBot = translateBot;
 }
        public async Task SiteRequestDialogAsync(IDialogContext context)
        {
            var            replyMessage  = context.MakeMessage();
            Attachment     attachment    = null;
            DataController dc            = new DataController();
            string         SiteSettings  = dc.getSiteProvisionConfig();
            List <string>  SelectedValue = SiteSettings.Split(',').ToList();

            attachment = EchoBot.Test1(SelectedValue);
            replyMessage.Attachments = new List <Attachment> {
                attachment
            };
            await context.PostAsync(replyMessage);

            this.DisplayOptionsAsync(context);
        }
Beispiel #12
0
        private async Task <Attachment> PrepareCardForFinanceTeam(IDialogContext context, ExpenseReport expenseReport, string profileKey, string employeeId)
        {
            Employee employee;

            if (context.ConversationData.ContainsKey(profileKey))
            {
                employee = context.ConversationData.GetValue <Employee>(profileKey);
            }
            else
            {
                employee = await DocumentDBRepository.GetItemAsync <Employee>(employeeId, nameof(Employee));
            }
            var attachment = EchoBot.PrepareCardWithAttachment(expenseReport, employee, false, true);

            return(attachment);
        }
Beispiel #13
0
        private async Task <HttpResponseMessage> HandleInvokeMessages(Activity activity)

        {
            var activityValue = activity.Value.ToString();

            if (activity.Name == "task/fetch")

            {
                var action = Newtonsoft.Json.JsonConvert.DeserializeObject <TaskModule.TaskModuleActionData <EditLeaveDetails> >(activityValue);

                var leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(action.Data.Data.LeaveId);

                // TODO: Convert this to helpers once available.

                JObject taskEnvelope = new JObject();

                JObject taskObj = new JObject();

                JObject taskInfo = new JObject();

                taskObj["type"] = "continue";

                taskObj["value"] = taskInfo;

                taskInfo["card"] = JObject.FromObject(EchoBot.LeaveRequest(leaveDetails));

                taskInfo["title"] = "Edit Leave";

                taskInfo["height"] = 500;

                taskInfo["width"] = 600;

                taskEnvelope["task"] = taskObj;

                return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
            }
            else if (activity.Name == "task/submit")

            {
                activity.Name = Constants.EditLeave;

                await Conversation.SendAsync(activity, () => new RootDialog());
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    await EchoBot.EchoMessage(connector, activity);

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
            }
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            EchoBot echoBot = new EchoBot();

            echoBot.StartBot();
        }
        private static async Task AddUserToDatabase(IDialogContext context, TokenResponse tokenResponse)

        {
            var client = new SimpleGraphClient(tokenResponse.Token);

            User me = null;

            //User manager = null;

            var profilePhotoUrl = string.Empty;

            try

            {
                me = await client.GetMe();

                // manager = await client.GetManager();

                var photo = await client.GetProfilePhoto();

                var fileName = me.Id + "-ProflePhoto.png";

                string imagePath = System.Web.Hosting.HostingEnvironment.MapPath("~/ProfilePhotos/");

                if (!System.IO.Directory.Exists(imagePath))
                {
                    System.IO.Directory.CreateDirectory(imagePath);
                }

                imagePath += fileName;

                using (var fileStream = System.IO.File.Create(imagePath))

                {
                    photo.Seek(0, SeekOrigin.Begin);

                    photo.CopyTo(fileStream);
                }

                profilePhotoUrl = ApplicationSettings.BaseUrl + "/ProfilePhotos/" + fileName;
            }
            catch (Exception ex)

            {
                ErrorLogService.LogError(ex);

                profilePhotoUrl = null;
            }

            ConnectorClient connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));

            var channelData = context.Activity.GetChannelData <TeamsChannelData>();

            var employee = new Employee()

            {
                Name = me.DisplayName,

                EmailId = me.UserPrincipalName.ToLower(),

                UserUniqueId = context.Activity.From.Id, // For proactive messages

                TenantId = channelData.Tenant.Id,

                DemoManagerEmailId = string.Empty,

                JobTitle = me.JobTitle ?? me.UserPrincipalName,

                LeaveBalance = new LeaveBalance

                {
                    OptionalLeave = 2,

                    PaidLeave = 20,

                    SickLeave = 10
                },

                AzureADId = me.Id,

                PhotoPath = profilePhotoUrl,
            };

            var employeeDoc = await DocumentDBRepository.CreateItemAsync(employee);

            context.ConversationData.SetValue(GetProfileKey(context.Activity), employee);

            var msg = context.MakeMessage();

            var card = EchoBot.SetManagerCard(); // WelcomeLeaveCard(employee.Name.Split(' ').First());

            msg.Attachments.Add(card);

            await context.PostAsync(msg);
        }
Beispiel #17
0
 private static async Task SendNotificaiotnToManager(IDialogContext context, string profileKey, ExpenseReport expenseReport)
 {
     var employee = context.ConversationData.GetValue <Employee>(profileKey);
     var attachmentForManagerNotification = EchoBot.PrepareCardWithAttachment(expenseReport, employee, true);
     var conversationId = await SendNotification(context, employee.UserUniqueId, null, attachmentForManagerNotification, "", false);
 }
        /// <summary>

        /// Supports the commands recents, send, me, and signout against the Graph API

        /// </summary>

        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)

        {
            var activity = await result as Activity;

            string message = string.Empty;

            if (activity.Text != null)
            {
                message = Microsoft.Bot.Connector.Teams.ActivityExtensions.GetTextWithoutMentions(activity).ToLowerInvariant();
            }

            string userEmailId = string.Empty;

            string emailKey = GetEmailKey(activity);

            if (context.ConversationData.ContainsKey(emailKey))

            {
                userEmailId = context.ConversationData.GetValue <string>(emailKey);
            }
            else

            {
                // Fetch from roaster

                userEmailId = await GetUserEmailId(activity);

                context.ConversationData.SetValue(emailKey, userEmailId);
            }

            string profileKey = GetProfileKey(activity);

            Employee employee;

            if (context.ConversationData.ContainsKey(profileKey))

            {
                employee = context.ConversationData.GetValue <Employee>(profileKey);
            }
            else

            {
                employee = await DocumentDBRepository.GetItemAsync <Employee>(userEmailId);

                if (employee != null)
                {
                    context.ConversationData.SetValue <Employee>(profileKey, employee);
                }
            }

            if (employee == null)

            {
                // If Bot Service does not have a token, send an OAuth card to sign in.

                await SendOAuthCardAsync(context, (Activity)context.Activity);
            }
            else if ((string.IsNullOrEmpty(employee.ManagerEmailId) && string.IsNullOrEmpty(employee.DemoManagerEmailId))

                     && (!IsValidActionWithoutManager(activity.Value)))

            {
                await SendSetManagerCard(context, activity, employee, message);
            }
            else if (activity.Value != null)

            {
                await HandleActions(context, activity, employee);
            }
            else

            {
                if (message.ToLowerInvariant().Contains("set manager"))

                {
                    await SendSetManagerCard(context, activity, employee, message);
                }
                else if (message.ToLowerInvariant().Contains("reset"))

                {
                    // Sign the user out from AAD

                    await Signout(userEmailId, context);
                }
                else

                {
                    var reply = activity.CreateReply();

                    bool isManager = await IsManager(employee);

                    reply.Attachments.Add(EchoBot.WelcomeLeaveCard(employee.DisplayName, isManager));

                    try

                    {
                        await context.PostAsync(reply);
                    }
                    catch (Exception ex)

                    {
                        Console.WriteLine(ex);

                        throw;
                    }
                }
            }
        }
        private static async Task ApplyForLeave(IDialogContext context, Activity activity, Employee employee, string leaveCategory)

        {
            if (string.IsNullOrEmpty(employee.ManagerEmailId) && string.IsNullOrEmpty(employee.DemoManagerEmailId))

            {
                var reply = activity.CreateReply();

                reply.Text = "Please set your manager and try again.";

                reply.Attachments.Add(EchoBot.SetManagerCard());

                await context.PostAsync(reply);

                return;
            }

            var managerId = await GetManagerId(employee);

            if (managerId == null)

            {
                var reply = activity.CreateReply();

                reply.Text = "Unable to fetch your manager details. Please make sure that your manager has installed the Leave App.";

                await context.PostAsync(reply);
            }
            else

            {
                VacationDetails vacationDetails = null;

                if (activity.Name == Constants.EditLeave) // Edit request

                {
                    var editRequest = JsonConvert.DeserializeObject <EditRequest>(activity.Value.ToString());

                    vacationDetails = editRequest.data;
                }
                else
                {
                    vacationDetails = JsonConvert.DeserializeObject <VacationDetails>(activity.Value.ToString());
                }

                LeaveDetails leaveDetails;

                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))

                {
                    // Edit request

                    leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(vacationDetails.LeaveId);
                }
                else

                {
                    leaveDetails = new LeaveDetails();

                    leaveDetails.LeaveId = Guid.NewGuid().ToString();
                }

                leaveDetails.AppliedByEmailId = employee.EmailId;

                leaveDetails.EmployeeComment = vacationDetails.LeaveReason;

                var channelData = context.Activity.GetChannelData <TeamsChannelData>();

                leaveDetails.ChannelId = channelData.Channel?.Id; // Set channel Data if request is coming from a channel.

                if (!string.IsNullOrEmpty(leaveDetails.ChannelId))
                {
                    leaveDetails.ConversationId = activity.Conversation.Id;
                }

                leaveDetails.StartDate = new LeaveDate()

                {
                    Date = DateTime.Parse(vacationDetails.FromDate),

                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.FromDuration)
                };

                leaveDetails.EndDate = new LeaveDate()

                {
                    Date = DateTime.Parse(vacationDetails.ToDate),

                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.ToDuration)
                };

                leaveDetails.LeaveType = (LeaveType)Enum.Parse(typeof(LeaveType), vacationDetails.LeaveType);

                leaveDetails.Status = LeaveStatus.Pending;

                leaveDetails.ManagerEmailId = employee.ManagerEmailId;// Added for easy reporting.

                switch (leaveCategory)

                {
                case Constants.ApplyForPersonalLeave:

                    leaveDetails.LeaveCategory = LeaveCategory.Personal;

                    break;

                case Constants.ApplyForSickLeave:

                    leaveDetails.LeaveCategory = LeaveCategory.Sickness;

                    break;

                case Constants.ApplyForVacation:

                    leaveDetails.LeaveCategory = LeaveCategory.Vacation;

                    break;

                case Constants.ApplyForOtherLeave:

                default:

                    leaveDetails.LeaveCategory = LeaveCategory.Other;

                    break;
                }

                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))

                {
                    // Edit request

                    await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
                }
                else

                {
                    await DocumentDBRepository.CreateItemAsync(leaveDetails);
                }

                var attachment = EchoBot.ManagerViewCard(employee, leaveDetails);

                UpdateMessageInfo managerMessageIds = leaveDetails.UpdateMessageInfo;

                // Manger Updates.

                var conversationId = await SendNotification(context, managerId, null, attachment, managerMessageIds.Manager, false);

                if (!string.IsNullOrEmpty(conversationId))

                {
                    managerMessageIds.Manager = conversationId;
                }

                if (!string.IsNullOrEmpty(conversationId))

                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var employeeCardReply = activity.CreateReply();

                    var employeeView = EchoBot.EmployeeViewCard(employee, leaveDetails);

                    employeeCardReply.Attachments.Add(employeeView);

                    if (!string.IsNullOrEmpty(managerMessageIds.Employee))

                    {
                        // Update existing item.

                        await connector.Conversations.UpdateActivityAsync(employeeCardReply.Conversation.Id, managerMessageIds.Employee, employeeCardReply);
                    }
                    else

                    {
                        var reply = activity.CreateReply();

                        reply.Text = "Your leave request has been successfully submitted to your manager! Please review your details below:";

                        await context.PostAsync(reply);

                        var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(employeeCardReply);

                        managerMessageIds.Employee = msgToUpdate.Id;
                    }
                }
                else

                {
                    var reply = activity.CreateReply();

                    reply.Text = "Failed to send notification to your manger. Please try again later.";

                    await context.PostAsync(reply);
                }

                await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Called when a message is received by the dialog
        /// </summary>
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    activity    = await result as Activity;
            var    reply       = activity.CreateReply();
            string userEmailId = string.Empty;
            string userName    = string.Empty;

            string managerEmailKey = activity.From.Id + ManagerEmailKey;

            userEmailId = await GetUserMailId(context, activity);

            userName = await getUserName(activity);

            string   profileKey = GetProfileKey(activity);
            Employee employee   = new Employee();



            if (activity.Value != null)
            {
                var activityValue = JsonConvert.DeserializeObject <Models.activityJson>(activity.Value.ToString());
                if (activityValue.type == Constants.SetManager)
                {
                    if (ValidateManagerId(activityValue.managerId))
                    {
                        await SetManagerId(context, managerEmailKey, profileKey, activityValue.managerId);

                        reply.Text = "Manager Email Id is updated as : " + activityValue.managerId;
                    }
                    else
                    {
                        reply.Text = "Invalid Email Id, Please enter a valid manager email id. ";
                    }
                }
            }

            if (context.ConversationData.ContainsKey(profileKey))
            {
                employee = context.ConversationData.GetValue <Employee>(profileKey);
            }
            else
            {
                // TODO: Check if employee exists in DB before creating new record.

                employee = await DocumentDBRepository.GetItemAsync <Employee>(userEmailId, nameof(Employee));

                if (employee != null)
                {
                    context.ConversationData.SetValue <Employee>(profileKey, employee);
                }
                else
                {
                    employee = await SaveEmployeeToDbAsync(context, userEmailId, profileKey, managerEmailKey);

                    string emailKey = activity.From.Id + EmailKey;
                    context.ConversationData.SetValue(emailKey, userEmailId);
                    if (!string.IsNullOrEmpty(employee.ManagerEmailId))
                    {
                        context.ConversationData.SetValue(managerEmailKey, employee.ManagerEmailId);
                    }
                }
            }

            if (!(await IsManagerMailIdPresent(context, activity, managerEmailKey, employee)))
            {
                reply.Attachments.Add(EchoBot.CraeteManagerCard());
                await context.PostAsync(reply);

                return;
            }

            if (activity.Value != null)
            {
                var activityValue = JsonConvert.DeserializeObject <Models.activityJson>(activity.Value.ToString());
                switch (activityValue.type)
                {
                case Constants.CreateExpense:
                    reply.Attachments.Add(EchoBot.CreateExpense());
                    break;

                case Constants.EditExpense:
                    reply.Attachments.Add(EchoBot.EditExpense());
                    break;

                case Constants.UploadReport:
                    reply.Attachments.Add(EchoBot.UploadExpense());
                    break;

                case Constants.PendingApproval:
                    reply.Attachments.Add(EchoBot.PendingApproval());
                    break;

                case Constants.ApproveReport:
                    await HandleManagerAction(context, activity, profileKey, activityValue.reportId, activityValue.employeeId, true);

                    return;

                case Constants.RejectReport:
                    await HandleManagerAction(context, activity, profileKey, activityValue.reportId, activityValue.employeeId);

                    return;

                case Constants.SubmitExpense:
                    reply.Text = await ValidateAndSubmitExpense(context, activity, profileKey);

                    break;
                }
            }
            else if (activity.Attachments.Count > 0)
            {
                //Read attachement and save data to database
                try
                {
                    var attachmentList = HandleCsvAttachment.ReadCsv(activity.Attachments.First());
                    reply.Text = await ValidateAndSubmitExpense(context, activity, profileKey, attachmentList);

                    PrepareExpenseList(attachmentList);
                    var expenseReport = CreateExpenseReport(attachmentList);
                    reply.Attachments.Add(EchoBot.PrepareCardWithAttachment(expenseReport, null));
                    //reply.Text = "Uploaded sucessfully. ";
                }
                catch (Exception ex)
                {
                    reply.Text = "Unable to process the uploaded file, Please verify the file format. ";
                }
            }
            else
            {
                var typingReply = activity.CreateReply();
                typingReply.Text = null;
                typingReply.Type = ActivityTypes.Typing;
                await context.PostAsync(typingReply);

                reply.Attachments.Add(EchoBot.WelcomeCard(userEmailId, userName));
            }
            await context.PostAsync(reply);
        }
        private async Task HandleActions(IDialogContext context, Activity activity, Employee employee)

        {
            string type = string.Empty;

            if (activity.Name == Constants.EditLeave) // Edit request

            {
                var editRequest = JsonConvert.DeserializeObject <EditRequest>(activity.Value.ToString());

                type = editRequest.data.Type;
            }
            else

            {
                var details = JsonConvert.DeserializeObject <InputDetails>(activity.Value.ToString());

                type = details.Type;
            }

            var reply = activity.CreateReply();

            switch (type)

            {
            case Constants.ApplyForOtherLeave:

            case Constants.ApplyForPersonalLeave:

            case Constants.ApplyForSickLeave:

            case Constants.ApplyForVacation:

                await ApplyForLeave(context, activity, employee, type);

                break;

            case Constants.Withdraw:

                await WithdrawLeave(context, activity, employee, type);

                break;

            case Constants.RejectLeave:

            case Constants.ApproveLeave:

                await ApproveOrRejectLeaveRequest(context, activity, type, employee);

                break;

            case Constants.SetManager:

                await SetEmployeeManager(context, activity, employee);

                break;

            case Constants.ShowPendingApprovals:

                await ShowPendingApprovals(context, activity, employee);

                break;

            case Constants.LeaveRequest:

                try

                {
                    reply.Attachments.Add(EchoBot.LeaveRequest());
                }
                catch (Exception ex)

                {
                    ErrorLogService.LogError(ex);
                }

                await context.PostAsync(reply);

                break;

            case Constants.LeaveBalance:

                reply.Attachments.Add(EchoBot.ViewLeaveBalance(employee));

                await context.PostAsync(reply);

                break;

            case Constants.Holidays:

                reply.Attachments.Add(EchoBot.PublicHolidays());

                await context.PostAsync(reply);

                break;

            default:

                reply = activity.CreateReply("It will redirect to the tab");

                await context.PostAsync(reply);

                break;
            }
        }
        private async Task <Activity> HandleSystemMessage(Activity message)

        {
            if (message.Type == ActivityTypes.DeleteUserData)

            {
                // Implement user deletion here

                // If we handle user deletion, return a real message
            }

            else if (message.Type == ActivityTypes.ConversationUpdate)

            {
                // Handle conversation state changes, like members being added and removed

                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info

                // Not available in all channels



                for (int i = 0; i < message.MembersAdded.Count; i++)

                {
                    if (message.MembersAdded[i].Id == message.Recipient.Id)

                    {
                        // Bot is added. Let's send welcome message.

                        message.Text = "hi";

                        await Conversation.SendAsync(message, () => new RootDialog());

                        break;
                    }

                    else

                    {
                        try

                        {
                            var userId = message.MembersAdded[i].Id;

                            var channelData = message.GetChannelData <TeamsChannelData>();

                            var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl));



                            var parameters = new ConversationParameters

                            {
                                Members = new ChannelAccount[] { new ChannelAccount(userId) },

                                ChannelData = new TeamsChannelData

                                {
                                    Tenant = channelData.Tenant,

                                    Notification = new NotificationInfo()
                                    {
                                        Alert = true
                                    }
                                }
                            };



                            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);



                            var replyMessage = Activity.CreateMessageActivity();

                            replyMessage.ChannelData = new TeamsChannelData()
                            {
                                Notification = new NotificationInfo(true)
                            };

                            replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());

                            var name = message.MembersAdded[i].Name;

                            if (name != null)

                            {
                                name = name.Split(' ').First();
                            }

                            replyMessage.Attachments.Add(EchoBot.WelcomeLeaveCard(name, false));



                            await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage);
                        }

                        catch (Exception ex)

                        {
                            ErrorLogService.LogError(ex);
                        }
                    }
                }
            }

            else if (message.Type == ActivityTypes.ContactRelationUpdate)

            {
                // Handle add/remove from contact lists

                // Activity.From + Activity.Action represent what happened
            }

            else if (message.Type == ActivityTypes.Typing)

            {
                // Handle knowing tha the user is typing
            }

            return(null);
        }
Beispiel #23
0
 public static void Main(string[] args)
 {
     EchoBot T = new EchoBot();
 }
Beispiel #24
0
        private async Task <Activity> HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                if (message.MembersAdded.Any(m => m.Id.Contains(message.Recipient.Id)))
                {
                    try
                    {
                        var connectorClient      = new ConnectorClient(new Uri(message.ServiceUrl));
                        var channelData          = message.GetChannelData <TeamsChannelData>();
                        var TeamorConversationId = channelData.Team != null ? channelData.Team.Id : message.Conversation.Id;
                        if (channelData.Team == null)
                        {
                            await AddtoDatabase(message, TeamorConversationId, message.From.Id);

                            //await Conversation.SendAsync(message, () => new EchoBot());
                            ThumbnailCard card  = EchoBot.GetWelcomeMessage();
                            var           reply = message.CreateReply();
                            reply.TextFormat = TextFormatTypes.Xml;
                            reply.Attachments.Add(card.ToAttachment());
                            await connectorClient.Conversations.ReplyToActivityAsync(reply);

                            return(null);
                        }

                        var members = await connectorClient.Conversations.GetConversationMembersAsync(TeamorConversationId);

                        foreach (var meb in members)
                        {
                            await AddtoDatabase(message, TeamorConversationId, meb.Id);

                            ThumbnailCard card = EchoBot.GetWelcomeMessage();
                            //ThumbnailCard card = EchoBot.GetHelpMessage();
                            var replyMessage = Activity.CreateMessageActivity();
                            var parameters   = new ConversationParameters
                            {
                                Members     = new ChannelAccount[] { new ChannelAccount(meb.Id) },
                                ChannelData = new TeamsChannelData
                                {
                                    Tenant       = channelData.Tenant,
                                    Notification = new NotificationInfo()
                                    {
                                        Alert = true
                                    }
                                }
                            };

                            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);

                            replyMessage.ChannelData = new TeamsChannelData()
                            {
                                Notification = new NotificationInfo(true)
                            };
                            replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());
                            replyMessage.TextFormat   = TextFormatTypes.Xml;
                            replyMessage.Attachments.Add(card.ToAttachment());
                            await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage);
                        }
                        return(null);
                    }
                    catch (Exception ex)
                    {
                        return(null);
                    }
                    // Bot Installation
                    // Bot is added. Let's send welcome message.
                    //var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl));
                }

                // For Add new member
                for (int i = 0; i < message.MembersAdded.Count; i++)
                {
                    if (message.MembersAdded[i].Id != message.Recipient.Id)
                    {
                        try
                        {
                            var connectorClient      = new ConnectorClient(new Uri(message.ServiceUrl));
                            var userId               = message.MembersAdded[i].Id;
                            var channelData          = message.GetChannelData <TeamsChannelData>();
                            var user                 = new UserDetails();
                            var TeamorConversationId = channelData.Team != null ? channelData.Team.Id : message.Conversation.Id;
                            //string emailid = await GetUserEmailId(userId, message.ServiceUrl, TeamorConversationId);
                            //user.EmaildId = emailid;
                            user.EmaildId = await GetUserEmailId(userId, message.ServiceUrl, TeamorConversationId);

                            user.UserId   = userId;
                            user.UserName = await GetUserName(userId, message.ServiceUrl, TeamorConversationId);

                            var parameters = new ConversationParameters
                            {
                                Members     = new ChannelAccount[] { new ChannelAccount(userId) },
                                ChannelData = new TeamsChannelData
                                {
                                    Tenant       = channelData.Tenant,
                                    Notification = new NotificationInfo()
                                    {
                                        Alert = true
                                    }
                                }
                            };

                            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);

                            var replyMessage = Activity.CreateMessageActivity();
                            replyMessage.ChannelData = new TeamsChannelData()
                            {
                                Notification = new NotificationInfo(true)
                            };
                            replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());
                            var name = await GetUserName(userId, message.ServiceUrl, TeamorConversationId);

                            if (name != null)
                            {
                                name = name.Split(' ').First();
                            }
                            user.Type = Helper.Constants.NewUser;
                            var existinguserRecord = await DocumentDBRepository.GetItemsAsync <UserDetails>(u => u.EmaildId == user.EmaildId && u.Type == Helper.Constants.NewUser);

                            if (existinguserRecord.Count() == 0)
                            {
                                var NewUserRecord = await DocumentDBRepository.CreateItemAsync(user);
                            }
                            ThumbnailCard card = EchoBot.GetWelcomeMessage();
                            replyMessage.Attachments.Add(card.ToAttachment());

                            await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                var val = activity.Value;
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity, result);
                    return(response != null
                    ? Request.CreateResponse <ComposeExtensionResponse>(response)
                    : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    if (activity.Value != null)
                    {
                        result = await GetActivity(activity);
                    }
                    else
                    {
                        await EchoBot.EchoMessage(connector, activity);
                    }
                }
                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    for (int i = 0; i < activity.MembersAdded.Count; i++)
                    {
                        if (activity.MembersAdded[i].Id == activity.Recipient.Id)
                        {
                            var reply = activity.CreateReply();
                            reply.Text = "Hi! I am the Event Management bot for Dev Days 2019 happening in Taiwan. Ask me questions about the event and I can help you find answers Ask me questions like \n\n" +
                                         "   *\r What is the venue? \r\n\n" +
                                         "   *\r What tracks are available? \r\n\n" +
                                         "   *\r Do we have workshops planned? \n\n".Replace("\n", Environment.NewLine);

                            await connector.Conversations.ReplyToActivityAsync(reply);

                            var channelData = activity.GetChannelData <TeamsChannelData>();
                            if (channelData.Team != null)
                            {
                                ConversationParameters param = new ConversationParameters()
                                {
                                    Members = new List <ChannelAccount>()
                                    {
                                        new ChannelAccount()
                                        {
                                            Id = activity.From.Id
                                        }
                                    },
                                    ChannelData = new TeamsChannelData()
                                    {
                                        Tenant       = channelData.Tenant,
                                        Notification = new NotificationInfo()
                                        {
                                            Alert = true
                                        }
                                    }
                                };

                                var resource = await connector.Conversations.CreateConversationAsync(param);

                                await connector.Conversations.SendToConversationAsync(resource.Id, reply);
                            }
                            break;
                        }
                    }
                }
                return(new HttpResponseMessage(HttpStatusCode.Accepted));
            }
        }