Beispiel #1
0
 public SendResponse(INotifyAction action, string senderName, IRecipient recipient, SendResult sendResult)
 {
     SenderName = senderName;
     Recipient = recipient;
     Result = sendResult;
     NotifyAction = action;
 }
Beispiel #2
0
 public SendResult Send(Message message, object routingKey, int timeoutMilliseconds = 30000)
 {
     var sendResult = SendAsync(message, routingKey, timeoutMilliseconds).WaitResult<SendResult>(timeoutMilliseconds + 1000);
     if (sendResult == null)
     {
         sendResult = new SendResult(SendStatus.Timeout, string.Format("Send message timeout, message: {0}, routingKey: {1}, timeoutMilliseconds: {2}", message, routingKey, timeoutMilliseconds));
     }
     return sendResult;
 }
Beispiel #3
0
 public SendResponse(INoticeMessage message, string sender, SendResult result)
 {
     NoticeMessage = message;
     SenderName = sender;
     Result = result;
     if (message != null)
     {
         Recipient = message.Recipient;
         NotifyAction = message.Action;
     }
 }
Beispiel #4
0
		private async Task<SendResult> Send(MaloneRestRequest request, CancellationToken token)
		{
			var result = new SendResult();

			var client = new RestClient(request.BaseUrl)
			{
				FollowRedirects = false
			};

			result.SentAt = DateTimeOffset.UtcNow;
			var response = await client.ExecuteTaskAsync(request, token);
			result.ReceivedAt = DateTimeOffset.UtcNow;
			result.Response = response;
			
			return result;
		}
Beispiel #5
0
 void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
     MailMessage mailMsg = (MailMessage)e.UserState;
     string subject = mailMsg.Subject;
     SendResult enumResult = new SendResult();
     if (e.Cancelled)
     {
         enumResult = SendResult.Cancled;
     }
     if (e.Error != null)
     {
         enumResult = SendResult.Error;
     }
     else
     {
         enumResult = SendResult.Success;
     }
     SendCompleted(sender, enumResult);
 }
Beispiel #6
0
        /// <summary>
        /// 发送全部用户
        /// </summary>
        /// <param name="account"></param>
        /// <param name="args"></param>
        /// <param name="yilidb"></param>
        /// <returns></returns>
        private async Task <SendResult> SendAllByGroup(MpAccountDto account, MpMessageDto args, IDBHelper yilidb)
        {
            SendResult result = null;

            if (args.MessageType == MpMessageType.text.ToString())
            {
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.Content, GroupMessageType.text, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }
            else if (args.MessageType == MpMessageType.video.ToString())
            {
                var videoId = int.Parse(args.VideoID.ToString());
                var video   = yilidb.FindOne <MpMediaVideo>("SELECT TOP 1 * FROM MpMediaVideos WHERE ID=" + videoId, null, false);
                if (video == null)
                {
                    throw new Exception(string.Format("视频{0}不存在", args.VideoName));
                }
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.VideoMediaID, GroupMessageType.video, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }
            else if (args.MessageType == MpMessageType.voice.ToString())
            {
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.VoiceMediaID, GroupMessageType.voice, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }
            else if (args.MessageType == MpMessageType.image.ToString())
            {
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ImageMediaID, GroupMessageType.image, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }
            else if (args.MessageType == MpMessageType.mpnews.ToString())
            {
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ArticleMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }
            else if (args.MessageType == MpMessageType.mpmultinews.ToString())
            {
                try
                {
                    result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken)).access_token, "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}");
                }
                catch
                {
                    try
                    {
                        result = GroupMessageApi.SendGroupMessageByGroupId((await StaticObjects.GetAccessToken(account.TaskAccessToken, 1)).access_token, "", args.ArticleGroupMediaID, GroupMessageType.mpnews, true, clientmsgid: $"MpMessage{args.Id}");
                    }
                    catch
                    {
                    }
                }
            }

            return(result);
        }
        private static BrowserWindow <BrowseType> createInputBox(Browser browser, bool modal, SendResult <BrowseType> sendResult)
        {
            BrowserWindow <BrowseType> inputBox = new BrowserWindow <BrowseType>(browser.Prompt);

            inputBox.setBrowser(browser);
            inputBox.SendResult = sendResult;
            inputBox.Closing   += new EventHandler <DialogCancelEventArgs>(inputBox_Closing);
            inputBox.Closed    += new EventHandler(inputBox_Closed);
            inputBox.center();
            inputBox.open(modal);
            return(inputBox);
        }
Beispiel #8
0
        /// <summary>
        /// Connect to a mailbox.
        /// </summary>
        /// <param name="accountSettingsData">The account settings data.</param>
        /// <param name="isLastAccountSettingsData">true, if is last account settings data; otherwise, false.</param>
        /// <param name="configurationNumber">The configuration number.</param>
        /// <param name="configurationCount">The configuration count.</param>
        /// <returns>true, if connected successfully; otherwise, false.</returns>
        private async Task <bool> Connect(AccountSettingsData accountSettingsData, bool isLastAccountSettingsData, int configurationNumber, int configurationCount)
        {
            try
            {
                // Get the mail client
                MailClient mailClient = await MailClient.GetMailClient(accountSettingsData);

                // Resolve the mail server names
                if (isReceiveConnected || await ResolveDNS(accountSettingsData.IncomingMailServer))
                {
                    // The authentication result
                    AuthenticationResult authenticationResult = new AuthenticationResult();
                    // If login is successfull
                    if (isReceiveConnected || (authenticationResult = mailClient.Login(true)).IsSuccessfull)
                    {
                        App.RunOnUIThread(dispatcher, () => App.NotifyUser(txtSubTitle, string.Format("Found your account... Trying configuration {0} of {1} for sending emails...", configurationNumber, configurationCount), NotifyType.StatusMessage));
                        // Send email
                        isReceiveConnected = true;
                        SendResult sendResult = null;
                        if (await ResolveDNS(accountSettingsData.OutgoingMailServer) &&
                            (sendResult = await mailClient.SendTestEmail()).IsSuccessful)
                        {
                            // Receive email
                            isLoginFailure = false;

                            // Save settings
                            App.RunOnUIThread(dispatcher, () => App.NotifyUser(txtSubTitle, "Added your account. Starting email sync...", NotifyType.StatusMessage));
                            StorageSettings.AccountSettingsDataDictionary.Add(accountSettingsData.EmailAddress, accountSettingsData);
                            await StorageSettings.SaveAccountSettingsDataDictionary();

                            MainPage.Current.ConnectMailbox(accountSettingsData, mailClient);
                            Task.Run(async() => await mailClient.DownloadUnreadMessages());
                            return(true);
                        }
                        else if (isLastAccountSettingsData)
                        {
                            isLoginFailure = true;
                            message        = string.Format("Outgoing server login failed.{0}Response from {1}: {2}", Environment.NewLine, (accountSettingsData.EmailServiceProvider == EmailServiceProvider.Other ? accountSettingsData.AccountName : accountSettingsData.EmailServiceProvider.ToString()), sendResult.LastResponse.GeneralMessage);
                            return(false);
                        }
                        else
                        {
                            isLoginFailure = false;
                            return(false);
                        }
                    }

                    // Login failed
                    isLoginFailure = mailClient.State == MailClientState.Connected;
                    message        = "Login failed. " + authenticationResult.Response;
                    return(false);
                }
                else if (isLastAccountSettingsData)
                {
                    isLoginFailure = true;
                    message        = "Your email account could not be found. Try configuring your account manually.";
                    return(false);
                }
                else
                {
                    isLoginFailure = false;
                    return(false);
                }
            }
            catch (Exception ex)
            {
                // Login failed
                LogFile.Instance.LogError("", "", ex.ToString());
                message = "Failed to add account. An error occurred while trying to add your account. Please try again.";
                return(false);
            }
        }
