public Dictionary <string, StaffDto> GetUserByEmail(int tenantId, int userId, IEnumerable <string> emailList) { var result = new Dictionary <string, StaffDto>(); if (!emailList.Any()) { return(result); } var provider = StaffService.Instance; if (provider != null) { var res = provider.GetStaffsByEmails(new StaffsGetByEmailsArgs() { TenantId = tenantId, OperatorId = userId, Emails = emailList.ToArray() }).Items; if (res != null && res.Any()) { foreach (var data in res) { result.AddOrUpdate(data.Email, data); } } } else { AppConnectLogHelper.Error("UserFramework接口实例化失败"); throw new Exception("UserFramework接口实例化失败"); } return(result); }
/// <summary> /// 创建provider实例 /// </summary> /// <typeparam name="TProvider"></typeparam> /// <returns></returns> public static TProvider GetProvider <TProvider>() where TProvider : class { try { string typeName = typeof(TProvider).FullName; AppConnectProvider providerConfig = GetProviderConfig(typeName); if (!Repositories.ContainsKey(providerConfig.TypeName)) { Type providerType = Type.GetType(providerConfig.TypeName); if (providerType == null) { throw new ArgumentException(typeName, typeName + " provider is null "); } var bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty; var provider = providerType.InvokeMember("Instance", bindingFlags, null, null, null) as TProvider; //var provider = Activator.CreateInstance(providerType) as TProvider; Repositories[providerConfig.TypeName] = provider; return(provider); } return(Repositories[providerConfig.TypeName] as TProvider); } catch (Exception ex) { AppConnectLogHelper.Error("创建provider实例出错", ex); return(null); } }
private static ObjectData IsExistLogin(int tenantId, AppUserAccountInfo appUserAccountInfo) { ApplicationContext.Current.ApplicationName = AppUserConstants.MetaName; ApplicationContext.Current.TenantId = tenantId; ApplicationContext.Current.UserId = appUserAccountInfo.UserId; ObjectData objectData = new ObjectData(); var filter = new BooleanFilter() .Must(new TermFilter(AppUserConstants.AppUser_AppId, appUserAccountInfo.AppId)) .Must(new TermFilter(AppUserConstants.AppUser_OpenId, appUserAccountInfo.OpenId)); // .Must(new TermFilter(AppUserConstants.AppUser_UserId, appUserAccountInfo.UserId)); var result = CloudDataHelper.GetEntityAllList("AppConnect.AppUser", tenantId, filter).ToList(); if (result != null && result.Count > 0) { if (result.Count > 1) { AppConnectLogHelper.Error("AppId下面的OpenId个数大于一个!appUserAccountInfo:" + JsonConvert.SerializeObject(appUserAccountInfo)); objectData = null; } else { objectData = result.First(); } } else { objectData = null; } return(objectData); }
public JsonResult _Bind(string batch, int type, string username, string password = "", string captcha = "") { try { var result = ProviderGateway.AppUserAccountProvider.Bind(CookieHelper.GetCookie().OpenIds, batch, (ServiceInterface.Model.Enum.AppUserAccountType)type, username, password, captcha); AppConnectLogHelper.Debug("Bind返回值DEBUG" + JsonConvert.SerializeObject(result)); return(Json(new WebApiResult <WebApiBindResult> { Code = result.Result, Message = result.Message, Data = new WebApiBindResult { NeedCaptcha = result.NeedCaptcha, RedirectUrl = result.RedirectUrl } })); } catch (System.Exception ex) { AppConnectLogHelper.Error("_Bind异常信息" + ex.Message + "EX:", ex); return(Json(new WebApiResult <WebApiBindResult> { Code = 417, Message = ex.Message, Data = new WebApiBindResult() })); } }
protected void Application_Error(object sender, EventArgs e) { if (Context != null && Context.AllErrors != null) { var url = Context.Request.Url.ToString(); //var text = new StringBuilder(); //text.Append("Request.Browser.MajorVersion:"+Request.Browser.MajorVersion); //text.AppendLine(); //text.Append("Request.Browser.Platform:" + Request.Browser.Platform); //text.AppendLine(); //text.Append("Request.UserHostAddress:" + Request.UserHostAddress); //text.AppendLine(); //text.Append("Request.Url:" + Request.Url); //text.AppendLine(); //text.Append("Request.UrlReferrer:" + Request.UrlReferrer); //text.AppendLine(); //text.Append("Request.UserAgent:" + Request.UserAgent); //text.AppendLine(); //text.Append("Request.UserHostAddress:" + Request.UserHostAddress); //text.AppendLine(); //text.Append("Request.UserHostName :" + Request.UserHostName); //text.AppendLine(); //text.Append("Request.UserLanguages :" + Request.UserLanguages); //AppConnectLogHelper.Error(string.Format("[TestLog][{0}]", text.ToString())); foreach (var error in Context.AllErrors) { AppConnectLogHelper.Error(string.Format("[Application_Error][{0}]", url), error); } } }
/// <summary> /// 根据userId获取员工信息 /// </summary> /// <param name="tenantId"></param> /// <param name="userId"></param> /// <returns></returns> public StaffDto GetByTenantIdAndUserId(int tenantId, int userId) { var args = new StaffsGetByIdsArgs { TenantId = tenantId, UserIds = new int[] { userId } }; var options = QueryOptions.Default; options.IgnoreOperator = true; try { var provider = Beisen.UserFramework.Service.StaffService.Instance; // var provider = PlatformServiceFactory<UserFramework.ESB.ServiceInterface.IStaffProvider>.Instance(); if (provider == null) { AppConnectLogHelper.Error(new ESBServiceNotFoundException("UserFramework ESB Service Is null")); return(null); } var result = provider.GetStaffByIds(args, options); if (result.Code != 200) { throw new UserOperateException(string.Format("Code:{0},Message:{1}", result.Code, result.Message)); } return(result.Total > 0 ? result.Items[0] : null); } catch (System.Exception ex) { AppConnectLogHelper.Error(ex.Message, new UserOperateException(string.Format("根据租户id和userid获取用户信息失败,接口:StaffService.Instance.GetStaffByIds,参数:tenantId {0},userId {1}", tenantId, userId), ex)); return(null); } }
/// <summary> /// 根据NodeType和Key从远程配置中读取配置信息 /// </summary> /// <typeparam name="T">返回值的类型</typeparam> /// <param name="nodeType">节点类型</param> /// <param name="key">节点的Key</param> /// <returns>节点的Value</returns> public static T GetAppconnectConfigInfo <T>(string nodeType, string key) { if (appconnectConfigInfo.Count <= 0 || !appconnectConfigInfo.ContainsKey(nodeType)) { AppConnectLogHelper.Error(string.Format("为获取到远程配置信息AppconnectConfig,NodeType{0}", nodeType)); return(default(T)); } if (!appconnectConfigInfo[nodeType].ContainsKey(key)) { AppConnectLogHelper.Error(string.Format("为获取到远程配置信息AppconnectConfig,NodeType{0}, Key:{1}", nodeType, key)); return(default(T)); } Add item = appconnectConfigInfo[nodeType][key]; object res; switch (typeof(T).ToString()) { case "System.String": res = item.Value; break; case "System.Int32": res = int.Parse(item.Value); break; case "System.Boolean": res = Convert.ToBoolean(item.Value); break; default: res = item.Value; break; } return((T)(res)); }
/// <summary> /// 校验用户名是否存在 /// </summary> /// <param name="userName"></param> /// <returns></returns> public bool CheckUserNameExist(string userName) { try { // var provider = PlatformServiceFactory<IAccountProvider>.Instance(); var provider = AccountService.Instance; if (provider == null) { AppConnectLogHelper.Error(new ESBServiceNotFoundException("UserFramework ESB Service Is null")); return(false); } var args = new LoginNameCheckNotTakenArgs { LoginName = userName }; var result = provider.CheckLoginNameNotTaken(args); return(!result.Ok); } catch (System.Exception ex) { AppConnectLogHelper.Error(ex.Message, new UserOperateException(string.Format("校验UserName失败,接口:AccountService.Instance.CheckLoginNameNotTaken,参数:userName:{0}", userName), ex)); return(false); } }
public string ExportExcelTemplate() { var tenantId = ApplicationContext.Current.TenantId; var userId = ApplicationContext.Current.UserId; var path = string.Empty; try { //设置Excel表头 var templateData = AppAccountService.Instance.GetTemplateStream(tenantId, userId); if (templateData.Length == 0) { //error AppConnectLogHelper.Error("生成模板失败,文件数据流为null"); return(path); } var dfsItem = new DfsItem("AppConnectFile", "人员信息模板表.xls", templateData, tenantId); var dfsPath = Dfs.Store(dfsItem); path = Dfs.ToDownloadUrl(dfsPath.ToString(), UrlSignDomain.Tms, userId); ApplicationContext.Current.Put(Const.BeisenContextXHasException, ExceptionType.UrlRedirect); ApplicationContext.Current.Put(Const.BeisenContextXExResultModel, new ResultModel { code = "302", message = "url redirect", param = path }); } catch (Exception ex) { AppConnectLogHelper.Error("生成模板失败", ex); } return(path); }
/// <summary> /// 增加开放平台帐号信息 /// </summary> /// <param name="tenantId"></param> /// <param name="info"></param> /// <param name="isSaveMultiTenant"></param> public string Add(int tenantId, AppAccountInfo info, bool isSaveMultiTenant = true) { ArgumentHelper.AssertIsTrue(tenantId > 0, "TenantId is 0"); ArgumentHelper.AssertIsTrue(info != null, "AppAccountInfo is null"); ArgumentHelper.AssertIsTrue(info.TenantId > 0, "AppAccountInfo.TenantId is 0"); ArgumentHelper.AssertNotNullOrEmpty(info.Name, "AppAccountInfo.AppAccountName is null or empty"); ArgumentHelper.AssertNotNullOrEmpty(info.AppId, "AppAccountInfo.AppId is null or empty"); ArgumentHelper.AssertNotNullOrEmpty(info.AppSecret, "AppAccountInfo.AppSecret is null or empty"); AppAccountDao.Insert(info); if (isSaveMultiTenant && info.TenantId > 1) { try { AppAccountDao.SaveMultiTenant(info); } catch (Exception ex) { AppConnectLogHelper.Error("保存多租赁信息出错,AppAccountId=" + info.AppAccountId, ex); } } return(info.AppAccountId); }
protected string GetOpenId(AppAccountInfo appAccount, string code) { var extend = new Dictionary <string, string> { { TemplateConst.ExtendCode, code }, { TemplateConst.ExtendToken, ProviderGateway.TokenProvider.GetToken(appAccount) } }; var requestTemplate = new DefaultApiTemplate(appAccount, TemplateConst.GetOpenId, extend); //TODO:这块会出现空引用需要加一下判断 var openId = requestTemplate.GetResponse()[TemplateConst.OpenId]; if (string.IsNullOrWhiteSpace(openId)) { var message = string.Format("未获取到OpenId:tenantId={0},appAccountId={1},code={2}", appAccount.TenantId, appAccount.Id, code); AppConnectLogHelper.Error(message); throw new SDKResultException(message); } var cookie = CookieHelper.GetCookie(); if (cookie.OpenIds == null) { cookie.OpenIds = new Dictionary <string, string>(); } cookie.OpenIds.Add(appAccount.AppId, openId); CookieHelper.SetCookie(cookie); return(openId); }
private bool DispatcherService(bool boot) { bool succeed = true; IConsumerPipeline instance = ConsumerPipeline.Instance; foreach (var consumer in instance.GetConsumer()) { try { if (boot) { consumer.ActiveService(); } else { consumer.UnActiveService(); } } catch (Exception ex) { AppConnectLogHelper.Error("appconnect 消息队列" + consumer.GetType().Name + " failed in Dispatch " + Newtonsoft.Json.JsonConvert.SerializeObject(ex)); succeed = false; } } return(succeed); }
public override MessageResult OnMessage(MessageContext context) { if (context == null) { AppConnectLogHelper.Error("AppConnect context is null , process finished"); return(Ack()); } try { #region 处理前的校验 if (context.Data == null)//消息体为空 { AppConnectLogHelper.Error("AppConnect context.Data is null , process finished"); return(Ack()); } var messageFiledList = Convert.ToString(context.Data).Trim('\"').Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (messageFiledList == null || messageFiledList.Count() < 3) { AppConnectLogHelper.Error("处理消息时 消息结构不完整 , process finished"); return(Ack()); } AccountStaffMessage empMessage = new AccountStaffMessage { TenantId = Convert.ToInt32(messageFiledList[0]), NotifyType = (AccountNotifyType)(Convert.ToInt32(messageFiledList[1])), UserId = Convert.ToInt32(messageFiledList[2]) }; AppConnectLogHelper.Debug("Account Staff的消息" + JsonConvert.SerializeObject(empMessage)); #endregion switch (empMessage.NotifyType) { //account账号停用,离职,删除 case AccountNotifyType.DisableUserStatus: case AccountNotifyType.DisableStaffStatus: case AccountNotifyType.DeleteStaff: //AppConnectLogHelper.Error("分发rbmq 未使用ActionBlock方法作为缓冲"); //var provider = new DimissionRecordExcuter(empMessage); //provider.Excute(); AppConnectLogHelper.Error("分发rbmq 使用本地的ActionBlock方法作为缓冲"); if (!_asyncHandleQueue.Post(new DimissionRecordExcuter(empMessage))) { return(Reject()); } break; default: AppConnectLogHelper.Debug("AppConnect MessageHandler 未订阅的消息类型 . Json :" + JsonConvert.SerializeObject(empMessage)); break; } } catch (Exception ex) { AppConnectLogHelper.Error("AppConnect MessageHandler 处理出现异常 . Json :" + JsonConvert.SerializeObject(ex)); } return(Ack()); }
public static string SendEmail(int tenantId, string emailSubject, string fromUser, string toUsers, string body, bool isBodyHtml = true, EmailType emailType = EmailType.Normal) { Beisen.BeisenUser.BeisenTenant beisenTenant = null; if (tenantId != 0) { beisenTenant = BeisenUser.ServiceImp.BeisenUserGateway.BeisenTenantProvider.GetTenantById(tenantId); } var smsMailProvider = PlatformServiceFactory <ISMSMailProvider> .Instance(); if (smsMailProvider == null) { AppConnectLogHelper.Error("SMSMailProvider实例化错误"); return(string.Empty); } var batch = new MailBatch { SystemId = _systemId, TenantId = beisenTenant != null ? beisenTenant.ID : 0, EMailType = emailType, TenantName = beisenTenant != null ? beisenTenant.Name : "北森" }; var to = new MailAddressCollection(); to.Add(new MailAddress(toUsers, toUsers)); var msg = new MailMessage { From = new MailAddress(_virtualFromEmail, "iTalent"), To = to, //ReplyTo = new MailAddressCollection() //{ // new MailAddress() // { // DisplayName = "iTalent", // Address = _virtualFromEmail // } //}, Subject = emailSubject, Body = body, IsBodyHtml = isBodyHtml, Priority = MailPriority.Normal }; batch.MailMessages.Add(msg); var result = smsMailProvider.Mail_SendMailByBatch(batch); if (Enum.IsDefined(typeof(RequestStatus), result)) { AppConnectLogHelper.Error(string.Format("发送邮件失败:result={0},toUsers={1}", result, string.Join("|", toUsers))); return(string.Empty); } return(result); }
protected void Application_Error(object sender, EventArgs e) { if (Context != null && Context.AllErrors != null) { var url = Context.Request.Url.ToString(); foreach (var error in Context.AllErrors) { AppConnectLogHelper.Error(string.Format("[Application_Error][{0}]", url), error); } } }
/// <summary> /// 记录请求日志 /// </summary> /// <param name="url"></param> /// <param name="method"></param> /// <param name="body"></param> /// <param name="response"></param> /// <param name="message"></param> internal static void Add(string url, string method, string body, string response, string message = null) { try { RequestLogDao.Insert(url, method, body, response, message); } catch (Exception ex) { AppConnectLogHelper.Error("记录请求日志错误", ex); } }
public static int ValidateByEmail(string email, string password) { try { return(BeisenUserGateway.UserSecurityProvider.ValidateByEmai(email, password, false)); } catch (Exception ex) { AppConnectLogHelper.Error(string.Format("BeisenUserProxy.ValidateByEmail error:email={0},message:{1}", email, ex.Message)); throw; } }
public static int GetTenantId(int userId) { try { return(UserLiteProvider.Instance.GetUserLiteByID(userId).TenantID); } catch (Exception ex) { AppConnectLogHelper.Error(string.Format("BeisenUserProxy.GetTenantId error:userid={0},message:{1}", userId, ex.Message)); throw; } }
public static int GetSecurityByUserName(string userName) { try { return(BeisenUserGateway.UserSecurityProvider.GetSecurityByUserName(userName)); } catch (Exception ex) { AppConnectLogHelper.Error(string.Format("BeisenUserProxy.GetUserEmail error:userName={0},message:{1}", userName, ex.Message)); throw; } }
public static List <UserLite> GetUserLiteByUserIds(int tenantId, List <int> userIds) { try { return(UserLiteProvider.Instance.GetUserLiteByUserIds(tenantId, userIds)); } catch (Exception ex) { AppConnectLogHelper.Error(string.Format("BeisenUserProxy.GetUserLiteByUserIds error:tenantId={0},userid={1},message:{2}", tenantId, string.Join(",", userIds), ex.Message)); throw; } }
public ActionResult Image(string code, int size = 320, int tenant_id = 0, string appaccount_id = "", int type = 12) { ArgumentHelper.AssertNotNullOrEmpty(code, "code is null or empty"); AppConnectLogHelper.DebugFormat("调用Image方法:code:{0}", code); var file = ProviderGateway.QrCodeLoginProvider.GenerateQrCodePicture(tenant_id, appaccount_id, type, code, size); if (file == null || file.Length <= 0) { AppConnectLogHelper.Error("file stream is null"); } return(File(file, "image/png")); }
/// <summary> /// 创建员工 /// </summary> /// <returns></returns> public int CreateStaff(RegisterUserInfo info, int operatorId = 0) { var args = new StaffCreateArgs { TenantId = info.TenantId, Origin = (int)RegisterOriginState.WeChat, Staff = new Staff { Email = info.Email, Name = info.Name, Mobile = info.Mobile, WorkPhone = info.WorkPhone, Position = info.Position, Hobbies = info.DepartmentName, EmployedDate = DateTime.Now }, Account = new Account { UserName = info.RegisterType == 1 ? null : info.Email, Password = info.Password, BindingMobile = info.RegisterType == 1 ? info.Mobile : null }, OperatorId = 0 }; var options = StaffCreateOptions.CreateAccountAndActivate; options.IgnoreOperator = operatorId == 0; options.UseVirtualUserName = info.RegisterType == 1; try { var provider = Beisen.UserFramework.Service.StaffService.Instance; // var provider = PlatformServiceFactory<UserFramework.ESB.ServiceInterface.IStaffProvider>.Instance(); if (provider == null) { AppConnectLogHelper.Error(new ESBServiceNotFoundException("UserFramework ESB Service Is null")); return(0); } var result = provider.CreateStaff(args, options); if (!result.Ok) { throw new UserOperateException(string.Format("Message:{0}", result.Error.Message)); } return(result.State); } catch (System.Exception ex) { AppConnectLogHelper.Error(ex.Message, new UserOperateException("创建员工失败,接口:StaffService.Instance.CreateStaff", ex)); return(0); } }
/// <summary> /// 保存缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> public static void SaveEntityInstanceToCache <T>(T instance) where T : IAppConnectExtendedSerializableEntity, new() { try { if (instance.IsEnable) { EntityProcedure.SaveEntityInstanceToCache(instance); } } catch (Exception exception) { AppConnectLogHelper.Error(exception); } }
/// <summary> /// 保存缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instances"></param> public static void SaveEntityInstanceListToCache <T>(IList <T> instances) where T : IAppConnectExtendedSerializableEntity, new() { try { if (instances != null && instances.Count > 0 && instances[0].IsEnable) { EntityProcedure.SaveEntityInstanceListToCache(instances); } } catch (Exception exception) { AppConnectLogHelper.Error(exception); } }
/// <summary> /// 删除缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> public static void DeleteEntityFromCacheByPrimaryId <T>(T instance) where T : IAppConnectExtendedSerializableEntity, new() { try { if (instance.IsEnable) { EntityProcedure.DeleteEntityFromCache <T>(instance.PrimaryId); } } catch (Exception exception) { AppConnectLogHelper.Error(exception); } }
/// <summary> /// 发送ISV手机验证码(只有发送验证码可用,发送其他短信不要用此接口) /// </summary> public bool SendISVMobileValCode(int tenantId, string isv, string channelId, string content, string toPhone, SMSType type, string templateMessageText) { if (string.IsNullOrEmpty(channelId)) { AppConnectLogHelper.Error(new SMSSendException("短信通道未配置")); return(false); } var smsInvokeProvider = PlatformServiceFactory <ISMSMailProvider> .Instance(); if (smsInvokeProvider == null) { AppConnectLogHelper.Error(new ESBServiceNotFoundException("SMS ESB Service Is null")); return(false); } var smsBatch = new SMSBatch(); var shortMessages = new List <ShortMessage>() { new ShortMessage() { PhoneNumber = toPhone, MessageText = content, TemplateMessageText = templateMessageText } }; var messageCollection = new MessageCollection(shortMessages.ToArray()); smsBatch.SystemId = channelId; if (tenantId == 0) { tenantId = 2; } smsBatch.TenantId = tenantId; smsBatch.TenantName = "ISV业务短信"; smsBatch.ShortMessages = messageCollection; smsBatch.UserId = 0; ArgumentHelper.IsValid(smsBatch, true); var sendInfo = smsInvokeProvider.SMS_SendSMSByTime(smsBatch); bool isSuccess = CheckResult(sendInfo); if (isSuccess) { return(true); } AppConnectLogHelper.Error("短信发送失败:" + sendInfo); return(false); }
protected override TokenInfo GetTokenFromSDk(AppAccountInfo account) { var token = WeChatSDK.Work.Token.GetToken(account.AppId, account.AppSecret); if (string.IsNullOrWhiteSpace(token.AccessToken)) { var ex = new SDKResultException(string.Format("未获取到企业微信AccessToken:AppId={0},AppSecret={1},ErrCode={2},ErrMsg={3}", account.AppId, account.AppSecret, token.ErrCode, token.ErrMsg)); AppConnectLogHelper.Error(ex); throw ex; } return(new TokenInfo { AppId = account.AppId + account.AppSecret, AccessToken = token.AccessToken, ExpireTime = DateTime.Now.AddSeconds(token.ExpiresIn) }); }
protected override TokenInfo GetTicketFromSDk(AppAccountInfo account, string token, string ticketType) { var ticket = DingTalkSDK.JsApi.GetTicket(token); if (string.IsNullOrWhiteSpace(ticket.Ticket)) { var ex = new SDKResultException(string.Format("未获取到钉钉Ticket:AppId={0},AppSecret={1},TicketType={2},ErrCode={3},ErrMsg={4}", account.AppId, account.AppSecret, ticketType, ticket.ErrCode, ticket.ErrMsg)); AppConnectLogHelper.Error(ex); throw ex; } return(new TokenInfo { AppId = account.AppId + account.AppSecret + ticketType, AccessToken = ticket.Ticket, ExpireTime = DateTime.Now.AddSeconds(ticket.ExpiresIn) }); }
/// <summary> /// 生成二维码登录 /// </summary> /// <returns></returns> public string GenerateQrCode(int titaAppId) { var checkResult = ProviderGateway.AuthorizeProvider.CheckApp(titaAppId, ""); if (!checkResult) { AppConnectLogHelper.Error("GenerateQrCode--检查app失败"); return(null); } var qrCodeLoginInfo = new QrCodeLoginInfo { Code = Guid.NewGuid().ToString(), TitaAppId = titaAppId }; Add(qrCodeLoginInfo); return(qrCodeLoginInfo.Code); }
/// <summary> /// 获取缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> /// <returns></returns> public static T GetEntityInstanceFromCacheByExtendedId <T>(T instance) where T : IAppConnectExtendedSerializableEntity, new() { try { if (instance.IsEnable) { var item = EntityProcedure.GetEntityInstanceFromCache <T>(instance.ExtendedId); if (item == null || item.IsEmpty) { return(default(T)); } return(item); } } catch (Exception exception) { AppConnectLogHelper.Error(exception); } return(default(T)); }