コード例 #1
0
ファイル: Program.cs プロジェクト: adrenalin88/MessengerApp
        // Отправка сообщений на сервер. Если сообщение отправлено не было - оно будет обработано вместе с остальными неотправленными сообщениями.
        static async Task <bool> TrySendMessageAsync(OutMessage message)
        {
            var messageSender = _serviceProvider.GetService <IMessageSender>();

            var result = MessageSendResult.BeforeSend();

            while (!result.Sucsess)
            {
                result = await messageSender.SendMessageAsync(_url, new InMessage(message.MessageText, message.CreatedAt));

                if (result.Sucsess)
                {
                    message.Sent = true;
                    var messageService = _serviceProvider.GetService <IClientMessageService>();
                    await messageService.MarkAsSentAsync(message);

                    _log.Info($"Сообщение {message.Id}('{message.MessageText}') отправлено на сервер");
                }
                else
                {
                    if (result.Exception != null)
                    {
                        _log.Error("Ошибка при отправке сообщения на сервер", result.Exception);
                    }
                    else
                    {
                        _log.Warn($"При отправке сообщения получен ответ {result.ResponseCode}");
                    }
                    Thread.Sleep(_timeout);
                }
            }
            return(true);
        }
コード例 #2
0
 private bool CheckIfPinned(MessageSendResult result)
 {
     // We known if the application is pinned by checking the following send result flags:
     return(result.DeviceConnectionStatus == DeviceConnectionStatus.Connected &&
            result.SubscriptionStatus == SubscriptionStatus.Active &&
            result.NotificationStatus == NotificationStatus.Received);
 }
コード例 #3
0
        private void OnMessageSent(NotificationType type, MessageSendResult result)
        {
            PushNotificationsLogMsg msg = new PushNotificationsLogMsg(type, result);

            Dispatcher.BeginInvoke((Action)(() =>
                                            { trace.Add(msg); }));
        }
コード例 #4
0
 /// <summary>
 /// Once tile update sent, check if handled by the phone.
 /// In case that the application is not pinned, ask to pin.
 /// </summary>
 private void OnMessageSent(string userName, MessageSendResult result)
 {
     if (!CheckIfPinned(result))
     {
         AskUserToPin(result.ChannelUri);
     }
 }
コード例 #5
0
        private void OnRawSent(string userName, MessageSendResult result)
        {
            // In case that the device is disconnected, no need to send a tile message.
            if (result.DeviceConnectionStatus == DeviceConnectionStatus.TempDisconnected)
            {
                return;
            }

            // Checking these three flags we can know what's the state of both the device and apllication.
            bool isApplicationRunning =
                result.SubscriptionStatus == SubscriptionStatus.Active &&
                result.NotificationStatus == NotificationStatus.Received &&
                result.DeviceConnectionStatus == DeviceConnectionStatus.Connected;

            // In case that the application is not running, send a tile update with counter increase.
            if (!isApplicationRunning)
            {
                var tileMsg = new TilePushNotificationMessage(MessageSendPriority.High)
                {
                    Count = IncreaseCounter(userName),
                    BackgroundImageUri = BackgroundImageUri,
                    Title = Title
                };

                tileMsg.SendAsync(result.ChannelUri, Log, Log);
            }
        }