Beispiel #9
0
        public async Task <IActionResult> Index()
        {
            //senders number
            string[] sender = { "10008663", "10008663", "10008663", "10008663", "10008663" };

            //receptors numbers
            string[] receptor = { "09112345678", "09112345678", "", "09112345678", "09012345678" };

            //list of messages
            string[] message = { "تست وب سرویس کاوه نگار", "تست وب سرویس کاوه نگار", "تست وب سرویس کاوه نگار", "تست وب سرویس کاوه نگار", "تست وب سرویس کاوه نگار" };

            //localids that exist in local database
            string[] localIDs = { new Random().Next(0,      2454).ToString(), new Random().Next(0,   12544).ToString(),
                                  new Random().Next(0,     45645).ToString(), new Random().Next(0, 2000000).ToString(),
                                  new Random().Next(0, 123123456).ToString(), };

            //Your Api Key in kavenegar
            KavenegarApi kavenegar = new KavenegarApi("Your Api Key");

            SendResult        result     = null;
            List <SendResult> resultList = null;

            StatusResult        statusResult     = null;
            List <StatusResult> statusResultList = null;

            StatusLocalMessageIdResult        StatusLocalMessageIdResultResult     = null;
            List <StatusLocalMessageIdResult> StatusLocalMessageIdResultResultList = null;

            CountInboxResult CountInboxResult = null;


            #region SelectAsync
            result     = kavenegar.Select("274037533");
            resultList = kavenegar.Select(new List <string>()
            {
                "1775698101", "1775696560"
            });
            #endregion

            #region SelectOutboxAsync
            resultList = kavenegar.SelectOutbox(DateTime.Now.AddDays(-1), DateTime.Now);
            resultList = kavenegar.SelectOutbox(DateTime.Now.AddDays(-2));
            #endregion

            #region SendByPostalCodeAsync
            resultList = kavenegar.SendByPostalCode(4451865169, sender[0], "slama", 0, 10, 0, 16);
            resultList = kavenegar.SendByPostalCode(4451865169, sender[0], "slama", 0, 10, 0, 16, DateTime.Now);
            #endregion

            #region StatusAsync
            statusResult     = kavenegar.Status("1775698101");
            statusResultList = kavenegar.Status(new List <string>()
            {
                "1775698101", "1775696560"
            });
            #endregion

            #region StatusLocalMessageIdAsync
            StatusLocalMessageIdResultResult     = kavenegar.StatusLocalMessageId(localIDs[0]);
            StatusLocalMessageIdResultResultList = kavenegar.StatusLocalMessageId(localIDs.ToList());
            #endregion

            #region CancelAsync
            statusResult     = kavenegar.Cancel("1775698101");
            statusResultList = kavenegar.Cancel(new List <string>()
            {
                "1775698101", "1775696560"
            });
            #endregion

            #region CountInboxAsync
            CountInboxResult = kavenegar.CountInbox(DateTime.Now.AddDays(-1), sender[0]);
            CountInboxResult = kavenegar.CountInbox(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), sender[0]);
            #endregion

            #region CountOutboxAsync
            CountInboxResult = kavenegar.CountOutbox(DateTime.Now.AddDays(-1));
            CountInboxResult = kavenegar.CountOutbox(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1));
            #endregion

            #region CountPostalCodeAsync
            List <CountPostalCodeResult> countPostalCodeResult = kavenegar.CountPostalCode(4451865169);
            #endregion

            #region LatestOutboxAsync
            resultList = kavenegar.LatestOutbox(1);
            resultList = kavenegar.LatestOutbox(1, sender[0]);
            #endregion

            #region LatestOutboxAsync
            List <ReceiveResult> receiveResult = kavenegar.Receive(sender[0], 0);
            List <ReceiveResult> ReceiveResult = kavenegar.Receive(sender[0], 1);
            #endregion

            #region sendAsync
            result = kavenegar.Send(sender[0], receptor[0], message[0]);
            result = kavenegar.Send(sender[0], receptor[0], message[0], localIDs[0].ToString());
            #endregion

            #region sendArrayAsync
            resultList = kavenegar.SendArray(sender.ToList(), receptor.ToList(), message.ToList(), localIDs[0]);
            resultList = kavenegar.SendArray(sender[0], receptor.ToList(), message.ToList(), localIDs[0]);
            #endregion

            #region VerifyLookupAsync

            //verify is template neme, you can create template from here https://panel.kavenegar.com/Client/Verification/Create
            result = kavenegar.VerifyLookup(receptor[0], "123", "verify");

            //rate is template neme, you can create template from here https://panel.kavenegar.com/Client/Verification/Create
            result = kavenegar.VerifyLookup(receptor[0], "123", null, null, null, "token20", "rate", VerifyLookupType.Sms);
            #endregion

            return(View());
        }
Beispiel #10
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            WebSMS wsm = new WebSMS();

            g_uid                = SiteConfig.SiteOption.G_uid;
            g_eid                = SiteConfig.SiteOption.G_eid;
            g_pwd                = SiteConfig.SiteOption.G_pwd;
            g_gate_id            = SiteConfig.SiteOption.G_gate_id;
            this.x_uid.Value     = g_uid.ToString();
            this.x_eid.Value     = g_eid.ToString();
            this.x_pwd_md5.Value = g_pwd.ToString();
            this.h_gate_id.Value = g_gate_id.ToString();
            if (wsm == null)
            {
                function.WriteErrMsg("网关初始化失败!");
                return;
            }
            string strIdentity = wsm.GetIdentityMark(Int32.Parse(g_eid), g_uid, g_pwd, Int32.Parse(g_gate_id));

            if (strIdentity == null || strIdentity == "")
            {
                function.WriteErrMsg("获取标识串失败!");
                return;
            }
            if (this.t_sendNo.Text.ToString().Trim() == "" || this.t_sendMemo.Text.ToString().Trim() == "")
            {
                function.WriteErrMsg("接收号码或者短信内容没有输入!");
                return;
            }
            if (this.t_sendTime.Text.ToString().Trim() != "")
            {
                DateTime dt;
                if (!DateTime.TryParse(this.t_sendTime.Text.ToString().Trim(), out dt))
                {
                    function.WriteErrMsg("定时格式错误!");
                    return;
                }
                if (dt <= DateTime.Now)
                {
                    function.WriteErrMsg("定时时间必须大于当前时间!");
                    return;
                }
            }
            //快速发送.直接提交到运营商网关
            SendResult status = wsm.FastSend(strIdentity, this.t_sendNo.Text.ToString().Trim(), this.t_sendMemo.Text.ToString().Trim(), this.t_sendTime.Text.ToString().Trim(), "");
            //发送成功
            string js = "";

            if (status.RetCode > 0)
            {
                js = "发送成功,共发送:" + status.RetCode.ToString() + "条";
                this.Label1.Text = "当前余额:" + wsm.GetMoney(strIdentity).ToString("0.00");
            }
            else //发送失败
            {
                js = "发送失败,错误代码:" + status.RetCode.ToString() + ",原因:" + status.ErrorDesc;
            }
            js = js.Replace("\"", "\\\"");
            js = js.Replace("\'", "\\\'");
            // Response.Write("<script>alert('" + js + "');window.location='MessageInfo.aspx';</script>");
        }
        public static void GetInput(NativeOSWindow parent, Browser browser, bool modal, SendResult <BrowseType> sendResult, Action <String, Action <String> > importCallback, String prompt, String wildcard, String extension)
        {
            BrowserWindow <BrowseType> inputBox = createInputBox(browser, modal, sendResult);

            inputBox.importButton.MouseButtonClick += (source, e) =>
            {
                FileOpenDialog openDialog = new FileOpenDialog(parent, prompt, wildcard: wildcard);
                openDialog.showModal((result, paths) =>
                {
                    if (result == NativeDialogResult.OK)
                    {
                        String path = paths.First();
                        String ext  = Path.GetExtension(path);
                        if (ext.Equals(extension, StringComparison.OrdinalIgnoreCase))
                        {
                            importCallback(path, previewPath =>
                            {
                                ThreadManager.invoke(new Action(() =>
                                {
                                    BrowserNode node = new BrowserNode(Path.GetFileName(previewPath), previewPath);
                                    inputBox.browserTree.Nodes.First().Children.add(inputBox.addNodes(node, node));
                                    inputBox.browserTree.layout();
                                }));
                            });
                        }
                        else
                        {
                            MessageBox.show(String.Format("Cannot open a file with extension '{0}'.", extension), "Can't Load File", MessageBoxStyle.IconWarning | MessageBoxStyle.Ok);
                        }
                    }
                });
            };
        }
