private void button1_Click(object sender, EventArgs e) { MessageType messageType = MessageType.Info; if (comboBoxMessageType.SelectedItem != null) { messageType = (MessageType)Enum.Parse(typeof(MessageType), comboBoxMessageType.SelectedItem.ToString()); } using (NotifyClient notifyClient = new NotifyClient()) { notifyClient.NotifyAll(messageType, DateTime.Now, textBoxTeamId.Text, textBoxCategory.Text, textBoxText.Text); } }
public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message) { if (entry == null) { throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest); } if (!CanSetAccess(entry)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } var fileSecurity = Global.GetFilesSecurity(); var entryType = entry.FileEntryType; var recipients = new Dictionary <Guid, FileShare>(); var usersWithoutRight = new List <Guid>(); var changed = false; foreach (var w in aceWrappers.OrderByDescending(ace => ace.SubjectGroup)) { var subjects = fileSecurity.GetUserSubjects(w.SubjectId); var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy; if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) || ownerId == w.SubjectId) { continue; } var share = w.Share; if (w.SubjectId == FileConstant.ShareLinkId) { if (w.Share == FileShare.ReadWrite && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } // only editable format on personal if (CoreContext.Configuration.Personal && !FileUtility.CanWebView(entry.Title) && w.Share != FileShare.Restrict) { throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest); } // only editable format on SaaS trial if (w.Share != FileShare.Restrict && !CoreContext.Configuration.Standalone && TenantExtra.GetTenantQuota().Trial&& !FileUtility.CanWebView(entry.Title)) { throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest); } share = w.Share == FileShare.Restrict ? FileShare.None : w.Share; } fileSecurity.Share(entry.ID, entryType, w.SubjectId, share); changed = true; if (w.SubjectId == FileConstant.ShareLinkId) { continue; } entry.Access = share; var listUsersId = new List <Guid>(); if (w.SubjectGroup) { listUsersId = CoreContext.UserManager.GetUsersByGroup(w.SubjectId).Select(ui => ui.ID).ToList(); } else { listUsersId.Add(w.SubjectId); } listUsersId.Remove(SecurityContext.CurrentAccount.ID); if (entryType == FileEntryType.File) { listUsersId.ForEach(uid => FileTracker.ChangeRight(entry.ID, uid, true)); } var addRecipient = share == FileShare.Read || share == FileShare.CustomFilter || share == FileShare.ReadWrite || share == FileShare.Review || share == FileShare.FillForms || share == FileShare.Comment || share == FileShare.None && entry.RootFolderType == FolderType.COMMON; var removeNew = share == FileShare.None && entry.RootFolderType == FolderType.USER || share == FileShare.Restrict; listUsersId.ForEach(id => { recipients.Remove(id); if (addRecipient) { recipients.Add(id, share); } else if (removeNew) { usersWithoutRight.Add(id); } }); } if (entryType == FileEntryType.File) { DocumentServiceHelper.CheckUsersForDrop((File)entry); } if (recipients.Any()) { if (entryType == FileEntryType.File || ((Folder)entry).TotalSubFolders + ((Folder)entry).TotalFiles > 0 || entry.ProviderEntry) { FileMarker.MarkAsNew(entry, recipients.Keys.ToList()); } if ((entry.RootFolderType == FolderType.USER || entry.RootFolderType == FolderType.Privacy) && notify) { NotifyClient.SendShareNotice(entry, recipients, message); } } usersWithoutRight.ForEach(userId => FileMarker.RemoveMarkAsNew(entry, userId)); return(changed); }
protected void Page_Load(object sender, EventArgs e) { this.param = new NameValueCollection { base.Request.QueryString, base.Request.Form }; SiteSettings masterSettings = SettingsManager.GetMasterSettings(); NotifyClient notifyClient = null; notifyClient = ((string.IsNullOrEmpty(masterSettings.Main_Mch_ID) || string.IsNullOrEmpty(masterSettings.Main_AppId)) ? new NotifyClient(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret, masterSettings.WeixinPartnerID, masterSettings.WeixinPartnerKey, masterSettings.WeixinPaySignKey, "", "") : new NotifyClient(masterSettings.Main_AppId, masterSettings.WeixinAppSecret, masterSettings.Main_Mch_ID, masterSettings.WeixinPartnerKey, masterSettings.WeixinPaySignKey, masterSettings.WeixinAppId, masterSettings.WeixinPartnerID)); NameValueCollection nameValueCollection = new NameValueCollection { base.Request.QueryString, base.Request.Form }; string sign = ""; PayNotify payNotify = notifyClient.GetPayNotify(base.Request.InputStream); if (payNotify == null) { Globals.AppendLog(this.param, "通知信息为空", sign, "", "AppStore_wxPay"); } else { this.OrderId = payNotify.PayInfo.OutTradeNo; this.Order = ShoppingProcessor.GetOrderInfo(this.OrderId); this.offlineOrder = StoresHelper.GetStoreCollectionInfo(this.OrderId); if (this.Order == null) { this.Order = ShoppingProcessor.GetOrderInfo(payNotify.PayInfo.OutTradeNo); } if (this.offlineOrder == null) { this.offlineOrder = StoresHelper.GetStoreCollectionInfo(payNotify.PayInfo.OutTradeNo); } if (this.Order == null && this.offlineOrder == null) { Globals.AppendLog(this.param, "订单信息为空", sign, "", "AppStore_wxPay"); base.Response.Write("success"); } else { EnumPaymentType enumPaymentType = EnumPaymentType.WXPay; if (this.Order == null) { this.isOfflineOrder = true; } else { this.Order.PaymentTypeId = (int)enumPaymentType; this.Order.PaymentType = EnumDescription.GetEnumDescription((Enum)(object)enumPaymentType, 0); this.Order.Gateway = EnumDescription.GetEnumDescription((Enum)(object)enumPaymentType, 1); this.Order.GatewayOrderId = payNotify.PayInfo.TransactionId; if (this.offlineOrder == null) { this.offlineOrder = StoresHelper.GetStoreCollectionInfoOfOrderId(this.Order.OrderId); } } if (this.offlineOrder != null) { this.offlineOrder.GateWayOrderId = payNotify.PayInfo.TransactionId; this.offlineOrder.PaymentTypeId = (int)enumPaymentType; this.offlineOrder.PaymentTypeName = EnumDescription.GetEnumDescription((Enum)(object)enumPaymentType, 0); this.offlineOrder.GateWay = EnumDescription.GetEnumDescription((Enum)(object)enumPaymentType, 1); } this.UserPayOrder(); base.Response.Write("success"); } } }
public static void RegisterSendMethods() { NotifyClient.RegisterSendMethods(); }
public override void Shutdown() { NotifyClient.UnregisterSendMethods(); }
public static async Task Run([TimerTrigger("0 0 0 * * *")] TimerInfo myTimer, ILogger log) { string message = string.Empty; string messageContent = string.Empty; string responseMessage = string.Empty; var connectingString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); var serviceParam = Environment.GetEnvironmentVariable("ServiceParameter").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries). ToDictionary(x => x.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[0], x => x.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]); var adminId = Environment.GetEnvironmentVariable("AdminId"); var csLink = Environment.GetEnvironmentVariable("CSContact"); var adminArray = adminId.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var csArray = csLink.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); try { var serviceList = await TableStorage <UserServiceInfoModel> .CreateTable(connectingString, "ClientServiceInfo"); var macList = await TableStorage <TradeCallMACRecordModel> .CreateTable(connectingString, "MACTable"); // Only check alive service var mac = macList.FindAsync("ServiceStatus", TableStorage <TradeCallMACRecordModel> .SelectCondition.NotEqual, "Terminated").Result; var now = DateTime.Now; // Comfirm the MAC is availble to use notify funtion foreach (var alive in mac) { bool bChange = false; var days = Math.Ceiling(new TimeSpan(alive.ServiceExpiredDate.Ticks - now.Ticks).TotalDays); if (days >= 0) { alive.RemainedDays = Convert.ToInt16(days); bChange = true; } if (alive.RemainedDays <= 0) { alive.ServiceStatus = "Expired"; bChange = true; } if (bChange) { await macList.UpdateAsync(alive); } } var clientList = await TableStorage <UserLineInfo> .CreateTable(connectingString, "ClientInfo"); var serviceTable = serviceList.FindAsync("ServiceStatus", TableStorage <UserServiceInfoModel> .SelectCondition.NotEqual, "Terminated").Result; var admin = new List <UserLineInfo>(); foreach (var item in adminArray) { var user = clientList.FindAsync("User", item).Result; if (user != null) { admin.Add(user); } } var agents = string.Empty; foreach (var item in csArray) { agents += (item + "\n"); } foreach (var service in serviceTable) { var days = Math.Ceiling(new TimeSpan(service.ServiceExpiredDate.Ticks - now.Ticks).TotalDays); if (days >= 0) { service.RemainedDays = Convert.ToInt16(days); } if (days <= Convert.ToInt16(serviceParam["ServiceRemindDays"]) && service.ExpiredNotifyTimes > 0) { var client = clientList.FindAsync("User", service.RowKey).Result; if (days > 0) { messageContent = $"@{client.UserName}, 您的交易通知服務將於 {service.ServiceExpiredDate.ToString("yyyy/MM/dd")} 到期,請儘快連絡營業員\n{agents}"; } else { messageContent = $"@{client.UserName}, 您的交易通知服務已到期,請連絡營業員\n{agents}"; } if (client != null) { using (var notifyClient = new NotifyClient()) { if (client.NotifyToken.Length > 1) { await notifyClient.SentNotifyToUser(client.NotifyToken, $"\n\n@{client.UserName} - 到期通知\n\n{messageContent}"); } } } if (admin.Count > 0) { foreach (var item in admin) { using (var notifyClient = new NotifyClient()) { if (item.NotifyToken.Length > 1) { await notifyClient.SentNotifyToUser(item.NotifyToken, $"\n\n@{client.UserName} - 到期通知\n\n" + $"會員 @{client.UserName} 交易通知服務將於 {days}日 後到期,請通知會員"); } } } } } if (days <= 0 && service.ServiceStatus == "Alive") { service.ServiceStatus = "Expired"; } if (days <= 0 && service.ExpiredNotifyTimes > 0) { service.ExpiredNotifyTimes--; } await serviceList.UpdateAsync(service); } message = $"推播完成"; } catch (Exception ex) { message = $"推播未完成,錯誤原因: {ex.ToString()}"; } finally { log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}, {message}"); } }
public void SavePost(Post post, bool isNew, bool notifyComments) { CommunitySecurity.DemandPermissions( new PersonalBlogSecObject(CoreContext.UserManager.GetUsers(post.UserID)), isNew ? Constants.Action_AddPost : Constants.Action_EditRemovePost); _storage.GetPostDao().SavePost(post); if (isNew) { var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(post.UserID.ToString(), "")); try { NotifyClient.BeginSingleRecipientEvent("asc_blog"); NotifyClient.AddInterceptor(initiatorInterceptor); var tags = new List <ITagValue> { new TagValue(Constants.TagPostSubject, post.Title), new TagValue(Constants.TagPostPreview, post.GetPreviewText(500)), new TagValue(Constants.TagUserName, DisplayUserSettings.GetFullUserName(post.UserID)), new TagValue(Constants.TagUserURL, CommonLinkUtility.GetFullAbsolutePath( CommonLinkUtility.GetUserProfile(post.UserID))), new TagValue(Constants.TagDate, string.Format("{0:d} {0:t}", post.Datetime)), new TagValue(Constants.TagURL, CommonLinkUtility.GetFullAbsolutePath( Constants.ViewBlogPageUrl + "?blogid=" + post.ID.ToString())), GetReplyToTag(Guid.Empty, post) }; NotifyClient.SendNoticeAsync( Constants.NewPost, null, null, tags.ToArray()); NotifyClient.SendNoticeAsync( Constants.NewPostByAuthor, post.UserID.ToString(), null, tags.ToArray()); NotifyClient.EndSingleRecipientEvent("asc_blog"); } finally { NotifyClient.RemoveInterceptor(initiatorInterceptor.Name); } } if (!notifyComments) { return; } var subscriptionProvider = NotifySource.GetSubscriptionProvider(); subscriptionProvider.Subscribe( Constants.NewComment, post.ID.ToString(), NotifySource.GetRecipientsProvider(). GetRecipient(post.UserID.ToString()) ); }
public async System.Threading.Tasks.Task Invoke(HttpContext context, WebItemSecurity webItemSecurity, SecurityContext securityContext, CrmSecurity crmSecurity, MessageTarget messageTarget, MessageService messageService, Global global, IOptionsMonitor <ILog> logger, NotifyClient notifyClient, SettingsManager settingsManager, DaoFactory daoFactory) { try { WebItemSecurity = webItemSecurity; SecurityContext = securityContext; CRMSecurity = crmSecurity; MessageTarget = messageTarget; MessageService = messageService; Global = global; Logger = logger.Get("ASC.CRM"); NotifyClient = notifyClient; SettingsManager = settingsManager; _context = context; SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem); if (!CheckPermission()) { throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException); } var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString()); if (!productInfo.Enabled) { throw new Exception(CRMCommonResource.CRMProductIsDisabled); } Contact contact; var fieldCollector = new NameValueCollection(); var addressTemplate = new Dictionary <String, Object>(); foreach (String addressPartName in Enum.GetNames(typeof(AddressPart))) { addressTemplate.Add(addressPartName.ToLower(), ""); } var addressTemplateStr = JsonSerializer.Serialize(addressTemplate); var isCompany = false; var isCompanyString = GetValue("is_company"); var firstName = GetValue("firstName"); var lastName = GetValue("lastName"); var companyName = GetValue("companyName"); if (!String.IsNullOrEmpty(isCompanyString)) { if (!Boolean.TryParse(isCompanyString, out isCompany)) { throw new ArgumentException(); } } else //old scheme { if (!String.IsNullOrEmpty(firstName)) { isCompany = false; } else if (!String.IsNullOrEmpty(companyName)) { isCompany = true; } else { throw new ArgumentException(); } } if (isCompany) { contact = new Company(); ((Company)contact).CompanyName = companyName; fieldCollector.Add(CRMContactResource.CompanyName, companyName); } else { contact = new Person(); ((Person)contact).FirstName = firstName; ((Person)contact).LastName = lastName; ((Person)contact).JobTitle = GetValue("jobTitle"); fieldCollector.Add(CRMContactResource.FirstName, firstName); fieldCollector.Add(CRMContactResource.LastName, lastName); if (!String.IsNullOrEmpty(GetValue("jobTitle"))) { fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle); } } contact.About = GetValue("about"); if (!String.IsNullOrEmpty(contact.About)) { fieldCollector.Add(CRMContactResource.About, contact.About); } if (!String.IsNullOrEmpty(GetValue("is_shared"))) { contact.ShareType = Convert.ToBoolean(GetValue("is_shared")) ? ShareType.ReadWrite : ShareType.None; } else { contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type"))); } contact.ID = daoFactory.GetContactDao().SaveContact(contact); var messageAction = contact is Company ? MessageAction.CompanyCreatedWithWebForm : MessageAction.PersonCreatedWithWebForm; MessageService.Send(MessageInitiator.System, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); var contactInfos = new List <ContactInfo>(); foreach (var key in _context.Request.Form.Keys) { if (key.StartsWith("customField_")) { var fieldID = Convert.ToInt32(key.Split(new[] { '_' })[1]); String fieldValue = GetValue(key); if (String.IsNullOrEmpty(fieldValue)) { continue; } var customField = daoFactory.GetCustomFieldDao().GetFieldDescription(fieldID); if (customField == null || !(customField.EntityType == EntityType.Contact || customField.EntityType == EntityType.Company && isCompany || customField.EntityType == EntityType.Person && !isCompany)) { continue; } if (customField.Type == CustomFieldType.CheckBox) { fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false"; } fieldCollector.Add(customField.Label, fieldValue); daoFactory.GetCustomFieldDao().SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue); } else if (key.StartsWith("contactInfo_")) { var nameParts = key.Split(new[] { '_' }).Skip(1).ToList(); var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]); var category = Convert.ToInt32(nameParts[1]); bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType)) .Cast <object>() .Any(categoryEnum => (int)categoryEnum == category); if (!categoryIsExists) { throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0])); } if (contactInfoType == ContactInfoType.Address) { var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]); var findedAddress = contactInfos.Find( item => (category == item.Category) && (item.InfoType == ContactInfoType.Address)); if (findedAddress == null) { findedAddress = new ContactInfo { Category = category, InfoType = contactInfoType, Data = addressTemplateStr, ContactID = contact.ID }; contactInfos.Add(findedAddress); } Dictionary <string, object> addressParts = JsonSerializer.Deserialize <Dictionary <string, object> >(findedAddress.Data); addressParts[addressPart.ToString().ToLower()] = GetValue(key); string newJson = JsonSerializer.Serialize(addressParts); findedAddress.Data = JsonSerializer.Serialize(addressParts); continue; } var fieldValue = GetValue(key); if (String.IsNullOrEmpty(fieldValue)) { continue; } contactInfos.Add(new ContactInfo { Category = category, InfoType = contactInfoType, Data = fieldValue, ContactID = contact.ID, IsPrimary = true }); } else if (String.Compare(key, "tag", true) == 0) { var tags = _context.Request.Form["tag"]; daoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags); } } contactInfos.ForEach( item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data)); daoFactory.GetContactInfoDao().SaveList(contactInfos, contact); var notifyList = GetValue("notify_list"); if (!String.IsNullOrEmpty(notifyList)) { NotifyClient.SendAboutCreateNewContact( notifyList .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector); } var managersList = GetValue("managers_list"); SetPermission(contact, managersList); if (contact is Person && !String.IsNullOrEmpty(companyName)) { AssignPersonToCompany((Person)contact, companyName, managersList, daoFactory); } if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName)) { AssignCompanyToPerson((Company)contact, firstName, lastName, managersList, daoFactory); } SecurityContext.Logout(); var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri; context.Response.Clear(); context.Response.StatusCode = (int)HttpStatusCode.Found; context.Response.Headers.Add("Location", newURL); await context.Response.WriteAsync("<HTML><Head>"); await context.Response.WriteAsync(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL)); await context.Response.WriteAsync(String.Format("<Script>window.location='{0}';</Script>", newURL)); await context.Response.WriteAsync("</Head>"); await context.Response.WriteAsync("</HTML>"); } catch (Exception error) { Logger.Error(error); context.Response.StatusCode = (int)HttpStatusCode.BadRequest; await context.Response.WriteAsync(HttpUtility.HtmlEncode(error.Message)); } }
public NotifyClientTests() { _notificationClient = Substitute.For <INotificationClient>(); _sut = new NotifyClient(_notificationClient); }
protected void Page_Load(object sender, System.EventArgs e) { ErrorLog.Write("进入App微信支付回调(wx_Pay_notify_url) ..."); //// 看原始NotifyData //string notifyData = "空"; //if (base.Request.InputStream != null) //{ // StreamReader reader = new StreamReader(base.Request.InputStream, Encoding.GetEncoding("UTF-8")); // notifyData = reader.ReadToEnd(); //} //ErrorLog.Write("App微信支付回调原始数据(wx_Pay_notify_url) :" + notifyData); PaymentModeInfo paymentMode = SalesHelper.GetPaymentMode("Ecdev.plugins.payment.wx_apppay.wxwappayrequest"); string AppId = ""; string Key = ""; string AppSecret = ""; string Mch_id = ""; if (paymentMode != null) { if (paymentMode.Settings != "") { string xml = HiCryptographer.Decrypt(paymentMode.Settings); try { System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.LoadXml(xml); AppId = xmlDocument.GetElementsByTagName("AppId")[0].InnerText; Key = xmlDocument.GetElementsByTagName("Key")[0].InnerText; AppSecret = xmlDocument.GetElementsByTagName("AppSecret")[0].InnerText; Mch_id = xmlDocument.GetElementsByTagName("Mch_id")[0].InnerText; } catch (System.Exception ex) { ErrorLog.Write("微信App支付回调信息未设置:" + ex.Message); } } } ErrorLog.Write("开始获取App微信支付回调数据(wx_Pay_notify_url) ..."); NotifyClient notifyClient = new NotifyClient(AppId, AppSecret, Mch_id, Key, ""); payNotify = notifyClient.GetPayNotify(base.Request.InputStream); if (payNotify == null) { ErrorLog.Write("App微信支付回调数据(wx_Pay_notify_url)为空"); return; } this.OrderId = payNotify.PayInfo.OutTradeNo; ErrorLog.Write("获取App微信支付回调订单数据(wx_Pay_notify_url):" + this.OrderId); this.Order = ShoppingProcessor.GetOrderInfo(this.OrderId); if (this.Order == null) { ErrorLog.Write("App微信支付回调数据(wx_Pay_notify_url)没找到订单:" + this.OrderId); base.Response.Write("success"); return; } ErrorLog.Write("App微信支付回调数据(wx_Pay_notify_url)交易号:" + payNotify.PayInfo.TransactionId); this.Order.GatewayOrderId = payNotify.PayInfo.TransactionId; this.Order.PaymentTypeId = paymentMode.ModeId; this.Order.PaymentType = paymentMode.Name; this.Order.Gateway = paymentMode.Gateway; ErrorLog.Write("App微信支付回调数据(wx_Pay_notify_url),设置订单状态:" + this.OrderId); this.UserPayOrder(); }
public void RetrievePattern(RetrievePatternOps SubOp, string Font, int Page, int KbType) { int[] SizeRX = new int[] { 8, 8, 8, 16, 16, 32, 32, 72, 128, 32, 5, 5, 7, 200, 288 }; int[] CountRX = new int[] { 37, 37, 37, 37, 37, 15 }; int[] HeaderRX = new int[] { 4, 3 }; int[] SizePXR = new int[] { 8, 8, 16, 32, 72, 128, 16 }; int[,] CountPXR = new int[, ] { { 45, 45, 38 }, { 46, 44, 0 } }; int[] HeaderPXR = new int[] { 4, 2 }; // Local Storage int intCharSize = 0; int intRcvLength = 0; // Translate the font intCharSize = GetFont(Font, true)[0] - '0'; // Was the font invalid if (intCharSize < 0) { NotifyClient?.Invoke(this, new HPEventArgs("Invalid font specified!")); return; } // Is the page number valid switch (SubOp) { case RetrievePatternOps.Standard: if (Page < 1 || Page > 3) { Page = -1; } break; case RetrievePatternOps.User: if (rxClass) { if (Page < 1 || Page > 6) { Page = -1; } } else { if (Page < 1 || Page > 3) { Page = -1; } } break; } // Is the page number invalid if (Page < 0) { NotifyClient?.Invoke(this, new HPEventArgs("Invalid page number specified!")); return; } // Get the number of characters expected and issue operation if (rxClass) { if (SubOp == RetrievePatternOps.User) { intRcvLength = (SizeRX[intCharSize] + HeaderRX[(int)SubOp]) * CountRX[Page - 1] + 2; } else { if (KbType == 1) { if (Page == 2) { intRcvLength = 2; } else { intRcvLength = (SizeRX[intCharSize] + HeaderRX[(int)SubOp]) * 38 + 2; } } else { intRcvLength = (SizeRX[intCharSize] + HeaderRX[(int)SubOp]) * 26 + 2; } } } else { intRcvLength = (SizePXR[intCharSize] + HeaderPXR[(int)SubOp]) * CountPXR[(int)SubOp, Page - 1] + 2; } HPRequest mReq = GetRequest(PrinterOps.RetrievePattern, (int)SubOp); mReq.CharSize = intCharSize; mReq.Page = Page; mReq.RcvLength = RcvLength; mReq.KbType = KbType; mReq.Retries = 0; IssueRequest(mReq); }
public void TearDown() { handler = null; client = null; }
public void SaveComment(Comment comment, Post post) { CommunitySecurity.DemandPermissions(post, Constants.Action_AddComment); SaveComment(comment); var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(comment.UserID.ToString(), "")); try { NotifyClient.BeginSingleRecipientEvent("asc_blog_c"); NotifyClient.AddInterceptor(initiatorInterceptor); var tags = new ITagValue[] { new TagValue(Constants.TagPostSubject, post.Title), new TagValue(Constants.TagPostPreview, post.GetPreviewText(500)), new TagValue(Constants.TagUserName, DisplayUserSettings.GetFullUserName(comment.UserID)), new TagValue(Constants.TagUserURL, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(comment.UserID))), new TagValue(Constants.TagDate, string.Format("{0:d} {0:t}", comment.Datetime)), new TagValue(Constants.TagCommentBody, comment.Content), new TagValue(Constants.TagURL, CommonLinkUtility.GetFullAbsolutePath(Constants.ViewBlogPageUrl + "?blogid=" + post.ID.ToString())), new TagValue(Constants.TagCommentURL, CommonLinkUtility.GetFullAbsolutePath(Constants.ViewBlogPageUrl + "?blogid=" + post.ID.ToString() + "#container_" + comment.ID.ToString())) }; var mentionedUsers = MentionProvider.GetMentionedUsers(comment.Content); var mentionedUserIds = mentionedUsers.Select(u => u.ID.ToString()); var provider = _notifySource.GetSubscriptionProvider(); var objectID = post.ID.ToString(); var recipients = provider .GetRecipients(Constants.NewComment, objectID) .Where(r => !mentionedUserIds.Contains(r.ID)) .ToArray(); NotifyClient.SendNoticeToAsync(Constants.NewComment, objectID, recipients, false, tags); if (mentionedUsers.Length > 0) { NotifyClient.SendNoticeToAsync(Constants.MentionForPostComment, objectID, mentionedUsers, false, tags); } NotifyClient.EndSingleRecipientEvent("asc_blog_c"); } finally { NotifyClient.RemoveInterceptor(initiatorInterceptor.Name); } var subscriptionProvider = NotifySource.GetSubscriptionProvider(); if (!subscriptionProvider.IsUnsubscribe((IDirectRecipient)NotifySource.GetRecipientsProvider(). GetRecipient(SecurityContext.CurrentAccount.ID.ToString()), Constants.NewComment, post.ID.ToString())) { subscriptionProvider.Subscribe( Constants.NewComment, post.ID.ToString(), NotifySource.GetRecipientsProvider(). GetRecipient(SecurityContext.CurrentAccount.ID.ToString()) ); } }
public void NotifyAll(MessageType messageType, DateTime dateTime, string teamId, string category, string text) { ThreadPool.QueueUserWorkItem(delegate { try { using (NotifyClient notifyClient = new NotifyClient()) { notifyClient.NotifyAll(messageType, dateTime, teamId, category, text); } } catch { } }, null); }
public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message) { if (entry == null) { throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest); } if (!CanSetAccess(entry)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } var fileSecurity = Global.GetFilesSecurity(); var defaultShare = entry.RootFolderType == FolderType.COMMON ? fileSecurity.DefaultCommonShare : fileSecurity.DefaultMyShare; var entryType = entry.FileEntryType; var recipients = new Dictionary <Guid, FileShare>(); var changed = false; foreach (var w in aceWrappers.OrderByDescending(ace => ace.SubjectGroup)) { var subjects = fileSecurity.GetUserSubjects(w.SubjectId); var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy; if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) || ownerId == w.SubjectId) { continue; } var ace = fileSecurity.GetShares(entry) .Where(r => subjects.Contains(r.Subject)) .OrderBy(r => subjects.IndexOf(r.Subject)) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share) .FirstOrDefault(); var parentShare = ace != null && !(ace.Subject == w.SubjectId && ace.Share == w.Share) ? ace.Share : defaultShare; var share = parentShare == w.Share ? FileShare.None : w.Share; if (w.SubjectId == FileConstant.ShareLinkId) { if (w.Share == FileShare.ReadWrite && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } share = w.Share == FileShare.Restrict ? FileShare.None : w.Share; } fileSecurity.Share(entry.ID, entryType, w.SubjectId, share); changed = true; if (w.SubjectId == FileConstant.ShareLinkId) { continue; } entry.Access = share; var listUsersId = new List <Guid>(); if (w.SubjectGroup) { listUsersId = CoreContext.UserManager.GetUsersByGroup(w.SubjectId).Select(ui => ui.ID).ToList(); } else { listUsersId.Add(w.SubjectId); } listUsersId.Remove(SecurityContext.CurrentAccount.ID); if (entryType == FileEntryType.File) { listUsersId.ForEach(uid => FileTracker.ChangeRight(entry.ID, uid, true)); } var addRecipient = share == FileShare.Read || share == FileShare.ReadWrite || share == FileShare.Review || share == FileShare.None && entry.RootFolderType == FolderType.COMMON; listUsersId.ForEach(id => { recipients.Remove(id); if (addRecipient) { recipients.Add(id, share); } }); } if (entryType == FileEntryType.File) { DocumentServiceHelper.CheckUsersForDrop((File)entry); } if (recipients.Any()) { if (entryType == FileEntryType.File || ((Folder)entry).TotalSubFolders + ((Folder)entry).TotalFiles > 0 || entry.ProviderEntry) { FileMarker.MarkAsNew(entry, recipients.Keys.ToList()); } if (entry.RootFolderType == FolderType.USER && notify) { NotifyClient.SendShareNotice(entry, recipients, message); } } return(changed); }
private static void Webhook(HttpContext context) { Global.Logger.Info("DocuSign webhook: " + context.Request.QueryString); try { var xmldoc = new XmlDocument(); xmldoc.Load(context.Request.InputStream); Global.Logger.Info("DocuSign webhook outerXml: " + xmldoc.OuterXml); var mgr = new XmlNamespaceManager(xmldoc.NameTable); mgr.AddNamespace(XmlPrefix, "http://www.docusign.net/API/3.0"); var envelopeStatusNode = GetSingleNode(xmldoc, "DocuSignEnvelopeInformation/" + XmlPrefix + ":EnvelopeStatus", mgr); var envelopeId = GetSingleNode(envelopeStatusNode, "EnvelopeID", mgr).InnerText; var subject = GetSingleNode(envelopeStatusNode, "Subject", mgr).InnerText; var statusString = GetSingleNode(envelopeStatusNode, "Status", mgr).InnerText; DocuSignStatus status; if (!Enum.TryParse(statusString, true, out status)) { throw new Exception("DocuSign webhook unknown status: " + statusString); } Global.Logger.Info("DocuSign webhook: " + envelopeId + " " + subject + " " + status); var customFieldUserIdNode = GetSingleNode(envelopeStatusNode, "CustomFields/" + XmlPrefix + ":CustomField[" + XmlPrefix + ":Name='" + DocuSignHelper.UserField + "']", mgr); var userIdString = GetSingleNode(customFieldUserIdNode, "Value", mgr).InnerText; Auth(userIdString); switch (status) { case DocuSignStatus.Completed: var documentStatuses = GetSingleNode(envelopeStatusNode, "DocumentStatuses", mgr); foreach (XmlNode documentStatus in documentStatuses.ChildNodes) { try { var documentId = GetSingleNode(documentStatus, "ID", mgr).InnerText; var documentName = GetSingleNode(documentStatus, "Name", mgr).InnerText; string folderId = null; string sourceTitle = null; var documentFiels = GetSingleNode(documentStatus, "DocumentFields", mgr, true); if (documentFiels != null) { var documentFieldFolderNode = GetSingleNode(documentFiels, "DocumentField[" + XmlPrefix + ":Name='" + FilesLinkUtility.FolderId + "']", mgr, true); if (documentFieldFolderNode != null) { folderId = GetSingleNode(documentFieldFolderNode, "Value", mgr).InnerText; } var documentFieldTitleNode = GetSingleNode(documentFiels, "DocumentField[" + XmlPrefix + ":Name='" + FilesLinkUtility.FileTitle + "']", mgr, true); if (documentFieldTitleNode != null) { sourceTitle = GetSingleNode(documentFieldTitleNode, "Value", mgr).InnerText; } } var file = DocuSignHelper.SaveDocument(envelopeId, documentId, documentName, folderId); NotifyClient.SendDocuSignComplete(file, sourceTitle ?? documentName); } catch (Exception ex) { Global.Logger.Error("DocuSign webhook save document: " + documentStatus.InnerText, ex); } } break; case DocuSignStatus.Declined: case DocuSignStatus.Voided: var statusFromResource = status == DocuSignStatus.Declined ? FilesCommonResource.DocuSignStatusDeclined : FilesCommonResource.DocuSignStatusVoided; NotifyClient.SendDocuSignStatus(subject, statusFromResource); break; } } catch (Exception e) { Global.Logger.Error("DocuSign webhook", e); throw new HttpException((int)HttpStatusCode.BadRequest, e.Message); } }
public void Execute(XmlNode node) { ErrorLog.Write("start go WXOrderCheckJob"); WriteBackOrders(); // 取支付方式 partners = GetWxPayPartners(); IDictionary <string, string> orders = ShoppingProcessor.GetWxPayingOrder(); if (orders.Count == 0) { return; } StringBuilder sb = new StringBuilder(); foreach (var order in orders) { sb.Append(order.Key); } ErrorLog.Write(sb.ToString()); masterSettings = SettingsManager.GetMasterSettings(false); NotifyClient notifyClient = null; WxPayPartner partner = null; foreach (var order in orders) { ErrorLog.Write("开始准备请求微信服务器"); string orderId = order.Key; string gateway = order.Value.ToLower(); partner = null; if (!partners.TryGetValue(gateway, out partner)) { ErrorLog.Write("找不到支付网关信息:" + gateway); continue; } string payOrderInfo = LoadWXHadPayOrder(orderId, partner); ErrorLog.Write(payOrderInfo); notifyClient = new NotifyClient(partner.AppId, partner.AppSecret, partner.PartnerId, partner.PartnerKey, partner.SignKey); OrderNotify orderNotify = notifyClient.GetOrderStatusNotify(payOrderInfo); if (orderNotify != null) { if (orderNotify.result_code == "SUCCESS" && !string.IsNullOrEmpty(orderNotify.transaction_id)) { //UpdateOrder(orderNotify); OrderInfo orderInfo = ShoppingProcessor.GetOrderInfo(orderId); orderInfo.GatewayOrderId = orderNotify.transaction_id; DateTime payDate = DateTime.MinValue; DateTime.TryParseExact(orderNotify.time_end, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out payDate); orderInfo.PayDate = payDate; if (orderInfo != null) { PayOrder(orderInfo); ErrorLog.Write(string.Format("用户已支付成功,检测到的未即时回写订单状态的订单{0}使用jobs回写状态!", orderNotify.out_trade_no)); } } } } }
protected void Page_Load(object sender, System.EventArgs e) { ErrorLog.Write("进入微信扫码支付回调(wx_PayQRcode_notify_url) ..."); //// 看原始NotifyData //string notifyData = "空"; //if (base.Request.InputStream != null) //{ // byte[] array = new byte[base.Request.InputStream.Length]; // base.Request.InputStream.Read(array, 0, array.Length); // notifyData = Encoding.UTF8.GetString(array); //} //ErrorLog.Write("微信扫码回调原始数据(wx_PayQRcode_notify_url) :" + notifyData); PaymentModeInfo paymentMode = SalesHelper.GetPaymentMode("Ecdev.plugins.payment.WxpayQrCode.QrCodeRequest"); string AppId = ""; string Key = ""; string AppSecret = ""; string MchId = ""; if (paymentMode != null) { if (paymentMode.Settings != "") { string xml = HiCryptographer.Decrypt(paymentMode.Settings); try { System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.LoadXml(xml); AppId = xmlDocument.GetElementsByTagName("AppId")[0].InnerText; Key = xmlDocument.GetElementsByTagName("Key")[0].InnerText; AppSecret = xmlDocument.GetElementsByTagName("AppSecret")[0].InnerText; MchId = xmlDocument.GetElementsByTagName("MchId")[0].InnerText; } catch { AppId = ""; Key = ""; AppSecret = ""; MchId = ""; ErrorLog.Write("微信扫码回调原始数据(wx_PayQRcode_notify_url) ,支付未配置"); } } } NotifyClient notifyClient = new NotifyClient(AppId, AppSecret, MchId, Key, ""); payNotify = notifyClient.GetPayNotify(base.Request.InputStream); if (payNotify == null) { ErrorLog.Write("微信扫码回调原始数据(wx_PayQRcode_notify_url) ,数据为空"); return; } this.OrderId = payNotify.PayInfo.OutTradeNo; this.Order = ShoppingProcessor.GetOrderInfo(this.OrderId); if (this.Order == null) { ErrorLog.Write(string.Format("微信扫码回调原始数据(wx_PayQRcode_notify_url) ,订单不存在,订单号:{0}", this.OrderId)); base.Response.Write("success"); return; } this.Order.GatewayOrderId = payNotify.PayInfo.TransactionId; this.UserPayOrder(); }
public async Task <GetNotificationAPIResult> GetNotificationAsync(string AccountID, string Signature) { //verify signature here NotifyClient nc; if (_peers.ContainsKey(AccountID)) { nc = _peers[AccountID]; } else { nc = new NotifyClient() { AccountID = AccountID }; _peers.Add(AccountID, nc); } nc.Source = NotifySource.None; nc.ExtInfo = string.Empty; nc.tcs = new TaskCompletionSource <bool>(false); GetNotificationAPIResult result; try { await Task.WhenAny(nc.tcs.Task, Task.Delay(5 * 60 * 1000)); if (nc.tcs.Task.IsCompleted) { // has notify result = new GetNotificationAPIResult() { ResultCode = APIResultCodes.Success, HasEvent = true, Action = nc.Action, Catalog = nc.Catalog, ExtraInfo = nc.ExtInfo, Source = nc.Source }; } else { // no notify, just timeout result = new GetNotificationAPIResult() { ResultCode = APIResultCodes.Success, HasEvent = false, Source = NotifySource.None }; } } catch (Exception) { // network timeout etc. result = new GetNotificationAPIResult() { ResultCode = APIResultCodes.UnknownError, HasEvent = false, Source = NotifySource.None }; } finally { if (_peers.ContainsKey(AccountID)) { _peers.Remove(AccountID); } } return(result); }
private static string ProcessMailMerge(string fileId, TrackerData fileData) { Guid userId; if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } var sended = false; try { SecurityContext.AuthenticateMe(userId); if (string.IsNullOrEmpty(fileData.Url)) { throw new ArgumentException("emptry url"); } if (fileData.MailMerge == null) { throw new ArgumentException("MailMerge is null"); } var message = fileData.MailMerge.Message; Stream attach = null; switch (fileData.MailMerge.Type) { case MailMergeType.AttachDocx: case MailMergeType.AttachPdf: var downloadRequest = (HttpWebRequest)WebRequest.Create(fileData.Url); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var downloadStream = new ResponseStream(downloadRequest.GetResponse())) { const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; attach = new MemoryStream(); while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { attach.Write(buffer, 0, readed); } attach.Position = 0; } if (string.IsNullOrEmpty(fileData.MailMerge.Title)) { fileData.MailMerge.Title = "Attach"; } var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf"; var curExt = FileUtility.GetFileExtension(fileData.MailMerge.Title); if (curExt != attachExt) { fileData.MailMerge.Title += attachExt; } break; case MailMergeType.Html: var httpWebRequest = (HttpWebRequest)WebRequest.Create(fileData.Url); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) using (var stream = httpWebResponse.GetResponseStream()) if (stream != null) { using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName))) { message = reader.ReadToEnd(); } } break; } using (var mailMergeTask = new MailMergeTask { From = fileData.MailMerge.From, Subject = fileData.MailMerge.Subject, To = fileData.MailMerge.To, Message = message, AttachTitle = fileData.MailMerge.Title, Attach = attach }) { var response = mailMergeTask.Run(); Global.Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}", fileData.MailMerge.RecordIndex, fileData.MailMerge.RecordCount, response); } sended = true; } catch (Exception ex) { Global.Logger.Error( string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}", (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount), userId, fileData.Url), ex); } if (fileData.MailMerge != null && fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1) { var errorCount = fileData.MailMerge.RecordErrorCount; if (!sended) { errorCount++; } NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount, errorCount); } return(sended ? "0" //error:0 - sended : "1"); //error:1 - some error }
protected void Page_Load(object sender, EventArgs e) { this.nPram = new NameValueCollection { base.Request.QueryString, base.Request.Form }; SiteSettings masterSettings = SettingsManager.GetMasterSettings(); NotifyClient notifyClient = null; notifyClient = ((string.IsNullOrEmpty(masterSettings.Main_Mch_ID) || string.IsNullOrEmpty(masterSettings.Main_AppId)) ? new NotifyClient(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret, masterSettings.WeixinPartnerID, masterSettings.WeixinPartnerKey, masterSettings.WeixinPaySignKey, "", "") : new NotifyClient(masterSettings.Main_AppId, masterSettings.WeixinAppSecret, masterSettings.Main_Mch_ID, masterSettings.WeixinPartnerKey, masterSettings.WeixinPaySignKey, masterSettings.WeixinAppId, masterSettings.WeixinPartnerID)); PayNotify payNotify = notifyClient.GetPayNotify(base.Request.InputStream); if (payNotify == null) { if (masterSettings.OpenO2OAppletWxPay) { notifyClient = new NotifyClient(masterSettings.O2OAppletAppId, masterSettings.O2OAppletAppSecrect, masterSettings.O2OAppletMchId, masterSettings.O2OAppletKey, "", "", ""); payNotify = notifyClient.GetPayNotify(base.Request.InputStream); } if (payNotify == null && masterSettings.OpenWxAppletWxPay) { notifyClient = new NotifyClient(masterSettings.WxAppletAppId, masterSettings.WxAppletAppSecrect, masterSettings.WxApplectMchId, masterSettings.WxApplectKey, "", "", ""); payNotify = notifyClient.GetPayNotify(base.Request.InputStream); } if (payNotify == null) { Globals.AppendLog(this.nPram, "获取通知信息错误", "", "wxPay", ""); return; } } this.OrderId = payNotify.PayInfo.OutTradeNo; this.Order = ShoppingProcessor.GetOrderInfo(this.OrderId); if (this.Order == null && !string.IsNullOrEmpty(payNotify.PayInfo.OutTradeNo)) { Globals.AppendLog(this.nPram, "订单ID错误", this.OrderId, "wxPay", ""); this.Order = ShoppingProcessor.GetOrderInfo(payNotify.PayInfo.OutTradeNo); } if (this.Order == null) { Globals.AppendLog(this.nPram, "订单ID错误", payNotify.PayInfo.OutTradeNo, "wxPay", ""); this.ResponseReturn(true, ""); } else { this.hasNotify = !string.IsNullOrEmpty(this.Order.GatewayOrderId); if (this.Order.PreSaleId > 0 && this.Order.DepositGatewayOrderId.ToNullString() == payNotify.PayInfo.TransactionId) { this.ResponseReturn(true, ""); } else { if ((this.Order.PreSaleId > 0 && !this.Order.DepositDate.HasValue) || this.Order.DepositGatewayOrderId.ToNullString() == payNotify.PayInfo.TransactionId) { this.Order.DepositGatewayOrderId = payNotify.PayInfo.TransactionId; } else { this.Order.GatewayOrderId = payNotify.PayInfo.TransactionId; } this.UserPayOrder(); } } }