コード例 #6
0
        public MessageSendResult Send(AppAccountInfo appAccount, MessageInfo message)
        {
            var result = new MessageSendResult();

            if (appAccount == null)
            {
                appAccount = ProviderGateway.AppAccountProvider.Get(message.AppAccountId);
            }
            var token = ProviderGateway.TokenProvider.GetToken(appAccount);

            if (string.IsNullOrWhiteSpace(message.ToOpenId))
            {
                var appUsers  = ProviderGateway.AppUserAccountProvider.GetListByUserId(message.TenantId, message.ToUser.Split('|'), appAccount.AppId);
                var toOpenIds = new List <string>();
                foreach (var appUser in appUsers)
                {
                    toOpenIds.Add(appUser.OpenId);
                }
                message.ToOpenId = string.Join("|", toOpenIds);
            }

            var description = new StringBuilder();

            foreach (var detail in message.Content.Detail)
            {
                if (string.IsNullOrWhiteSpace(detail.Text))
                {
                    description.AppendFormat("{0}\n", detail.Value);
                }
                else
                {
                    description.AppendFormat("{0}:{1}\n", detail.Text, detail.Value);
                }
            }
            var picUrl = MediaDataHelper.GetPicUrl(message.ProductId, appAccount.Type.ToString());

            AppConnectLogHelper.DebugFormat("调用企业微信发送消息:Token{0};ToOpenId{1}; AgentId{2} ContentUrl{3}, ContentTitle{4}, description:{5}, pic:{6},tenantId:{7}", token, message.ToOpenId, appAccount.AgentId, message.Content.Url, message.Content.Title, description.ToString(), picUrl, appAccount.TenantId);

            if (string.IsNullOrEmpty(message.Content.Url))
            {
                message.Content.Url = AppConnectHostConfig.Cache[0] + string.Format("/Common/Error?title={0}&message={1}", HttpUtility.UrlEncode("友情提醒"), HttpUtility.UrlEncode("抱歉,此消息暂不支持在此查看,请在电脑浏览器中查看"));
            }
            WorkMessageSendResult sendResult = new WorkMessageSendResult();

            sendResult = WeChatSDK.Work.Message.SendNews(token, message.ToOpenId, Convert.ToInt32(appAccount.AgentId), message.Content.Title, description.ToString(), message.Content.Url, picUrl);
            if (sendResult.ErrCode == 0)
            {
                result.State = MessageState.Success;
                AppConnectLogHelper.DebugFormat("企业微信发送消息成功{0}", JsonConvert.SerializeObject(sendResult));
            }
            else
            {
                result.State = MessageState.Failed;
                AppConnectLogHelper.ErrorFormat("企业微信发送消息失败,errorCode:{0},errorMsg:{1},tenantId:{2},userId:{3}", sendResult.ErrCode, sendResult.ErrMsg, appAccount.TenantId, message.ToOpenId);
            }

            result.ErrMsg = SerializeHelper.Serialize(sendResult);
            return(result);
        }
コード例 #7
0
        public MessageSendResult MessageSend(MessageSendArgument argument)
        {
            var result  = new MessageSendResult();
            var command = new MessageSend.Command {
                Argument = argument, Result = result
            };

            _mediator.Send(command).Wait();
            return(result);
        }
コード例 #8
0
        /// <summary>
        /// Update MessageSendResult in EventMessages Collection.
        /// </summary>
        /// <param name="id">unique id that identifies the record in EventMessages Collection. </param>
        /// <param name="statusCode">HTTP Status code.</param>
        /// <param name="lastAtttemptTime">Last attempt time.</param>
        /// <param name="responseBody">Response body.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task UpdateMessageSendResult(string id, int statusCode, DateTime lastAtttemptTime, string responseBody)
        {
            MessageSendResult messageSendResult = new MessageSendResult()
            {
                LastAttemptTime = lastAtttemptTime,
                StatusCode      = statusCode,
                ResponseBody    = responseBody,
            };

            await this.eventHelper.UpdateEventMessageAsync(id, messageSendResult);
        }
コード例 #9
0
 public PushNotificationsLogMsg(NotificationType notificationType, MessageSendResult messageSendResult)
 {
     this.Timestamp              = messageSendResult.Timestamp;
     this.MessageId              = messageSendResult.AssociatedMessage.Id.ToString();
     this.ChannelUri             = messageSendResult.ChannelUri.ToString();
     this.NotificationType       = notificationType;
     this.StatusCode             = messageSendResult.StatusCode;
     this.NotificationStatus     = messageSendResult.NotificationStatus.ToString();
     this.DeviceConnectionStatus = messageSendResult.DeviceConnectionStatus.ToString();
     this.SubscriptionStatus     = messageSendResult.DeviceConnectionStatus.ToString();
 }