Beispiel #12
0
 public SendResultEventArgs(string tagName, EmitterPackageData data,
                            SendResult result, Exception ex)
     : this(tagName, data, result, ex == null ? "" : ex.Message)
 {
 }
Beispiel #13
0
 public void onSuccess(SendResult sr)
 {
     SendSuccessHandler?.Invoke(_producer, new SendSuccessArgs {
         Result = sr
     });
 }
Beispiel #14
0
        public async void SendFile()
        {
            try
            {
                SendResult returnSendResult   = SendResult.CannotSend;
                string     returnMessage      = string.Empty;
                string     returnMessageTitle = string.Empty;

                if (!await Connect())
                {
                    returnSendResult   = SendResult.CannotSend;
                    returnMessage      = Translator.GetStringFromResource(MessageCodes.SenderConnectError.ToString());
                    returnMessageTitle = Translator.GetStringFromResource(MessageCodes.SenderConnectErrorTitle.ToString());

                    SendingFileFinished(returnSendResult, returnMessage, returnMessageTitle);
                    return;
                }

                byteToSend = GetPacketToSend();
                byte[] buff = new byte[SEND_BUFFER];

                long noOfPack = (byteToSend.Length % SEND_BUFFER == 0) ?
                                byteToSend.Length / SEND_BUFFER :
                                ((byteToSend.Length - (byteToSend.Length % SEND_BUFFER)) / SEND_BUFFER) + 1;

                SendingFileStarted();

                await Task.Run(async() =>
                {
                    if (NetworkStream != null)
                    {
                        int loopStep = 0;
                        while (noOfPack > 0)
                        {
                            if (!NetworkStream.CanWrite)
                            {
                                returnSendResult   = SendResult.CannotSend;
                                returnMessage      = Translator.GetStringFromResource(MessageCodes.SenderCouldntWriteToStream.ToString());
                                returnMessageTitle = Translator.GetStringFromResource(MessageCodes.SenderCouldntWriteToStreamTitle.ToString());

                                return;
                            }
                            if (IsCancelled)
                            {
                                returnSendResult   = SendResult.Cancelled;
                                returnMessage      = Translator.GetStringFromResource(MessageCodes.SenderCancelledByUser.ToString());
                                returnMessageTitle = Translator.GetStringFromResource(MessageCodes.SenderCancelledByUserTitle.ToString());

                                return;
                            }

                            if (noOfPack > 1) //Son paket değilse
                            {
                                Array.Copy(byteToSend, loopStep *SEND_BUFFER, buff, 0, SEND_BUFFER);
                            }
                            else //Son paket ise
                            {
                                Array.Copy(byteToSend, loopStep *SEND_BUFFER, buff, 0, byteToSend.Length % SEND_BUFFER);
                            }

                            await NetworkStream.WriteAsync(buff, 0, buff.Length);

                            totalSent += buff.Length;

                            --noOfPack;
                            ++loopStep;
                        }
                        returnSendResult   = SendResult.Completed;
                        returnMessage      = Translator.GetStringFromResource(MessageCodes.SenderCompleted.ToString());
                        returnMessageTitle = Translator.GetStringFromResource(MessageCodes.SenderCompletedTitle.ToString());

                        return;
                    }
                    else
                    {
                        returnSendResult   = SendResult.CannotSend;
                        returnMessage      = Translator.GetStringFromResource(MessageCodes.SenderException.ToString());
                        returnMessageTitle = Translator.GetStringFromResource(MessageCodes.SenderExceptionTitle.ToString());
                    }
                });

                SendingFileFinished(returnSendResult, returnMessage, returnMessageTitle);
            }
            catch (ArgumentNullException)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderArgumentNullException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderArgumentNullExceptionTitle.ToString()));
            }
            catch (ArgumentException)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderArgumentException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderArgumentExceptionTitle.ToString()));
            }
            catch (PathTooLongException)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderPathTooLongException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderPathTooLongExceptionTitle.ToString()));
            }
            catch (DirectoryNotFoundException)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderDirectoryNotFoundException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderDirectoryNotFoundExceptionTitle.ToString()));
            }
            catch (IOException ex)
            {
                var errcode = ex.InnerException as Win32Exception;

                if (errcode != null && errcode.ErrorCode == 10054)
                {
                    SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderIOExceptionError10054.ToString()), Translator.GetStringFromResource(MessageCodes.SenderIOExceptionError10054Title.ToString()));
                }
                else
                {
                    SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderIOException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderIOExceptionTitle.ToString()));
                }
            }
            catch (UnauthorizedAccessException)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderUnauthorizedAccessException.ToString()), Translator.GetStringFromResource(MessageCodes.SenderUnauthorizedAccessExceptionTitle.ToString()));
            }
            catch (Exception exception)
            {
                SendingFileFinished(SendResult.CannotSend, Translator.GetStringFromResource(MessageCodes.SenderException.ToString(), exception.Message), Translator.GetStringFromResource(MessageCodes.SenderExceptionTitle.ToString()));
            }
            finally
            {
                Dispose();
            }
        }
Beispiel #15
0
 public SendResultEventArgs(string tagName, EmitterPackageData data,
                            SendResult result, string message) : this(tagName, data.Tos, data.Subject,
                                                                      data.PackageId, data.Body, data.BodyEncoding,
                                                                      data.SubjectEncoding, data.IsBodyHtml, data.AttachmentPath, result, message)
 {
 }
Beispiel #16
0
    public SendResult SendToServ <T>(T data) where T : HttpData
    {
        SendResult res = new SendResult();

        return(res);
    }
Beispiel #17
0
 public Task<SendResult> SendAsync(Message message, object arg)
 {
     var queueCount = GetTopicQueueCount(message.Topic);
     if (queueCount == 0)
     {
         throw new Exception(string.Format("No available queue for topic [{0}].", message.Topic));
     }
     var queueId = _queueSelector.SelectQueueId(queueCount, message, arg);
     var remotingRequest = BuildSendMessageRequest(message, queueId);
     var taskCompletionSource = new TaskCompletionSource<SendResult>();
     _remotingClient.InvokeAsync(remotingRequest, Setting.SendMessageTimeoutMilliseconds).ContinueWith((requestTask) =>
     {
         var remotingResponse = requestTask.Result;
         if (remotingResponse != null)
         {
             var response = _binarySerializer.Deserialize<SendMessageResponse>(remotingResponse.Body);
             var sendStatus = SendStatus.Success; //TODO, figure from remotingResponse.Code;
             var result = new SendResult(sendStatus, response.MessageOffset, response.MessageQueue, response.QueueOffset);
             taskCompletionSource.SetResult(result);
         }
         else
         {
             var result = new SendResult(SendStatus.Failed, "Send message request failed or wait for response timeout.");
             taskCompletionSource.SetResult(result);
         }
     });
     return taskCompletionSource.Task;
 }
        /// <summary>
        /// Start sending <see cref="NotifyMessage"/>
        /// to the consuming business application
        /// </summary>
        /// <param name="messagingContext"></param>
        /// <returns></returns>
        public async Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            if (messagingContext == null)
            {
                throw new ArgumentNullException(nameof(messagingContext));
            }

            if (messagingContext.NotifyMessage == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(SendNotifyMessageStep)} requires a NotifyMessage to send but no NotifyMessage is present in the MessagingContext");
            }

            if (messagingContext.NotifyMessage.StatusCode == Status.Delivered &&
                messagingContext.SendingPMode == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(SendNotifyMessageStep)} requires a SendingPMode when the NotifyMessage is a Receipt that must be notified, "
                          + "this is indicated by the NotifyMessage.StatusCode = Delivered");
            }

            if (messagingContext.NotifyMessage.StatusCode == Status.Error &&
                messagingContext.SendingPMode == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(SendNotifyMessageStep)} requires a SendingPMode when the NotifyMessage is an Error that must be notified, "
                          + "this is indicated by the NotifyMessage.StatusCode = Error");
            }

            if (messagingContext.NotifyMessage.StatusCode == Status.Exception &&
                messagingContext.SendingPMode == null &&
                messagingContext.ReceivingPMode == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(SendNotifyMessageStep)} requires either a SendingPMode ore ReceivingPMode when the NotifyMessage is an Exception that must be notified, "
                          + "this is indicated by teh NotifyMessage.StatusCode = Exception");
            }

            Method notifyMethod = GetNotifyMethodBasedOnNotifyMessage(
                messagingContext.NotifyMessage,
                messagingContext.SendingPMode,
                messagingContext.ReceivingPMode);

            if (messagingContext.SendingPMode == null)
            {
                SendingProcessingMode pmode =
                    RetrieveSendingPModeForMessageWithEbmsMessageId(
                        messagingContext.NotifyMessage
                        .MessageInfo
                        ?.RefToMessageId);

                if (pmode != null)
                {
                    Logger.Debug(
                        $"Using SendingPMode {pmode.Id} based on the NotifyMessage.MessageInfo.RefToMessageId "
                        + $"{messagingContext.NotifyMessage.MessageInfo?.RefToMessageId} from the matching stored OutMessage");

                    messagingContext.SendingPMode = pmode;
                }
            }

            Logger.Trace("Start sending NotifyMessage...");
            SendResult result = await SendNotifyMessageAsync(notifyMethod, messagingContext.NotifyMessage).ConfigureAwait(false);

            Logger.Trace($"NotifyMessage sent result in: {result}");

            await UpdateDatastoreAsync(
                messagingContext.NotifyMessage,
                messagingContext.MessageEntityId,
                result);

            return(StepResult.Success(messagingContext));
        }
        public async Task SendWebHook_StopsOnLastLastFailureOrFirstSuccessAndFirstGone(TimeSpan[] delays, Func<HttpRequestMessage, int, Task<HttpResponseMessage>> handler, int expectedOffset, SendResult expectedResult)
        {
            // Arrange
            SendResult actualResult = SendResult.None;
            ManualResetEvent done = new ManualResetEvent(initialState: false);
            WebHookWorkItem final = null;
            int actualRetries = 0;
            _sender = new TestDataflowWebHookSender(_loggerMock.Object, delays, _options, _httpClient,
            onWebHookRetry: item =>
            {
                actualRetries++;
            },
            onWebHookSuccess: item =>
            {
                final = item;
                actualResult = SendResult.Success;
                done.Set();
            },
            onWebHookGone: item =>
            {
                final = item;
                actualResult = SendResult.Gone;
                done.Set();
            },
            onWebHookFailure: item =>
            {
                final = item;
                actualResult = SendResult.Failure;
                done.Set();
            });
            _handlerMock.Handler = handler;
            NotificationDictionary notification = new NotificationDictionary("a1", data: null);
            WebHook webHook = WebHookManagerTests.CreateWebHook();
            WebHookWorkItem workItem = new WebHookWorkItem(webHook, new[] { notification })
            {
                Id = "1234567890",
            };

            // Act
            await _sender.SendWebHookWorkItemsAsync(new[] { workItem });
            done.WaitOne();

            // Assert
            int expectedRetries = expectedResult == SendResult.Failure ? Math.Max(0, expectedOffset - 1) : expectedOffset;
            Assert.Equal(expectedRetries, actualRetries);
            Assert.Equal(expectedResult, actualResult);
            Assert.Equal(expectedOffset, final.Offset);
        }