コード例 #10
0
 /// <summary>
 /// Initialize a new instance of this type.
 /// </summary>
 public MessageStatus(string pattern, MessageSendResult result)
 {
     Pattern                = pattern;
     Timestamp              = result.Timestamp;
     MessageType            = MessageTypes[result.AssociatedMessage.GetType()];
     MessageId              = result.AssociatedMessage.Id;
     ChannelUri             = result.ChannelUri;
     StatusCode             = result.StatusCode;
     NotificationStatus     = result.NotificationStatus;
     DeviceConnectionStatus = result.DeviceConnectionStatus;
     SubscriptionStatus     = result.SubscriptionStatus;
 }
コード例 #11
0
        /// <summary>
        /// Send a raw notification message to the client.
        /// </summary>
        /// <param name="clientURI">Client Uri.</param>
        /// <param name="rawData">The data to send.</param>
        /// <returns>The message send operation result for the last message sent .</returns>
        private static MessageSendResult SendMessage(Uri clientURI, byte[] rawData)
        {
            // Send a raw message
            //
            // For more information on the WindowsPhone.Recipes.Push.Messages namespace,
            // and the the push notification implementation please refer this link:
            // http://msdn.microsoft.com/en-us/WP7TrainingCourse_UsingPushNotificationsLab
            //
            RawPushNotificationMessage message = new RawPushNotificationMessage(MessageSendPriority.High);

            message.RawData = rawData;
            MessageSendResult result = message.Send(clientURI);

            return(result);
        }