Beispiel #20
0
        // Background reading
        private void ThreadWork()
        {
            while (run)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["address"].Value != null && row.Cells["IsValid"].Value.ToString() == "1")
                    {
                        // Read row
                        string idrow  = row.Cells["idrow"].Value.ToString();
                        string addr   = row.Cells["address"].Value.ToString();
                        string format = row.Cells["format"].Value.ToString();

                        string GraphName = addr;

                        // Raw byte from PLC
                        byte[] resbyte = _plc.GetValue(addr);
                        // Formated user output
                        string resvalue = "";
                        // Read in format
                        switch (format.ToUpper())
                        {
                        case "BOOL":
                            resvalue = _plc.GetBooltS(resbyte);
                            break;

                        case "DEC":
                            resvalue = _plc.GetDecS(resbyte);
                            break;

                        case "BIN":
                            resvalue = _plc.GetBinS(resbyte);
                            break;

                        case "FLOAT":
                            resvalue = _plc.GetFloatS(resbyte);
                            break;

                        case "CHAR":
                            resvalue = _plc.GetCharS(resbyte);
                            break;

                        default:
                            resvalue = "Data type error";
                            break;
                        }

                        // Update datagridview
                        SendResult dResult = new SendResult(ShowResult);
                        this.Invoke(dResult, idrow, resvalue);
                        if (Convert.ToBoolean(row.Cells["check"].Value))
                        {
                            // Insert into chart
                            if (format.ToUpper() != "BIN" & format.ToUpper() != "CHAR")
                            {
                                PlotResult dPlot = new PlotResult(InsertPlotPoint);
                                this.Invoke(dPlot, GraphName, resvalue, format.ToUpper());
                            }
                        }
                    }
                }
                Thread.Sleep(100);
                // Update chart
                UpdateChart dupdate = new UpdateChart(UpdateChartPoints);
                this.Invoke(dupdate);
            }
        }
        public async Task <int> ReceiveAsync(byte[] buffer, int offset, int count)
        {
            // This is a little tricky, so let's spell it out in comments...
            if (Disposed)
            {
                throw new OperationCanceledException();
            }

            // If this is the first time ReceiveAsync is invoked, then we should get the first PieceMessage from the queue
            if (CurrentRequest == null)
            {
                // When we call 'SendAsync' with request piece messages, we add them to the list and then toggle the handle.
                // When this returns it means we have requests ready to go!
                await Task.Run(() => ReceiveWaiter.WaitOne());

                if (Disposed)
                {
                    throw new OperationCanceledException();
                }

                // Grab the request. We know the 'SendAsync' call won't return until we process all the queued requests, so
                // this is threadsafe now.
                CurrentRequest = new HttpRequestData(RequestMessages[0]);
                RequestMessages.RemoveAt(0);
            }

            // If we have not sent the length header for this message, send it now
            if (!CurrentRequest.SentLength)
            {
                // The message length counts as the first four bytes
                CurrentRequest.SentLength     = true;
                CurrentRequest.TotalReceived += 4;
                Message.Write(buffer, offset, CurrentRequest.TotalToReceive - CurrentRequest.TotalReceived);
                return(4);
            }

            // Once we've sent the length header, the next thing we need to send is the metadata for the 'Piece' message
            int written = 0;

            if (!CurrentRequest.SentHeader)
            {
                CurrentRequest.SentHeader = true;

                // We have *only* written the messageLength to the stream
                // Now we need to write the rest of the PieceMessage header
                written += Message.Write(buffer, offset + written, PieceMessage.MessageId);
                written += Message.Write(buffer, offset + written, CurrentRequest.Request.PieceIndex);
                written += Message.Write(buffer, offset + written, CurrentRequest.Request.StartOffset);
                count   -= written;
                offset  += written;
                CurrentRequest.TotalReceived += written;
            }

            // Once we have sent the message length, and the metadata, we now need to add the actual data from the HTTP server.
            // If we have already connected to the server then DataStream will be non-null and we can just read the next bunch
            // of data from it.
            if (DataStream != null)
            {
                var result = await DataStream.ReadAsync(buffer, offset, count);

                DataStreamCount -= result;
                // If result is zero it means we've read the last data from the stream.
                if (result == 0)
                {
                    using (DataStreamResponse)
                        DataStream.Dispose();

                    DataStreamResponse = null;
                    DataStream         = null;

                    // If we requested more data (via the range header) than we were actually given, then it's a truncated
                    // stream and we can give up immediately.
                    if (DataStreamCount > 0)
                    {
                        throw new WebException("Unexpected end of stream");
                    }
                }
                else
                {
                    // Otherwise if we have received non-zero data we can accumulate that!
                    CurrentRequest.TotalReceived += result;
                    // If the request is complete we should dequeue the next RequestMessage so we can process
                    // that the next ReceiveAsync is invoked. Otherwise, if we have processed all the queued
                    // messages we can mark the 'SendAsync' as complete and we can wait for the piece picker
                    // to add more requests for us to process.
                    if (CurrentRequest.Complete)
                    {
                        if (RequestMessages.Count > 0)
                        {
                            CurrentRequest = new HttpRequestData(RequestMessages[0]);
                            RequestMessages.RemoveAt(0);
                        }
                        else
                        {
                            using (DataStreamResponse)
                                DataStream.Dispose();

                            DataStreamResponse = null;
                            DataStream         = null;

                            CurrentRequest = null;

                            SendResult.TrySetResult(null);
                        }
                    }
                    return(result + written);
                }
            }

            // Finally, if we have had no datastream what we need to do is execute the next web request in our list,
            // and then begin reading data from that stream.
            while (WebRequests.Count > 0)
            {
                var r = WebRequests.Dequeue();
                using (var cts = new CancellationTokenSource(ConnectionTimeout))
                    using (cts.Token.Register(() => r.Key.Abort())) {
                        DataStreamResponse = await r.Key.GetResponseAsync();

                        DataStream      = DataStreamResponse.GetResponseStream();
                        DataStreamCount = r.Value;
                        return(await ReceiveAsync(buffer, offset, count) + written);
                    }
            }

            // If we reach this point it means that we processed all webrequests and still ended up receiving *less* data than we required,
            // and we did not throw an unexpected end of stream exception.
            throw new WebException("Unable to download the required data from the server");
        }
 internal NotifyResult(SendResult result, List <SendResponse> responses)
 {
     Result    = result;
     Responses = responses ?? new List <SendResponse>();
 }
 private bool CheckStatus(SendResult Result)
 {
     try
     {
         if (Result.Status == 5)
         {
             return(true);
         }
         else
         {
             if (Result.Status == 401)
             {
                 throw new Exception("حساب کاربری غیرفعال شده است");
             }
             else if (Result.Status == 402)
             {
                 throw new Exception("عملیات ناموفق بود");
             }
             else if (Result.Status == 403)
             {
                 throw new Exception("کد شناسائی API-Key معتبر نمی‌باشد");
             }
             else if (Result.Status == 406)
             {
                 throw new Exception("پارامترهای اجباری خالی ارسال شده اند");
             }
             else if (Result.Status == 407)
             {
                 throw new Exception("دسترسی به اطلاعات مورد نظر برای شما امکان پذیر نیست. برای استفاده از متدهای Select، SelectOutbox و LatestOutBox و یا ارسال با خط بین المللی نیاز به تنظیم IP در بخش تنظیمات امنیتی می باشد");
             }
             else if (Result.Status == 409)
             {
                 throw new Exception("سرور قادر به پاسخگوئی نیست بعدا تلاش کنید");
             }
             else if (Result.Status == 411)
             {
                 throw new Exception($"دریافت کننده نامعتبر است, [{Result.Receptor}]");
             }
             else if (Result.Status == 412)
             {
                 throw new Exception($"ارسال کننده نامعتبر است, [{_sender}]");
             }
             else if (Result.Status == 414)
             {
                 throw new Exception("حجم درخواست بیشتر از حد مجاز است ،ارسال پیامک :هر فراخوانی حداکثر 200 رکوردو کنترل وضعیت :هر فراخوانی 500 رکورد");
             }
             else if (Result.Status == 415)
             {
                 throw new Exception("اندیس شروع بزرگ تر از کل تعداد شماره های مورد نظر است");
             }
             else if (Result.Status == 416)
             {
                 throw new Exception("IP سرویس مبدا با تنظیمات مطابقت ندارد");
             }
             else if (Result.Status == 417)
             {
                 throw new Exception("تاریخ ارسال اشتباه است و فرمت آن صحیح نمی باشد.");
             }
             else if (Result.Status == 418)
             {
                 throw new Exception("اعتبار شما کافی نمی‌باشد");
             }
             else if (Result.Status == 420)
             {
                 throw new Exception("استفاده از لینک در متن پیام برای شما محدود شده است");
             }
             else if (Result.Status == 422)
             {
                 throw new Exception("داده ها به دلیل وجود کاراکتر نامناسب قابل پردازش نیست");
             }
             else if (Result.Status == 424)
             {
                 throw new Exception("الگوی مورد نظر پیدا نشد");
             }
             else if (Result.Status == 426)
             {
                 throw new Exception("استفاده از این متد نیازمند سرویس پیشرفته می‌باشد");
             }
             else if (Result.Status == 427)
             {
                 throw new Exception("استفاده از این خط نیازمند ایجاد سطح دسترسی می باشد");
             }
             else if (Result.Status == 428)
             {
                 throw new Exception("ارسال کد از طریق تماس تلفنی امکان پذیر نیست");
             }
             else if (Result.Status == 429)
             {
                 throw new Exception("IP محدود شده است");
             }
             else if (Result.Status == 432)
             {
                 throw new Exception("پارامتر کد در متن پیام پیدا نشد");
             }
             else if (Result.Status == 451)
             {
                 throw new Exception("فراخوانی بیش از حد در بازه زمانی مشخص IP محدود شده");
             }
             else if (Result.Status == 501)
             {
                 throw new Exception("فقط امکان ارسال پیام تست به شماره صاحب حساب کاربری وجود دارد");
             }
             else
             {
                 throw new Exception("Unknown error");
             }
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         return(false);
     }
 }
Beispiel #24
0
        public SendResult SendPasswordResetMessage()
        {
            SendResult result = GetSendResult();

            return(result);
        }
        public SendResult SendPlatformTicket(int month, int day, CustomersInfo customer, Pay pay)
        {
            DateTime now = DateTime.Now;

            switch (PluginHost.SendType)
            {
            case SendTypes.Inquire:
                if (customer.Total > 5)
                {
                    return(SendResult.Rethink("要求人数超過"));
                }
                else
                {
                    return(SendResult.Yes("", "", false));
                }

            case SendTypes.Sell:
            case SendTypes.Reserve:
                if (customer.Total > 5)
                {
                    return(SendResult.Rethink("要求人数超過"));
                }
                else
                {
                    bool isFirstReservation = false;
                    if (!PluginHost.IsOneTimeMode && PluginHost.SendType == SendTypes.Reserve)
                    {
                        PluginHost.IsOneTimeMode = true;
                        isFirstReservation       = true;
                    }

                    Func <int, int, List <TicketBase> > createTicketsFunc = (issueNumber, countStartNumber) =>
                    {
                        NativeEventTicket ticket = new NativeEventTicket(new IssueInformation()
                        {
                            TerminalName = StationName + TerminalName, Number = CompanyNumber
                        }, new EventTicketInformation()
                        {
                            Title               = "普通入場券",
                            Product             = StationName,
                            Description         = "旅客車内に立ち入ることはできません。",
                            Amount_Adult        = 140,
                            Amount_Child        = 70,
                            ValidType           = TicketValidTypes.Once,
                            UseDate             = new DateTime(now.Year, month, day),
                            Persons_Adult       = customer.Adult + customer.Student,
                            Persons_Child       = customer.Child + customer.Preschooler,
                            IssuedDate          = now,
                            IssueNumber         = issueNumber,
                            CountBeginNumber    = countStartNumber,
                            IsWorkingOnInternet = true,
                            InfoTop             = PluginHost.IsTestMode ? AdditionalInformation_Top.Test : pay.PayType switch
                            {
                                PayType.Cash => AdditionalInformation_Top.None,
                                PayType.IC => AdditionalInformation_Top.IC,
                                _ => throw new ArgumentOutOfRangeException(),
                            },
                        }, PrintSetting);

                        return(ticket.ticketImages.Select((t, i) => (TicketBase) new PlatformTicket(ticket, i)).ToList());
                    };
        public static void GetInput(Browser browser, bool modal, SendResult <BrowseType> sendResult)
        {
            BrowserWindow <BrowseType> inputBox = createInputBox(browser, modal, sendResult);

            inputBox.importButton.Visible = false;
        }
Beispiel #27
0
        public JsonResult InviteRegister(int cityId, string info, string password, string from = "")
        {
            if (String.IsNullOrEmpty(info))
            {
                return(Json(new { status = -1, msg = "无效的参数" }));
            }
            UserModels userModels = new UserModels();

            info       = CryptoUtility.TripleDESDecrypt(info);
            userModels = JsonConvert.DeserializeObject <UserModels>(info);
            string tel = string.IsNullOrEmpty(userModels.Tel) ? "" : StringUtility.StripWhiteSpace(userModels.Tel.Replace("-", ""), false);

            if (tel.StartsWith("0"))
            {
                tel = tel.Substring(1);
            }
            userModels.Tel = tel;
            if (!StringUtility.ValidateMobile(userModels.Tel))
            {
                return(Json(new { status = -1, msg = "手机号码格式不正确" }));
            }
            PublicUser publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Tel == userModels.Tel).FirstOrDefault();

            if (publicUser.IsNoNull())
            {
                return(Json(new { status = -1, msg = "该手机号码已经注册过了" }));
            }
            publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Name == userModels.UserName).FirstOrDefault();
            string userName = userModels.UserName;

            if (publicUser.IsNoNull())
            {
                userModels.UserName = userModels.UserName + "_" + userModels.UserId + StringUtility.GetValiCode();
            }
            PublicUserModel user = new PublicUserModel();

            string  strCompany = string.IsNullOrEmpty(userModels.Company) ? userModels.Store : userModels.Company;
            string  strStore   = string.IsNullOrEmpty(userModels.Company) ? "" : userModels.Store;
            Company company    = ncBase.CurrentEntities.Company.Where(o => o.Name == strCompany && o.CityID == cityId).FirstOrDefault();

            if (company.IsNull())
            {
                company         = new Company();
                company.Name    = strCompany;
                company.Tel     = "";
                company.Address = "";
                company.CityID  = cityId;
                ncBase.CurrentEntities.AddToCompany(company);
                ncBase.CurrentEntities.SaveChanges();
            }


            CompanyStore companyStore = ncBase.CurrentEntities.CompanyStore.Where(o => o.StoreName == strStore && o.CompanyId == company.CompanyId).FirstOrDefault();

            if (!string.IsNullOrEmpty(strStore) && companyStore.IsNull())
            {
                companyStore           = new CompanyStore();
                companyStore.Address   = "";
                companyStore.CityID    = cityId;
                companyStore.CompanyId = company.CompanyId;
                companyStore.StoreName = strStore;
                companyStore.Tel       = "";
                ncBase.CurrentEntities.AddToCompanyStore(companyStore);
                ncBase.CurrentEntities.SaveChanges();
            }
            user.Tel         = userModels.Tel;
            user.Name        = userModels.UserName;
            user.Password    = password;
            user.CityID      = cityId;
            user.DistrictId  = 0;
            user.CompanyId   = company.CompanyId;
            user.StoreId     = companyStore.IsNoNull() ? companyStore.StoreId : 0;
            user.RegionId    = 0;
            user.VipType     = 2; //会员类型
            user.Portrait    = userModels.Portrait;
            user.Remarks     = !string.IsNullOrEmpty(from) ? "From:" + from : "";
            user.IP          = Request.UserHostAddress;
            user.LastLoginIP = Request.UserHostAddress;
            user.NickName    = userName;
            user.EnrolnName  = userName;

            #region 表单验证
            if (string.IsNullOrEmpty(user.Tel))
            {
                return(Json(new { status = 1, msg = "手机号不能为空" }));
            }

            if (string.IsNullOrEmpty(user.Name))
            {
                return(Json(new { status = 1, msg = "用户名不能为空" }));
            }
            if (string.IsNullOrEmpty(user.Password) || (user.Password != null && user.Password.Length < 6))
            {
                return(Json(new { status = 1, msg = "密码至少6位数" }));
            }
            if (user.CityID <= 0)
            {
                return(Json(new { status = 1, msg = "所属城市必填" }));
            }
            if (user.CompanyId <= 0)
            {
                return(Json(new { status = 1, msg = "所属公司必填" }));
            }

            #endregion

            UserBll userBll = new UserBll();
            int     userid  = userBll.addPublicUser(user);
            if (userid == -1)
            {
                return(Json(new { status = 1, msg = "用户名已经存在" }));
            }
            else if (userid == -2)
            {
                return(Json(new { status = 1, msg = "手机号已被注册" }));
            }
            if (userid > 0)//自动登录
            {
                try
                {
                    if (userModels.InviteUid.IsNoNull() && userModels.InviteUid > 0)
                    {
                        PublicUser publicUserInvite =
                            ncBase.CurrentEntities.PublicUser.Where(
                                o => o.UserID == userModels.InviteUid && o.Status == 1).FirstOrDefault();
                        if (publicUserInvite.IsNoNull())
                        {
                            int points = publicUserInvite.Points;
                            publicUserInvite.Points = points + 200;
                            ncBase.CurrentEntities.SaveChanges();

                            PublicUserPointsLog publicUserPointsLog = new PublicUserPointsLog();
                            publicUserPointsLog.Points        = 200;
                            publicUserPointsLog.UserId        = publicUserInvite.UserID;
                            publicUserPointsLog.AddTime       = DateTime.Now;
                            publicUserPointsLog.CurrentPoints = points + 200;
                            publicUserPointsLog.Description   = "手机用户" + user.Tel + "接受邀请注册加分";
                            ncBase.CurrentEntities.AddToPublicUserPointsLog(publicUserPointsLog);
                            ncBase.CurrentEntities.SaveChanges();
                            smsApi.SendSms(publicUserInvite.Tel, "手机用户" + user.Tel + "成功通过您的邀请链接注册房产盒子,系统赠送您200积分!", (Purpose)8, "【房产盒子】");
                        }
                    }
                    SendResult sendResult = smsApi.SendSms(user.Tel, "恭喜您成功开通房产盒子,帐号:" + user.Tel + " 密码:" + user.Password, (Purpose)8, "【房产盒子】");
                }
                catch (Exception)
                {
                    throw;
                }
                if (Session[user.Tel] != null)
                {
                    Session[user.Tel] = null;
                    Session.Remove(user.Tel);
                }
                PublicUserModel newUser = userBll.PublicUserLogin(user.Name, user.Password);
                String          saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];
                if (String.IsNullOrEmpty(saveKey))
                {
                    saveKey = "WXLoginedUser";
                }
                Session[saveKey] = newUser;
                HttpCookie loginUserCookie = new HttpCookie(saveKey, CryptoUtility.TripleDESEncrypt(newUser.UserID.ToString()));
                loginUserCookie.Expires = DateTime.Now.AddDays(10);
                HttpContext.Response.Cookies.Add(loginUserCookie);
            }
            return(Json(new { status = 0, msg = "注册成功" }));
        }
Beispiel #28
0
 public void Add(SendResult r)
 {
     _results[r]++;
 }
        public async Task SendWebHook_StopsOnLastLastFailureOrFirstSuccessAndFirstGone(TimeSpan[] delays, Func <HttpRequestMessage, int, Task <HttpResponseMessage> > handler, int expectedOffset, SendResult expectedResult)
        {
            // Arrange
            var             actualResult  = SendResult.None;
            var             done          = new ManualResetEvent(initialState: false);
            WebHookWorkItem final         = null;
            var             actualRetries = 0;

            _sender = new TestDataflowWebHookSender(_loggerMock.Object, delays, _options, _httpClient,
                                                    onWebHookRetry: item =>
            {
                actualRetries++;
            },
                                                    onWebHookSuccess: item =>
            {
                final        = item;
                actualResult = SendResult.Success;
                done.Set();
            },
                                                    onWebHookGone: item =>
            {
                final        = item;
                actualResult = SendResult.Gone;
                done.Set();
            },
                                                    onWebHookFailure: item =>
            {
                final        = item;
                actualResult = SendResult.Failure;
                done.Set();
            });
            _handlerMock.Handler = handler;
            var notification = new NotificationDictionary("a1", data: null);
            var webHook      = WebHookManagerTests.CreateWebHook();
            var workItem     = new WebHookWorkItem(webHook, new[] { notification })
            {
                Id = "1234567890",
            };

            // Act
            await _sender.SendWebHookWorkItemsAsync(new[] { workItem });

            done.WaitOne();

            // Assert
            var expectedRetries = expectedResult == SendResult.Failure ? Math.Max(0, expectedOffset - 1) : expectedOffset;

            Assert.Equal(expectedRetries, actualRetries);
            Assert.Equal(expectedResult, actualResult);
            Assert.Equal(expectedOffset, final.Offset);
        }
Beispiel #30
0
 public void Add(SendResult r)
 {
     _results[r]++;
 }
Beispiel #31
0
        void getClipboardCallback(SendResult <SaveableClipboard> resultCallback)
        {
            String error = null;

            resultCallback.Invoke(scratchAreaController.Clipboard, ref error);
        }
        // Code converted from php to C#: https://github.com/FroastJ/roblox-bots/blob/master/message.php
        public async Task <SendResult_t> Send()
        {
            HttpWebRequest request;

            if (String.IsNullOrWhiteSpace(_LastCSRFToken))
            {
                request = _Client.GetWebRequest(new Uri("http://www.roblox.com/messages/send"));
            }
            else
            {
                request = _Client.GetWebRequest(new Uri("http://www.roblox.com/messages/send"), _LastCSRFToken);
            }

            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));

            NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);

            outgoingQueryString.Add("subject", Subject);
            outgoingQueryString.Add("body", Body);
            outgoingQueryString.Add("recipientid", RecipientId.ToString());
            outgoingQueryString.Add("cacheBuster", t.TotalSeconds.ToString());
            string        postdata = outgoingQueryString.ToString();
            ASCIIEncoding ascii    = new ASCIIEncoding();

            byte[] data = ascii.GetBytes(postdata.ToString());

            if (maxSendIters >= RobloxBot.MAX_TRIES_WITH_CSRF_TOKEN)
            {
                maxSendIters = 0;
                return(new SendResult_t(SendResult.InvalidXSRFToken));
            }
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            request.Expect = "application/json";

            Stream postStream = request.GetRequestStream();

            postStream.Write(data, 0, data.Length);
            postStream.Flush();
            postStream.Close();
            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)await request.GetResponseAsync())
                {
                    SendResult   resulte    = (SendResult)(int)resp.StatusCode;
                    Stream       dataStream = resp.GetResponseStream();
                    StreamReader reader     = new StreamReader(dataStream);
                    string       result     = await reader.ReadToEndAsync();

                    SendResult_t res = JsonConvert.DeserializeObject <SendResult_t>(result);
                    res.Result   = resulte;
                    maxSendIters = 0;
                    return(res);
                }
            }
            catch (WebException ex)
            {
                if (((HttpWebResponse)ex.Response).StatusCode == (HttpStatusCode)403)
                {
                    maxSendIters++;
                    try
                    {
                        _LastCSRFToken = ex.Response.Headers.Get("X-Csrf-Token");
                    }
                    catch { }
                }
                else
                {
                    return(new SendResult_t(SendResult.InternalServerError));
                }
            }
            catch
            {
                return(new SendResult_t(SendResult.Unknown));
            }

            return(await Send());
        }
 internal NotifyResult(SendResult result, List<SendResponse> responses)
 {
     Result = result;
     Responses = responses ?? new List<SendResponse>();
 }
 public SendResponse(INotifyAction action, string senderName, IRecipient recipient, SendResult sendResult)
 {
     SenderName   = senderName;
     Recipient    = recipient;
     Result       = sendResult;
     NotifyAction = action;
 }
Beispiel #35
0
        private static SendResult MPSendMessage(SysWechatConfig wechat, string value,
                                                Weixin.MP.GroupMessageType type, string strTags, string[] strOpenids, string[] PreviewOpenids, string VideoTitle, string VideoContent, bool isKefu)
        {
            SendResult returnResult = null;

            //客服消息
            if (isKefu)
            {
                WxJsonResult retCustom = SendMsgKF(type, wechat, strOpenids, value, VideoTitle, VideoContent);

                return(new SendResult()
                {
                    errcode = retCustom.errcode, errmsg = retCustom.errmsg
                });
            }

            //预览消息
            if (PreviewOpenids != null)
            {
                foreach (var openid in PreviewOpenids)
                {
                    returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessagePreview(wechat.WeixinAppId, wechat.WeixinCorpSecret, type, value, openid);
                }
                return(returnResult);
            }


            //其他正常消息
            if (strTags == "-1" || (null != strOpenids && strOpenids.Length == 1 && "@all".Equals(strOpenids[0]))) //ToAll
            {
                returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByGroupId(wechat.WeixinAppId, wechat.WeixinCorpSecret, "", value, type, true, false, 10000);
            }
            else if (!string.IsNullOrEmpty(strTags)) //To Tags
            {
                returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByGroupId(wechat.WeixinAppId, wechat.WeixinCorpSecret, strTags, value, type, false, false, 10000);
            }
            else if (strOpenids.Length > 0) //To openids
            {
                //一次最多1W人,超过1W,分批发
                int      iOpenidCount = strOpenids.Length;
                string[] TempOpenids;

                for (int i = 0; i < Math.Ceiling(iOpenidCount / 5000d); i++)
                {
                    int iTo = 5000 * (i + 1) > iOpenidCount ? (iOpenidCount - 5000 * i) : 5000;
                    TempOpenids = new string[iTo];

                    Array.Copy(strOpenids, 5000 * i, TempOpenids, 0, iTo);

                    if (type == GroupMessageType.video) //腾讯接口视频单独处理
                    {
                        returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendVideoGroupMessageByOpenId(wechat.WeixinAppId, wechat.WeixinCorpSecret, VideoTitle, VideoContent, value, 10000, TempOpenids);
                    }
                    else
                    {
                        returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByOpenId(wechat.WeixinAppId, wechat.WeixinCorpSecret, type, value, 10000, TempOpenids);
                    }
                }
            }

            return(returnResult);
        }
 public MailMessage()
 {
     Result = new SendResult();
 }