コード例 #12
0
        public async Task <MessageSendResult> SendMessageAsync(string url, MessageBase message)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsJsonAsync(url, message);

                    return(MessageSendResult.FromResponseStatusCode(response.StatusCode));
                }
                catch (Exception xcp)
                {
                    return(MessageSendResult.FromException(xcp));
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// update last message send result.
        /// </summary>
        /// <param name="id">Id to uniquely identify the record.</param>
        /// <param name="messageSendResult">MessageSendResult instance</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task UpdateEventMessageAsync(string id, MessageSendResult messageSendResult)
        {
            await this.EnsureInitializedAsync();

            var options = new FeedOptions {
                EnableCrossPartitionQuery = true
            };
            var document = this.documentClient.CreateDocumentQuery <EventMessage>(this.eventMessagesCollection.SelfLink, options)
                           .Where(x => x.Id == id).AsEnumerable().FirstOrDefault();

            if (document != null)
            {
                EventMessage eventMessage = (dynamic)document;
                eventMessage.MessageSendResult = messageSendResult;
                await this.documentClient.ReplaceDocumentAsync(document.SelfLink, eventMessage);
            }
        }
コード例 #14
0
        /// <summary>
        /// 重发消息
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public string Resend(int tenantId, int id)
        {
            var messageInfo = Get(tenantId, id);
            var appAccount  = ProviderGateway.AppAccountProvider.Get(messageInfo.AppAccountId);
            var instance    = MessageFactory.GetIntance(appAccount);
            var sendResult  = new MessageSendResult();

            try
            {
                sendResult = instance.Send(appAccount, messageInfo);
            }
            catch (Exception ex)
            {
                sendResult.State  = MessageState.Failed;
                sendResult.ErrMsg = ex.Message;
            }
            finally
            {
                //更新msgid、发送结果
                UpdateSendResult(messageInfo.TenantId, messageInfo.Id, sendResult.MessageId, sendResult.State, sendResult.ErrMsg);
            }
            return(messageInfo.BatchId);
        }
コード例 #15
0
        /// <summary>
        /// 微信发送(企业号)
        /// </summary>
        /// <param name="content">消息内容</param>
        /// <param name="list">用户列表</param>
        /// <returns></returns>
        public void WeChatSend(string content, List <UserEntity> list)
        {
            string SystemName   = Config.GetValue("SystemName");//系统名称
            string SalesManager = "";

            foreach (var item in list)
            {
                if (SalesManager != "")
                {
                    SalesManager += "|";
                }
                SalesManager += item.F_Account;
            }
            var text = new SendText()
            {
                agentid = Config.GetValue("ApplicationId"), //应用ID
                touser  = SalesManager,                     //@all:所有人,多个用户名用 “|”隔开
                text    = new SendText.SendItem()
                {
                    content = content
                }
            };
            MessageSendResult result = text.Send();//发送消息,并返回结果
        }
コード例 #16
0
        /// <summary>
        /// Process request to send preview card
        /// </summary>
        /// <param name="currentDateTime">Current dateTime</param>
        /// <returns>A <see cref="Task"/>Representing the asynchronous operation</returns>
        public async Task <HttpResponseMessage> Post(string currentDateTime = "")
        {
            this.logProvider.LogInfo($"Processing events to send the reminder to owner. CurrentDateTime:{currentDateTime}");

            DateTimeOffset currentDateTimeOffset;

            if (!DateTimeOffset.TryParse(currentDateTime, null, DateTimeStyles.AdjustToUniversal, out currentDateTimeOffset))
            {
                currentDateTimeOffset = DateTimeOffset.UtcNow;
            }

            var events = await(await this.eventHelper.GetCelebrationEventsAsync(GetEventQuery(currentDateTimeOffset.Date))).ToListAsync();

            this.logProvider.LogInfo($"found {events.Count} which are coming in next 72 hours.");
            if (events.Count > 0)
            {
                var existingRecurringEvents = await(await this.eventHelper.GetRecurringEventsAsync(events.Select(x => x.Id).ToList())).ToListAsync();

                this.logProvider.LogInfo($"Found {existingRecurringEvents.Count} for which reminder has already sent");
                int    lastAttemptStatusCode = (int)HttpStatusCode.OK;
                string responseBody          = string.Empty;

                // remove events which exist in Occurrences collection
                events.RemoveAll(x => existingRecurringEvents.Any(y => y.EventId == x.Id));

                if (events.Count > 0)
                {
                    this.users = await this.userManagementHelper.GetUsersByAadObjectIdsAsync(events.Select(x => x.OwnerAadObjectId).ToList());

                    this.connectorServiceHelper = new ConnectorServiceHelper(this.CreateConnectorClient(this.users.FirstOrDefault().ServiceUrl), this.logProvider);
                }

                // Loop each event and make entry in Occurrences collection to send preview and event card.
                foreach (var celebrationEvent in events)
                {
                    this.logProvider.LogInfo("Processing event to send reminder", new Dictionary <string, string>()
                    {
                        { "EventId", celebrationEvent.Id }, { "UserObjectId", celebrationEvent.OwnerAadObjectId }
                    });

                    // Get event owner information.
                    var user = this.users.Where(x => x.AadObjectId == celebrationEvent.OwnerAadObjectId).FirstOrDefault();

                    // update conversation id if it is null.
                    await this.ModifyUserDetailsAsync(user);

                    DateTime       upcomingEventDate          = Common.GetUpcomingEventDate(celebrationEvent.Date, currentDateTimeOffset.Date);
                    var            timespan                   = Array.ConvertAll <string, int>(ApplicationSettings.TimeToPostCelebration.Split(':'), Convert.ToInt32);
                    DateTime       upcomingEventDateTime      = upcomingEventDate.AddHours(timespan[0]).AddMinutes(timespan[1]);
                    DateTimeOffset upcomingEventDateTimeInUTC = TimeZoneInfo.ConvertTimeToUtc(upcomingEventDateTime, TimeZoneInfo.FindSystemTimeZoneById(celebrationEvent.TimeZoneId));

                    // add an entry to Occurrence collection for all the upcoming event.
                    EventOccurrence eventOccurrence = new EventOccurrence
                    {
                        EventId = celebrationEvent.Id,
                        Date    = upcomingEventDateTimeInUTC,
                    };

                    await this.eventHelper.AddRecurringEventAsync(eventOccurrence);

                    // Do not send reminder if event is today.
                    if (upcomingEventDate != currentDateTimeOffset.Date)
                    {
                        // Add new entry to EventMessages collection for reminder.
                        EventMessage eventMessage = new EventMessage
                        {
                            OccurrenceId = eventOccurrence.Id,
                            EventId      = celebrationEvent.Id,
                            Activity     = this.GetEventMessageActivity(celebrationEvent, user),
                            MessageType  = MessageType.Preview,
                            ExpireAt     = upcomingEventDate.AddHours(24),
                        };

                        await this.eventHelper.AddEventMessageAsync(eventMessage);

                        bool      isMessageSentSuccessfully = false;
                        Exception exception = null;

                        try
                        {
                            HeroCard previewCard = CelebrationCard.GetPreviewCard(eventMessage.Activity);

                            string message = string.Format(Strings.PreviewText, user.UserName);

                            this.logProvider.LogInfo("Sending reminder message to the owner of the event", new Dictionary <string, string>()
                            {
                                { "EventId", celebrationEvent.Id },
                                { "Attachment", Newtonsoft.Json.JsonConvert.SerializeObject(previewCard) },
                                { "Message", message },
                            });

                            // Send reminder of event to owner.
                            await this.connectorServiceHelper.SendPersonalMessageAsync(
                                message,
                                new List <Attachment> {
                                previewCard.ToAttachment()
                            },
                                user.ConversationId);

                            this.logProvider.LogInfo($"Reminder message sent to the owner of the event. EventId: {celebrationEvent.Id}");
                        }
                        catch (HttpException httpException)
                        {
                            lastAttemptStatusCode = httpException.GetHttpCode();
                            responseBody          = httpException.GetHtmlErrorMessage();
                            exception             = httpException;
                        }
                        catch (ErrorResponseException errorResponseException)
                        {
                            lastAttemptStatusCode = (int)errorResponseException.Response.StatusCode;
                            responseBody          = errorResponseException.Response.Content.ToString();
                            exception             = errorResponseException;
                        }
                        catch (Exception ex)
                        {
                            lastAttemptStatusCode = (int)HttpStatusCode.BadRequest;
                            responseBody          = ex.ToString();
                        }
                        finally
                        {
                            if (!isMessageSentSuccessfully)
                            {
                                this.logProvider.LogError("Failed to send reminder for upcoming event.", exception, new Dictionary <string, string>
                                {
                                    { "EventId", eventMessage.EventId },
                                    { "OccurrenceId", eventMessage.OccurrenceId },
                                    { "eventActivity", eventMessage.Activity.ToString() },
                                    { "LastAttemptStatusCode", lastAttemptStatusCode.ToString() },
                                    { "LastAttemptTime", DateTime.UtcNow.ToString() },
                                    { "ConversationId", user.ConversationId },
                                });
                            }

                            MessageSendResult messageSendResult = new MessageSendResult()
                            {
                                LastAttemptTime = DateTime.UtcNow,
                                StatusCode      = lastAttemptStatusCode,
                                ResponseBody    = responseBody,
                            };

                            await this.eventHelper.UpdateEventMessageAsync(eventMessage.Id, messageSendResult);
                        }
                    }
                    else
                    {
                        this.logProvider.LogInfo("Not sending reminder for this event as its upcoming event date is today.");
                    }
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
コード例 #17
0
        public string Send(MessageInfo message)
        {
            var messageBuildList = new List <MessageInfo>();

            if (string.IsNullOrWhiteSpace(message.BatchId))
            {
                message.BatchId = Guid.NewGuid().ToString();
            }
            if (message.MessageTypeList.Count > 0)
            {
                var appUsers = ProviderGateway.AppUserAccountProvider.GetListByUserId(message.TenantId, message.ToUser.Split('|'));
                var appIds   = new List <string>();
                var userDic  = new Dictionary <string, List <int> >();
                foreach (var appUser in appUsers)
                {
                    if (!userDic.ContainsKey(appUser.AppId))
                    {
                        userDic.Add(appUser.AppId, new List <int> {
                            appUser.UserId
                        });
                        appIds.Add(appUser.AppId);
                    }
                    else
                    {
                        userDic[appUser.AppId].Add(appUser.UserId);
                    }
                }
                if (appIds.Count <= 0)
                {
                    AppConnectLogHelper.DebugFormat("消息接收者{0}没有绑定钉钉微信相关产品!消息内容是:{1}", message.ToUser, Newtonsoft.Json.JsonConvert.SerializeObject(message));
                    throw new Exception("接收人未注册钉钉,微信等相关产品!");
                }
                var appAccounts = ProviderGateway.AppAccountProvider.GetListByAppId(message.TenantId, appIds);
                var messageUrl  = message.Content.Url;

                IEnumerable <AppAccountInfo> appAccountDistinct = new List <AppAccountInfo>();
                //去除重复应用
                Dictionary <string, AppAccountInfo> appAccountDistinctAgent = new Dictionary <string, AppAccountInfo>();
                foreach (var appAccount in appAccounts)
                {
                    if (string.IsNullOrEmpty(appAccount.AppId) || string.IsNullOrEmpty(appAccount.AgentId))
                    {
                        continue;
                    }
                    var key = string.Format("{0}_{1}", appAccount.TenantId, appAccount.AppId);
                    if (!appAccountDistinctAgent.ContainsKey(key))
                    {
                        appAccountDistinctAgent.Add(key, appAccount);
                    }
                }
                appAccountDistinct = appAccountDistinctAgent.Select(t => t.Value);
                AppConnectLogHelper.DebugFormat("appAccount个数:{0}", appAccountDistinct.Count());
                foreach (var appAccount in appAccountDistinct)
                {
                    if (message.MessageTypeList.Contains(appAccount.Type))
                    {
                        var messageModel = BuildNewModel(message);
                        messageModel.AppAccountId = appAccount.AppAccountId;
                        messageModel.Content.Url  = GetUrl(messageModel.TenantId, messageModel.AppAccountId, messageModel.ProductId, messageUrl);
                        if (appAccount.Type == 21)//只有钉钉的时候
                        {
                            messageModel.Content.DingTalkPCUrl = GetDingTalkPCUrl(messageModel.TenantId, messageModel.AppAccountId, messageModel.ProductId, messageUrl);
                        }
                        messageModel.ContentJson = SerializeHelper.Serialize(messageModel.Content);
                        var instance  = MessageFactory.GetIntance(appAccount);
                        var buildList = instance.Build(appAccount, userDic[appAccount.AppId], messageModel);
                        messageBuildList.AddRange(buildList);
                        AppConnectLogHelper.DebugFormat("message model:{0},messageType:{1}", Newtonsoft.Json.JsonConvert.SerializeObject(messageModel), appAccount.Type);
                    }
                }
            }
            AppConnectLogHelper.DebugFormat("组装发送消息的个数:{0}", messageBuildList.Count());
            foreach (var messageBuild in messageBuildList)
            {
                var appAccount = ProviderGateway.AppAccountProvider.Get(messageBuild.AppAccountId);
                if (messageBuild.Id == 0)
                {
                    messageBuild.State = MessageState.Unsent;
                    messageBuild.Id    = Add(messageBuild);
                }
                var instance   = MessageFactory.GetIntance(appAccount);
                var sendResult = new MessageSendResult();
                try
                {
                    messageBuild.ProductId = message.ProductId;
                    sendResult             = instance.Send(appAccount, messageBuild);
                }
                catch (Exception ex)
                {
                    sendResult.State  = MessageState.Failed;
                    sendResult.ErrMsg = ex.Message;
                }
                finally
                {
                    //更新msgid、发送结果
                    UpdateSendResult(messageBuild.TenantId, messageBuild.Id, sendResult.MessageId, sendResult.State, sendResult.ErrMsg);
                }
            }

            return(message.BatchId);
        }
コード例 #18
0
 /// <summary>
 /// Logs push message result.
 /// </summary>
 protected void Log(MessageSendResult result)
 {
     ResultLogger.Log(DisplayName, result);
 }
コード例 #19
0
        /// <summary>
        /// Send event card in Teams.
        /// </summary>
        /// <param name="message">message.</param>
        /// <param name="attachments">Attachments list</param>
        /// <param name="teamId">teamId</param>
        /// <param name="eventMessages">List of EventMessage</param>
        /// <param name="entities">entities</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task SendEventCard(string message, List <Attachment> attachments, string teamId, List <EventMessage> eventMessages, List <Entity> entities = null)
        {
            int       lastAttemptStatusCode     = (int)HttpStatusCode.OK;
            string    responseBody              = string.Empty;
            bool      isMessageSentSuccessfully = false;
            Exception exception = null;

            try
            {
                await this.connectorServiceHelper.SendMessageInCarouselFormatAsync(message, attachments, teamId, entities);

                isMessageSentSuccessfully = true;
            }
            catch (HttpException httpException)
            {
                lastAttemptStatusCode = httpException.GetHttpCode();
                responseBody          = httpException.GetHtmlErrorMessage();
                exception             = httpException;
            }
            catch (ErrorResponseException errorResponseException)
            {
                lastAttemptStatusCode = (int)errorResponseException.Response.StatusCode;
                responseBody          = errorResponseException.Response.Content.ToString();
                exception             = errorResponseException;
                if (errorResponseException.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    await this.userManagementHelper.DeleteTeamDetailsAsync(teamId);

                    await this.userManagementHelper.DeleteUserTeamMembershipByTeamIdAsync(teamId);
                }
            }
            catch (Exception ex)
            {
                lastAttemptStatusCode = (int)HttpStatusCode.BadRequest;
                responseBody          = ex.ToString();
            }
            finally
            {
                if (!isMessageSentSuccessfully)
                {
                    foreach (var eventMessage in eventMessages)
                    {
                        this.logProvider.LogError("Failed to send event card.", exception, new Dictionary <string, string>
                        {
                            { "EventId", eventMessage.EventId },
                            { "OccurrenceId", eventMessage.OccurrenceId },
                            { "eventActivity", eventMessage.Activity.ToString() },
                            { "LastAttemptStatusCode", lastAttemptStatusCode.ToString() },
                            { "LastAttemptTime", DateTime.UtcNow.ToString() },
                            { "TeamId", teamId },
                        });
                    }
                }

                foreach (var eventMessage in eventMessages)
                {
                    MessageSendResult messageSendResult = new MessageSendResult()
                    {
                        LastAttemptTime = DateTime.Now,
                        StatusCode      = lastAttemptStatusCode,
                        ResponseBody    = responseBody,
                    };

                    await this.eventHelper.UpdateEventMessageAsync(eventMessage.Id, messageSendResult);
                }
            }
        }
コード例 #20
0
        public MessageSendResult Send(AppAccountInfo appAccount, MessageInfo message)
        {
            var result = new MessageSendResult();

            if (appAccount == null)
            {
                appAccount = ProviderGateway.AppAccountProvider.Get(message.AppAccountId);
            }

            var token = ProviderGateway.TokenProvider.GetToken(appAccount);

            if (string.IsNullOrWhiteSpace(message.TemplateId))
            {
                if (string.IsNullOrWhiteSpace(message.TemplateIdShort))
                {
                    result.State  = MessageState.Failed;
                    result.ErrMsg = "模板为空";
                    return(result);
                }
                //跟据数据库中对应关系获取id
                var templateId = ProviderGateway.TemplateMappingProvider.GetTemplateId(appAccount.AppId, message.TemplateIdShort);
                //不存在增加模板
                if (string.IsNullOrWhiteSpace(templateId))
                {
                    var template = Template.AddTemplate(token, message.TemplateIdShort);
                    if (template.ErrCode != 0)
                    {
                        result.State  = MessageState.Failed;
                        result.ErrMsg = SerializeHelper.Serialize(template);
                        return(result);
                    }
                    message.TemplateId = template.TemplateId;
                    ProviderGateway.TemplateMappingProvider.Add(
                        new TemplateMappingInfo
                    {
                        AppId           = appAccount.AppId,
                        TemplateIdShort = message.TemplateIdShort,
                        TemplateId      = template.TemplateId,
                        CreateBy        = message.FromUser
                    });
                }
                else
                {
                    message.TemplateId = templateId;
                }
            }

            if (string.IsNullOrWhiteSpace(message.ToOpenId))
            {
                var appUser = ProviderGateway.AppUserAccountProvider.GetByUserId(message.TenantId, Convert.ToInt32(message.ToUser), appAccount.AppId);
                if (appUser == null)
                {
                    result.State  = MessageState.Failed;
                    result.ErrMsg = "用户未绑定";
                    return(result);
                }
                message.ToOpenId = appUser.OpenId;
            }

            var jsondata = new StringBuilder();

            jsondata.Append("{");
            foreach (var detail in message.Content.Detail)
            {
                jsondata.Append("\"" + detail.Key + "\":{\"value\":\"" + detail.Value + "\"},");
            }
            jsondata.Remove(jsondata.Length - 1, 1);
            jsondata.Append("}");

            var picUrl = MediaDataHelper.GetPicUrl(message.ProductId, appAccount.Type.ToString());

            AppConnectLogHelper.DebugFormat("调用微信服务号发送消息:Token{0};ToOpenId{1}; AgentId{2} ContentUrl{3}, ContentTitle{4}, description:{5}, pic:{6}", token, message.ToOpenId, appAccount.AgentId, message.Content.Url, message.Content.Title, jsondata.ToString(), picUrl);
            if (string.IsNullOrEmpty(message.Content.Url))
            {
                message.Content.Url = AppConnectHostConfig.Cache[0] + string.Format("/Common/Error?title={0}&message={1}", HttpUtility.UrlEncode("友情提醒"), HttpUtility.UrlEncode("抱歉,此消息暂不支持在此查看,请在电脑浏览器中查看"));
            }
            var sendResult = Template.SendTemplateMessageForJson(token, message.ToOpenId, message.TemplateId, "", message.Content.Url, jsondata.ToString());

            if (sendResult.ErrCode != 0)
            {
                result.State  = MessageState.Failed;
                result.ErrMsg = SerializeHelper.Serialize(sendResult);
                AppConnectLogHelper.ErrorFormat("企业微信发送消息失败,errorCode:{0},errorMsg:{1}", sendResult.ErrCode, sendResult.ErrMsg);
                return(result);
            }

            result.State     = MessageState.Success;
            result.MessageId = sendResult.MsgId.ToString();
            result.ErrMsg    = SerializeHelper.Serialize(sendResult);
            return(result);
        }
コード例 #21
0
 void IMessageSendResultLogger.Log(string patternName, MessageSendResult result)
 {
     Dispatcher.BeginInvoke(() => Status.Add(new MessageStatus(patternName, result)));
 }
コード例 #22
0
 /// <summary>
 /// Initializes a new instance of this type.
 /// </summary>
 /// <param name="result">The send operation result.</param>
 /// <param name="innerException">An inner exception causes this error.</param>
 internal MessageSendException(MessageSendResult result, Exception innerException)
     : base(Resources.FailedToSendMessage, innerException)
 {
     Result = result;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageSendException"/> class. 
 /// </summary>
 /// <param name="result">
 /// The send operation result.
 /// </param>
 /// <param name="innerException">
 /// An inner exception causes this error.
 /// </param>
 public MessageSendException(MessageSendResult result, Exception innerException)
     : base(Resources.FailedToSendMessage, innerException)
 {
     this.Result = result;
 }