Beispiel #37
0
 private void SendMessageCallback(ResponseFuture responseFuture, RemotingRequest request, string address, SendResult sendResult)
 {
     if (!sendResult.Success)
     {
         _logger.ErrorFormat("Send request {0} to channel <{1}> failed, exception:{2}", request, address, sendResult.Exception);
         responseFuture.SetException(new RemotingRequestException(address, request, sendResult.Exception));
         _responseFutureDict.Remove(request.Sequence);
     }
 }
Beispiel #38
0
        /// <summary>
        /// 服务号通用的发送消息
        /// </summary>
        /// <param name="strMsgType"></param>
        /// <param name="strContent"></param>
        /// <param name="lstContent"></param>
        /// <param name="strTags"></param>
        /// <param name="strOpenids"></param>
        /// <param name="PreviewOpenids"></param>
        /// <returns></returns>
        public static SendResult SendMsg(string strMsgType,
                                         string strContent, List <ArticleInfoView> lstContent, string strTags, string[] strOpenids, string[] PreviewOpenids, bool isKefu = false /*是否客服消息*/)
        {
            SendResult   returnResult = null;
            WxJsonResult retCustom    = null;
            var          objConfig    = WeChatCommonService.GetWeChatConfigByID(lstContent[0].AppId.Value);

            //log.Debug("strUser:{0} strDept:{1} strTags:{2} Msg:{3} APPID:{4}", strUser, strDept, strTags, strContent, iAppID);
            //  string strToken = Innocellence.Weixin.MP.CommonAPIs.AccessTokenContainer.GetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);
            switch (strMsgType)
            {
            case "text":

                returnResult = MPSendMessage(objConfig, lstContent[0].NewsInfo.NewsContent, Weixin.MP.GroupMessageType.text, strTags, strOpenids, PreviewOpenids, "", "", isKefu);
                break;

            case "news":     //因为历史原因,news和mpnews对应反了.此处实际就是mpnews业务

                List <NewsModel> articles = new List <NewsModel>();
                string           host     = CommonService.GetSysConfig("Content Server", "");
                if (host.EndsWith("/"))
                {
                    host = host.Substring(0, host.Length - 1);
                }
                for (int i = 0; i < lstContent.Count; i++)
                {
                    var item     = lstContent[i];
                    var filePath = "";
                    if (0 == i)
                    {
                        //不存在就创建
                        filePath = WechatCommon.doGetFileCover(item.ImageCoverUrl, "_B");
                    }
                    else
                    {
                        filePath = WechatCommon.doGetFileCover(item.ImageCoverUrl, "_T");
                    }


                    var ret0   = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, Weixin.MP.UploadMediaFileType.thumb, HttpRuntime.AppDomainAppPath + filePath);
                    var picUrl = (host + filePath).Replace("\\", "/");
                    var url    = string.Format("{0}/MPNews/ArticleInfo/WxDetail/{1}?wechatid={2}&isPreview={3}", host, item.Id, item.AppId, PreviewOpenids == null ? false : true);
                    articles.Add(new NewsModel()
                    {
                        title = item.ArticleTitle, content = WechatCommonMP.ImageConvert(item.ArticleContent, objConfig.Id), thumb_url = picUrl, thumb_media_id = ret0.thumb_media_id, content_source_url = url
                    });
                }
                var ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryNews(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, 10000, articles.ToArray());
                returnResult = MPSendMessage(objConfig, ret.media_id, Weixin.MP.GroupMessageType.mpnews, strTags, strOpenids, PreviewOpenids, "", "", isKefu);

                break;

            case "mpnews":      //因为历史原因,news和mpnews对应反了。此处实际就是news业务

                List <Article> articles1 = new List <Article>();
                string         host1     = CommonService.GetSysConfig("Content Server", "");
                if (host1.EndsWith("/"))
                {
                    host1 = host1.Substring(0, host1.Length - 1);
                }
                for (int i = 0; i < lstContent.Count; i++)
                {
                    var item     = lstContent[i];
                    var filePath = "";
                    if (0 == i)
                    {
                        //不存在就创建
                        filePath = WechatCommon.doGetFileCover(item.ImageCoverUrl, "_B");
                    }
                    else
                    {
                        filePath = WechatCommon.doGetFileCover(item.ImageCoverUrl, "_T");
                    }

                    //  var ret0 = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, Weixin.MP.UploadMediaFileType.thumb, filePath);
                    var picUrl = (host1 + filePath).Replace("\\", "/");
                    var url    = string.Format("{0}/MPNews/ArticleInfo/WxDetail/{1}?wechatid={2}&isPreview={3}", host1, item.Id, item.AppId, PreviewOpenids == null ? false : true);
                    articles1.Add(new Article()
                    {
                        Title = item.ArticleTitle, PicUrl = picUrl, Url = url, Description = item.ArticleComment
                    });
                }
                // var ret1 = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryNews(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, 10000, articles1.ToArray());

                // retCustom=SendMsgKF(strMsgType, objConfig,strOpenids, articles1);

                WxJsonResult retCustom1;
                foreach (var openId in strOpenids)
                {
                    retCustom1 = CustomApi.SendNews(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, openId, articles1);
                    if (retCustom1.errcode != ReturnCode.请求成功)
                    {
                        retCustom = retCustom1;
                    }
                    else if (retCustom == null)
                    {
                        retCustom = retCustom1;
                    }
                }

                returnResult = new SendResult()
                {
                    errcode = retCustom.errcode, errmsg = retCustom.errmsg
                };
                //  returnResult = MPSendMessage(objConfig, ret1.media_id, Weixin.MP.GroupMessageType.mpnews, strTags, strOpenids, PreviewOpenids, "", "");
                break;

            case "image":
                lstContent[0].NewsInfo.MediaId = WechatCommon.DoNewsInfo(lstContent[0].NewsInfo, objConfig, AutoReplyContentEnum.IMAGE, lstContent[0].NewsInfo.ImageContent);
                //WechatCommon.GetMediaInfo(AutoReplyContentEnum.IMAGE, lstContent[0].NewsInfo, objConfig.Id);
                returnResult = MPSendMessage(objConfig, lstContent[0].NewsInfo.MediaId, Weixin.MP.GroupMessageType.image, strTags, strOpenids, PreviewOpenids, "", "", isKefu);
                break;

            case "video":
                //WechatCommon.GetMediaInfo(AutoReplyContentEnum.VIDEO, lstContent[0].NewsInfo, lstContent[0].NewsInfo.AppId);
                lstContent[0].NewsInfo.MediaId = WechatCommon.DoNewsInfo(lstContent[0].NewsInfo, objConfig, AutoReplyContentEnum.VIDEO, lstContent[0].NewsInfo.VideoContent);
                if (!isKefu)
                {
                    var ret2 = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.GetOpenIdVideoMediaIdResult(objConfig.WeixinAppId, objConfig.WeixinCorpSecret, lstContent[0].NewsInfo.MediaId, lstContent[0].NewsInfo.NewsTitle, lstContent[0].NewsInfo.NewsComment);
                    lstContent[0].NewsInfo.MediaId         = ret2.media_id;
                    lstContent[0].NewsInfo.MediaCreateTime = ret2.created_at;
                }
                MPSendMessage(objConfig, lstContent[0].NewsInfo.MediaId, Weixin.MP.GroupMessageType.video, strTags, strOpenids, PreviewOpenids, lstContent[0].NewsInfo.NewsTitle, lstContent[0].NewsInfo.NewsComment, isKefu);
                break;

            case "voice":
                //WechatCommon.GetMediaInfo(AutoReplyContentEnum.VOICE, lstContent[0].NewsInfo, lstContent[0].NewsInfo.AppId);
                lstContent[0].NewsInfo.MediaId = WechatCommon.DoNewsInfo(lstContent[0].NewsInfo, objConfig, AutoReplyContentEnum.VOICE, lstContent[0].NewsInfo.SoundSrc);
                returnResult = MPSendMessage(objConfig, lstContent[0].NewsInfo.MediaId, Weixin.MP.GroupMessageType.voice, strTags, strOpenids, PreviewOpenids, "", "", isKefu);
                break;
            }
            return(returnResult);
        }
Beispiel #39
0
        public SendResult Reserve(int year, int count, string discount, Option option)
        {
            dynamic json = null;

            switch (PluginHost.SendType)
            {
            case SendTypes.Inquire:
                try
                {
                    json = Communicator.CheckClubMagazine(year, count);
                }
                catch (Exception ex)
                {
                    return(SendResult.Error(ex));
                }

                try
                {
                    return(ParseResult(json, true));
                }
                catch (Exception ex)
                {
                    try
                    {
                        return(SendResult.Error(ex, json, ResultTypeStringToEnum(json)));
                    }
                    catch
                    {
                        return(SendResult.Error(ex));
                    }
                }

            case SendTypes.Sell:
            case SendTypes.Reserve:
                try
                {
                    json = Communicator.BuyClubMagazine(year, count, discount, StationName + TerminalName, PluginHost.IsTestMode);
                }
                catch (Exception ex)
                {
                    return(SendResult.Error(ex));
                }

                try
                {
                    bool isFirstReservation = false;
                    if (!PluginHost.IsOneTimeMode && PluginHost.SendType == SendTypes.Reserve)
                    {
                        PluginHost.IsOneTimeMode = true;
                        isFirstReservation       = true;
                    }

                    SendResult result = ParseResult(json, new Func <int, int, List <TicketBase> >((issueNumber, countStartNumber) =>
                    {
                        NativeEventTicket ticket = new NativeEventTicket(new IssueInformation()
                        {
                            TerminalName = StationName + TerminalName, Number = CompanyNumber
                        }, new EventTicketInformation()
                        {
                            Title               = "部誌購入証",
                            Product             = "部誌" + Strings.StrConv(year.ToString(), VbStrConv.Wide) + "号",
                            Description         = "出札にて保管すること",
                            Amount_Adult        = json.price,
                            ValidType           = TicketValidTypes.Once,
                            UseDate             = DateTime.Parse(json.now),
                            Persons_Adult       = 1,
                            IssuedDate          = DateTime.Parse(json.now),
                            IssueNumber         = issueNumber,
                            CountBeginNumber    = countStartNumber,
                            IsWorkingOnInternet = true,
                            InfoTop             = AdditionalInformation_Top.None,
                        }, PrintSetting);

                        return(ticket.ticketImages.Select((t, i) => (TicketBase) new EventTicket(ticket, i)).ToList());
                    }));

                    if (PluginHost.SendType == SendTypes.Reserve)
                    {
                        result.Text = "#" + Strings.StrConv($"{PluginHost.ReservedResults.Count + 1}", VbStrConv.Wide);
                    }
                    if (isFirstReservation)
                    {
                        result.Message = "一括一件開始しました";
                    }

                    return(result);
                }
                catch (Exception ex)
                {
                    try
                    {
                        return(SendResult.Error(ex, ResultTypeStringToEnum(json)));
                    }
                    catch
                    {
                        return(SendResult.Error(ex));
                    }
                }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
 public void AddSendResult(SendResult result)
 {
     sendResults.Add(result);
     if (result.Success) Interlocked.Increment(ref sentItemCount);
     else Interlocked.Increment(ref failedItemCount);
 }