public void UnAuthenticatedCallShouldFail() { var api = new UserApi(GitHubUrl); var user = api.GetUser("sgrassie"); Assert.That(user.DiskUsage, Is.EqualTo(0)); }
public void Should_Get_List_Of_Following() { var api = new UserApi(GitHubUrl); var user = api.GetUser("sgrassie"); api.GetFollowing(user).Count.Should().BeGreaterThan(0); }
public GeneralApiResult<UserDto> Login(string userName, string password) { IUserApi userApi = new UserApi(); var funcResult = userApi.Login(userName, password); var model = new GeneralApiResult<UserDto>(); model.Data = funcResult.ReturnValue; model.Message = funcResult.Info; model.Result = funcResult.Status; return model; }
public void Should_Follow_And_Unfollow_User() { var api = new UserApi(GitHubUrl).WithAuthentication(ObjectFactory.GetInstance<IAuthenticator>()); var user = api.GetUser("sgrassie"); api.Follow("mono").Should().BeTrue("should follow the user mono"); api.GetFollowing(user).Should().Contain(x => x.Login == "mono"); api.UnFollow("mono").Should().BeTrue("Should unfollow the user mono"); api.GetFollowing(user).Should().NotContain(x => x.Login == "mono"); }
public void SendTemplateMessageTestForBookOptmize() { var openId = "olPjZjsXuQPJoV0HlruZkNzKc91E";//消息目标用户的OpenId //实际生产环境中,用户信息应该从数据库或缓存中读取 var userInfo = UserApi.Info(_appId, openId); var data = new TemplateMessage_PaySuccessNotice( "您的订单已经支付", userInfo.nickname, "1234567890", 88.ToString("c"), "模板消息测试商品", "更详细信息,请到Senparc.Weixin SDK官方网站(https://sdk.weixin.senparc.com)查看!\r\n这条消息使用的是优化过的方法,且不带Url参数。"); var result = TemplateApi.SendTemplateMessage(_appId, openId, data); Assert.AreEqual(ReturnCode.请求成功, result.errcode); }
public static object fetchUserProfile(string userId) { return(new ThunkAction <AppState>((dispatcher, getState) => { return UserApi.FetchUserProfile(userId: userId) .Then(userProfileResponse => { dispatcher.dispatch <IPromise>( fetchUserArticle(userId: userProfileResponse.user.id, 1)); dispatcher.dispatch(new PlaceMapAction { placeMap = userProfileResponse.placeMap }); dispatcher.dispatch(new TeamMapAction { teamMap = userProfileResponse.teamMap }); dispatcher.dispatch(new FollowMapAction { followMap = userProfileResponse.followMap }); dispatcher.dispatch(new UserLicenseMapAction { userLicenseMap = userProfileResponse.userLicenseMap }); var user = userProfileResponse.user; user.followingUsersCount = userProfileResponse.followingCount; user.followingUsersHasMore = userProfileResponse.followingsHasMore; user.followersHasMore = userProfileResponse.followersHasMore; user.followingTeamsCount = userProfileResponse.followingTeamsCount; user.followingTeams = userProfileResponse.followingTeams; user.followingTeamsHasMore = userProfileResponse.followingTeamsHasMore; user.jobRoleMap = userProfileResponse.jobRoleMap; dispatcher.dispatch(new FetchUserProfileSuccessAction { user = user, userId = userId }); }) .Catch(error => { var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(value: error.Message); var errorCode = errorResponse.errorCode; dispatcher.dispatch(new FetchUserProfileFailureAction { userId = userId, errorCode = errorCode }); Debuger.LogError(message: error); } ); })); }
static void Main(string[] args) { UserApi user = new UserApi("testKey00000000", "d95842e96ce84a10b76bc6dc4d36e45f", "http://localhost:37755/api/v1/"); var u = user.GetByIdAsync(1).Result; Console.WriteLine(u.Id + " " + u.NickName + " " + u.PhoneNum + " "); //var id = user.AddNewAsync("13872303747", "Aun", "qqqqq").Result; // Console.WriteLine(id+" "); //var res = user.CheckLoginAsync("13272303747", "qqqqq").Result; // Console.WriteLine(res + " "); //var u = user.GetByPhoneNumAsync("13272303747").Result; //Console.WriteLine(u.Id + " " + u.NickName + " " + u.PhoneNum + " "); //UserGroupApi userGroup = new UserGroupApi("qqqqq", "12345", "http://127.0.0.1:8888/api/v1/"); // userGroup.AddUserToGroupAsync(2, 3).Wait(); //var userGroupArr = userGroup.GetGroupsAsync(3).Result; //foreach (var ug in userGroupArr) //{ // Console.WriteLine(ug.Id+" Name:"+ug.Name); //} //var ug1 = userGroup.GetByIdAsync(2).Result; //Console.WriteLine("Group信息:" + ug1.Id + " UserGroupName:" + ug1.Name); //Console.WriteLine("该Group中的User:"); //var userArr = userGroup.GetGroupUsersAsync(2).Result; //foreach (var u in userArr) //{ // Console.WriteLine(u.Id + " Name:" + u.NickName + " " + u.PhoneNum); //} //userGroup.RemoveUserFromGroupAsync(2, 3).Wait(); //Console.WriteLine("删除成功"); Console.WriteLine("ok"); Console.ReadKey(); }
/// <summary> /// 异步关注事件 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public async override Task <IResponseMessageBase> OnEvent_SubscribeRequestAsync(RequestMessageEvent_Subscribe requestMessage) { BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget")); IResponseMessageBase reponseMessage = null; var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); try { var userInfo = await UserApi.InfoAsync(WXController.AppId, OpenId); if (userInfo != null) { var a = await _weiXinUserRepository.AddAsync( new WeiXinUserDto { City = userInfo.city, Country = userInfo.country, Groupid = userInfo.groupid.ToString(), Headimgurl = userInfo.headimgurl, Language = userInfo.language, Nickname = userInfo.nickname, Openid = userInfo.openid, Province = userInfo.province, Remark = userInfo.remark, Sex = userInfo.sex, Subscribe = userInfo.subscribe, Subscribe_scene = userInfo.subscribe_scene, Subscribe_time = userInfo.subscribe_time.ToString(), Tagid_list = userInfo.tagid_list.ToString(), Unionid = userInfo.unionid, OperationTime = DateTimeOffset.Now }); } strongResponseMessage.Content = "呙呙社区成立于2017年,是一家致力于服务社区业主的网络平台,呙呙社区与众多名企强强联合,本着简、好、快、省的原则共同为社区居民提供更便捷的生活方式。"; reponseMessage = strongResponseMessage; await CustomApi.SendTextAsync(WXController.AppId, OpenId, strongResponseMessage.Content); return(null); } catch (Exception e) { BackgroundJob.Enqueue(() => Console.WriteLine(e.Message)); return(null); } }
public static object fetchUserArticle(string userId, int pageNumber) { return(new ThunkAction <AppState>((dispatcher, getState) => { return UserApi.FetchUserArticle(userId: userId, pageNumber: pageNumber) .Then(userArticleResponse => { var articles = new List <Article>(); userArticleResponse.projectList.ForEach(articleId => { if (userArticleResponse.projectMap.ContainsKey(key: articleId)) { var article = userArticleResponse.projectMap[key: articleId]; if (article.type == "article") { articles.Add(item: article); } } }); dispatcher.dispatch(new PlaceMapAction { placeMap = userArticleResponse.placeMap }); dispatcher.dispatch(new UserMapAction { userMap = userArticleResponse.userMap }); dispatcher.dispatch(new TeamMapAction { teamMap = userArticleResponse.teamMap }); dispatcher.dispatch(new FollowMapAction { followMap = userArticleResponse.followMap }); dispatcher.dispatch(new LikeMapAction { likeMap = userArticleResponse.likeMap }); dispatcher.dispatch(new FetchUserArticleSuccessAction { articles = articles, hasMore = userArticleResponse.hasMore, pageNumber = pageNumber, userId = userId }); }) .Catch(error => { dispatcher.dispatch(new FetchUserArticleFailureAction()); Debug.Log(error); } ); })); }
protected override async void OnEnter(object sender, RoutedEventArgs e) { base.OnEnter(sender, e); UpdateLayout(); GC.WaitForPendingFinalizers(); GC.Collect(); if (!IsOnEnterActive) { e.Handled = true; return; } svPost.ScrollToVerticalOffset(0.0); await UpdatePost() .ConfigureAwait(true); var result = await UserApi.GetProfileById( SettingsManager.PersistentSettings.CurrentUser.Id) .ConfigureAwait(true); if (result.Data != null) { wdgWriteComment.SetRealUserAvatarSource(result.Data.PhotoUrl); } var draft = await StorageManager.GetPostCommentDraft( SettingsManager.PersistentSettings.CurrentUser.Id, ViewModel.CurrentPostData.Id) .ConfigureAwait(true); wdgWriteComment.CommentText = draft.CommentText; wdgWriteComment.IsAnonymous = draft.IsAnonymous; wdgWriteComment.txtContent.ScrollToEnd(); wdgWriteComment.txtContent.CaretIndex = draft.CommentText.Length; wdgWriteComment.txtContent.Focus(); if (svPost.VerticalOffset >= svPost.ScrollableHeight - 20) { svPost.ScrollToVerticalOffset(0.0); } }
private async void UserToSubmit_OnClick(object sender, RoutedEventArgs e) { UserHasInputControl(false); var uapi = new UserApi("5940771a096a5bf6e36f530769a6ba2f"); //todo REGEX if (string.IsNullOrWhiteSpace(UserEmail.Text) || string.IsNullOrWhiteSpace(UserUsername.Text) || string.IsNullOrWhiteSpace(UserPwd.Password) || !(UserPwd.Password.Length > 3) || !(UserUsername.Text.Length > 3) || !(UserEmail.Text.Length > 6) || !UserEmail.Text.Contains("@") || !UserEmail.Text.Contains(".")) { MessageBox.Show( "One or more of he fields contains an invalid entry.\nPasswords must be between 3 and 20 alphanumeric characters", ":(", MessageBoxButton.OK); } else { try { var y = await uapi.ApiReg(UserPwd.Password, UserUsername.Text, UserEmail.Text, FilingCabinet.TownsList.Find(i => i.name == (UserTown.SelectedItem.ToString())).id); if (y.success.Contains("Account created") || y.success.Contains("Account Created") || y.success.Contains("account created")) { MessageBox.Show("Registration successful. Account Created", ":)", MessageBoxButton.OK); NavigationService.Navigate(new Uri("/Pages/UserLogin.xaml", UriKind.Relative)); } else { MessageBox.Show("Registration unsuccessful.\nComputer says: " + y.success, ":(", MessageBoxButton.OK); } } catch (Exception ex) { MessageBox.Show("We could not sign you up at this time, please check details and try again.", ":(", MessageBoxButton.OK); } } UserHasInputControl(true); }
public bool UserCreate(UserApi user, EngineContext context, IEngineLogical funcion) { bool resultado = false; user.CreateDate = DateTime.UtcNow; user.Password = funcion.ConvertirBase64(user.Email + user.Password); try { using (context) { context.UserApi.Add(user); context.SaveChanges(); } resultado = true; } catch { } return(resultado); }
public UserApi GetUser(string password, EngineContext context, IEngineLogical funcion) { UserApi user = null; try { using (context) { user = context.UserApi.Where(s => s.Password == password).FirstOrDefault(); if (user != null) { return(user); } } } catch { } return(null); }
public async Task <IHttpActionResult> LogintUser([FromBody] User user) { UserApi api = new UserApi(); var userId = await api.Login(user); if (userId > 0) // user-defined function, checks against a database { System.IdentityModel.Tokens.JwtSecurityToken token = Microsoft.Azure.Mobile.Server.Login.AppServiceLoginHandler.CreateToken(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()) }, "GfYVqdtZUJQfghRiaonAeRQRDjytRi47", Debugger.IsAttached ? "http://localhost/" : "https://greenhand.azurewebsites.net", Debugger.IsAttached ? "http://localhost/" : "https://greenhand.azurewebsites.net", TimeSpan.FromHours(6)); return(Ok(token.RawData)); } return(Unauthorized()); }
public string BuildUserApiStr(string user, string password, IEngineTool Tool) { UserApi modelo = new UserApi(); bool result = Tool.EmailEsValido(user); if (result) { modelo.Email = user; modelo.User = "******"; } else { modelo.User = user; modelo.Email = "A"; } modelo.Password = password; return(JsonConvert.SerializeObject(modelo)); }
public HttpResponseMessage UpdateCihazId([FromBody] UserApi userApi)//([FromUri]string eMail, [FromUri]string password) { LoginItem loginUser; User user; _yetkilendirme.YetkiKontrolu(userApi, out loginUser, out user); if (user != null) { user.CihazId = userApi.CihazId; _userService.Update(user); return(Request.CreateResponse(HttpStatusCode.OK)); } else { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "CihazId güncellenemedi.")); } }
public async Task UpdateStatus() { if (UserAccount.Id == -1) { return; } var result = await UserApi.GetProfileById( UserAccount.Id) .ConfigureAwait(true); if (result.IsError || result.Data == null) { return; } UserStatus = result.Data.Status; }
public static async Task WechatLogin(this IAccessControl ac, string userName, string password, string openId) { var app = ac.Context.RequestServices.GetService <IWeChatContainer>().GetApp(); var userService = ac.Context.RequestServices.GetService <IUserService>(); var user = userService.CheckUser(userName, password); var userInfoJson = UserApi.Info(app.AppId, openId); if (userInfoJson != null) { user.NickName = userInfoJson.nickname; user.Photo = userInfoJson.headimgurl; userService.Update(user); } userService.UpdateAuth(user, app.Id, openId, "wechat"); await ac.Login(user, true); }
public UserApi GetUserApi(string strValue) { UserApi C = null; try { using (EngineContext Context = new EngineContext()) { C = Context.UserApi.Where(s => s.User == strValue || s.Email == strValue).FirstOrDefault(); return(C); } } catch (Exception ex) { InsertarSucesoLog(Funcion.ConstruirSucesoLog(ex.ToString() + "*EngineDb/GetUserApi*" + strValue)); } return(C); }
/// <summary> /// Function to retrieve the boundaries for the header on a list view. /// </summary> /// <param name="listView">The list view to use.</param> /// <returns>A rectangle containing the client area boundaries for the header.</returns> public static Drawing.Rectangle GetHeaderBounds(this ListView listView) { if (listView.HeaderStyle == ColumnHeaderStyle.None) { return(Drawing.Rectangle.Empty); } if (listView.View != View.Details) { return(Drawing.Rectangle.Empty); } IntPtr columnHeader = UserApi.SendMessage(listView.Handle, LvmGetHeader, IntPtr.Zero, IntPtr.Zero); UserApi.GetWindowRect(columnHeader, out RECT winRect); return(listView.RectangleToClient(Drawing.Rectangle.FromLTRB(winRect.left, winRect.top, winRect.right, winRect.bottom))); }
private async Task UpdateAvatarSource( int userId) { var result = await UserApi.GetProfileById( userId) .ConfigureAwait(true); if (result.IsError || result.Data == null) { UserAvatarSource = null; return; } UserAvatarSource = result.Data .PhotoUrl; }
protected void Page_Load(object sender, EventArgs e) { if (System.Web.HttpContext.Current.Request.Cookies["open_id1"] != null) { open_id = HttpContext.Current.Request.Cookies["open_id1"].Value; } else { Response.Redirect("/api/oauth/weixin_hugong/oauth.aspx"); } var result = UserApi.Info(Token(), open_id); pick_name = result.nickname; headimg = result.headimgurl; }
private void LoginButton_Click(object sender, EventArgs e) { loginButton.Enabled = false; UserApi.UserLogin(textEdit1.Text, textEdit2.Text, success: result => { Properties.Settings.Default.RefreshToken = result.RefreshToken; Properties.Settings.Default.Save(); loginButton.Enabled = true; InkoSecurityContext.UserId = result.UserId; InkoSecurityContext.UserName = result.RealName; NetGlobalInfo.AccessToken = result.Token; DialogResult = DialogResult.OK; }, failure: message => { XtraMessageBox.Show(message); loginButton.Enabled = true; }); }
protected string GetOpid(string cd) { string opid = string.Empty; try { var result = OAuthApi.GetAccessToken(WebConfigurationManager.AppSettings["wxappid1"], WebConfigurationManager.AppSettings["wxsecret1"], cd); var tpuser = UserApi.Info(AccessTokenContainer.TryGetToken(WebConfigurationManager.AppSettings["wxappid1"], WebConfigurationManager.AppSettings["wxsecret1"]), result.openid); try { iswxh = tpuser.subscribe + ""; } catch (Exception) { jsHint.toUrl("lxkjcinfo.aspx"); } if (result.errcode != ReturnCode.请求成功) { //Response.Redirect("/zpzs/zptinfo.aspx"); jsHint.toUrl("lxkjcinfo.aspx"); } else { opid = result.openid; HttpCookie cookie = Request.Cookies["LXKJWebDomain"]; if (cookie == null) { cookie = new HttpCookie("LXKJWebDomain"); } cookie.Values.Set("useropid", opid); cookie.Values.Set("iswxh", iswxh); //cookie.Expires = DateTime.Now.AddDays(-1); cookie.Secure = false; HttpContext.Current.Response.SetCookie(cookie); HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR"); } } catch (Exception) { jsHint.toUrl("lxkjcinfo.aspx"); } return(opid); }
private async void UserToLogin_OnClick(object sender, RoutedEventArgs e) { ProgressBar.Visibility = Visibility.Visible; UserHasInputControl(false); var uapi = new UserApi("5940771a096a5bf6e36f530769a6ba2f"); if (string.IsNullOrEmpty(UserUsername.Text) || string.IsNullOrEmpty(UserPwd.Password)) { ProgressBar.Visibility = Visibility.Collapsed; UserPwd.Password = ""; MessageBox.Show( "The credentials entered are either blank or not in a valid format. Try again.", ":(", MessageBoxButton.OK); } else { try { var y = await uapi.ApiLogin(UserPwd.Password, UserUsername.Text); if (y.success.Contains("logged in") || y.success.Contains("Logged In")) { FilingCabinet.CurrentUserCredentials.Consumerkey = y.consumerkey; FilingCabinet.CurrentUserCredentials.Consumersecret = y.consumersecret; FilingCabinet.CurrentUserCredentials.UserTown = "514628d17fa6866d15000038"; //todo !DEBUG! NEEDS TO UPDATE TempAppData.CurrentTown = FilingCabinet.TownsList.Find(i => i.id == (FilingCabinet.CurrentUserCredentials.UserTown)); NavigationService.Navigate(new Uri("/Pages/MainHub.xaml", UriKind.Relative)); } else { MessageBox.Show("Login unsuccessful.\nComputer says: " + y.success, ":(", MessageBoxButton.OK); } } catch (Exception ex) { MessageBox.Show("We could not sign you in at this time, please check details and try again.", ":(", MessageBoxButton.OK); } } UserHasInputControl(true); }
/// <summary> /// receive images from the server /// </summary> public async void receive() { MessageApi msgApi = MessageApi.getInstance(); UserApi userApi = UserApi.getInstance(); IEnumerable <Message> messages = await msgApi.getGroupMessageData(group.group.id); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; LoadingIndicator = true; if (messages != null && messages.Any()) { foreach (var msg in messages) { if (msg.id != null && !historyContainsMessage(msg.id)) { var fstream = await msgApi.getMessageFile(group.group.id, msg.id); if (fstream != null && fstream.Length > 0) { StorageFile targetFile = await storageFolder.CreateFileAsync(msg.id + ".png", CreationCollisionOption.ReplaceExisting); using (Stream targetStream = await targetFile.OpenStreamForWriteAsync()) { await fstream.CopyToAsync(targetStream); } Uri imageUri = new Uri(targetFile.Path, UriKind.Absolute); User sender = await userApi.getUser(msg.SenderId); MessageContent mc = new MessageContent(msg, sender, imageUri); History.Insert(0, mc); } else { Debug.WriteLine("File with id " + msg.id + " not found"); } } } } LoadingIndicator = false; }
/// <summary> /// 处理报警逻辑(汉王数据接入使用) /// 1.是否命中报警策略 /// 2.记录流水 /// 3.发送消息 /// </summary> /// <param name="deviceInfo"></param> /// <param name="itemInfo"></param> /// <param name="curValue"></param> /// <param name="now"></param> /// <returns></returns> private Task <int> HandleAlarmPolicies1(RetDeviceInfo deviceInfo, RetDeviceItemInfo itemInfo, string curValue, DateTime now) { int result = -1; using (AlertPoliciesEntities alert = new AlertPoliciesEntities()) { var alertInfo = alert.A_AlarmStrategy.Where(s => (s.DeviceID == deviceInfo.ID) && (s.DeviceItemId == itemInfo.ID) && (s.Active == true)).FirstOrDefault(); if (null != alertInfo) { if (isHitPolicies(curValue, alertInfo.Compare, alertInfo.Threshold)) { log.InfoFormat("[MQTT]Hit Policies,topic:{0}/{1},curValue:{2},compare:{3},theshold:{4}.", deviceInfo.DeviceLabel, itemInfo.PropertyLabel, curValue, alertInfo.Compare, alertInfo.Threshold); HistoryAlertPoliciesBLL historyBLL = new HistoryAlertPoliciesBLL(); HistoryAlertPoliciesModel model = new HistoryAlertPoliciesModel() { DeviceID = deviceInfo.ID.ToString(), DeviceItemID = itemInfo.ID.ToString(), StrategyID = alertInfo.ID.ToString(), Value = curValue, AlarmTime = now, EndTime = now.AddSeconds(1), OrgID = alertInfo.OrgID.ToString(), }; historyBLL.AddHistoryAlertPolicies(model); // 发送消息通知 UserApi api = new UserApi(); GetMessageInfoParameter messageModel = new GetMessageInfoParameter() { Type = "2", // 报警预警 Tittle = "【设备报警通知】" + deviceInfo.Name + itemInfo.Name + "报警!", Text = "<p>您好:</p><p class='ql-indent-1'>" + deviceInfo.Name + "(设备)" + itemInfo.Name + "(属性)当前数值为" + curValue + ",已触发预设报警策略,请及时处理异常!</p><p><br></p><p class='ql-align-right'>设备在线监测平台</p>", OrgID = alertInfo.OrgID.ToString() }; var userApi = api.AddAlarmMessage(messageModel); if (userApi.Code != 0) { log.ErrorFormat(userApi.Data); } } } } return(new Task <int>(() => result)); }
private void OnModifyUserInfo() { Console.WriteLine("输入新名称"); string newName = Console.ReadLine(); Console.WriteLine("输入新密码"); string newPass = Console.ReadLine(); if (UserApi.UserUpdate(Username, Password, newName, newPass)) { Console.WriteLine("修改成功 按下任意按键返回重新登录"); SceneManager.Instance.PopScene(); } else { Console.WriteLine("修改失败"); } Console.ReadKey(); }
/// <summary> /// 用户管理-获取用户列表 /// 未认证订阅号 未认证服务号 没有此权限 /// </summary> /// <param name="domainContext"></param> /// <param name="next_openid"></param> /// <returns></returns> public static RequestApiResult <WeixinGetUserListResult> GetUserList(DomainContext domainContext, string next_openid) { RequestApiResult <WeixinGetUserListResult> result; if (domainContext.Authorizer.AuthorizationType == EnumAuthorizationType.UnauthorizedService || domainContext.Authorizer.AuthorizationType == EnumAuthorizationType.UnauthorizedSubscription) { result = new RequestApiResult <WeixinGetUserListResult>(); result.ApiError = new WeixinApiErrorResult(); result.ApiError.ErrorCode = -1; result.ApiError.ErrorMessage = "未认证订阅号 及 未认证服务号 没有获取用户列表权限。"; return(result); } string accessToken = domainContext.AccessToken; result = UserApi.GetUserList(accessToken, next_openid); if (result.Success == false) { if (result.Retry) { if (result.ApiError.ErrorCode == 40001) { accessToken = AccessTokenGetter.Refresh(domainContext.AppId, accessToken); } result = UserApi.GetUserList(accessToken, next_openid); if (result.Success == false) { string logMessage = result.GetDetail() + Environment.NewLine + new StackTrace().ToString(); _log.Write("UserApi.GetUserList 失败", logMessage, TraceEventType.Warning); } } else { string logMessage = result.GetDetail() + Environment.NewLine + new StackTrace().ToString(); _log.Write("UserApi.GetUserList 失败", logMessage, TraceEventType.Warning); } } return(result); }
/// <summary> /// 加载用户真实姓名数据 /// </summary> public static async Task <Dictionary <Id, string> > GetUserInfosAsync(Id[] userIds) { var listParamas = new ListParams { Search = Query.In(Id.Name, userIds), Map = new[] { Id.Name, "RealName" } }; var result = await UserApi.GetUserInfoListAsync(listParamas); if (!result.IsOk) { Mg.Get <IMgLog>().Error($"获取用户的头像数据失败:{result.Message}"); Mg.Get <IMgDialog>().ShowDesktopAlert("获取用户的头像数据失败", result.Message); return(null); } var items = result.GetRecords(); return(items.ToDictionary(item => item[Id.Name].As <Id>(), item => item["RealName"].As <string>())); }
private static UserModel CreateUserTest(Iatec.Accounts.Client.Configuration apiConfig) { try { var api = new UserApi(apiConfig); return(api.CreateUser(new UserInsertModel { FirstName = "William", LastName = "Moura", Password = "******", Email = "*****@*****.**", UserName = "******", })); } catch (ApiException ex) { throw ex; } }
private UserInfoJson GetWXUserHead(string openid) { var siteSetting = this._siteSetting; if (!string.IsNullOrEmpty(siteSetting.WeixinAppId) || !string.IsNullOrEmpty(siteSetting.WeixinAppSecret)) { string accessToken = AccessTokenContainer.TryGetToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret); UserInfoJson user = UserApi.Info(accessToken, openid); if (user.errcode == Senparc.Weixin.ReturnCode.请求成功) { return(user); } else { throw new HimallException(user.errmsg); } } throw new Exception("未配置公众号"); }
public static object fetchUnFollowUser(string unFollowUserId) { return(new ThunkAction <AppState>((dispatcher, getState) => { return UserApi.FetchUnFollowUser(userId: unFollowUserId) .Then(success => { dispatcher.dispatch(new UnFollowUserSuccessAction { success = success, currentUserId = getState().loginState.loginInfo.userId ?? "", unFollowUserId = unFollowUserId }); }) .Catch(error => { dispatcher.dispatch(new UnFollowUserFailureAction { unFollowUserId = unFollowUserId }); Debuger.LogError(message: error); }); })); }
/// <summary> /// Function to convert a keyboard key into a character (if applicable). /// </summary> /// <param name="key">The key to convert into a character.</param> /// <param name="modifier">The modifier for that key.</param> /// <returns>The character representation for the key. If no representation is available, an empty string is returned.</returns> /// <remarks> /// <para> /// Use this to retrieve the character associated with a keyboard key. For example, if <see cref="Keys.A"/> is pressed, then 'a' will be returned. A <paramref name="modifier"/> can be /// passed with the <see cref="Keys.ShiftKey"/> to return 'A'. /// </para> /// <para> /// This method also supports the AltGr key which is represented by a combination of the <see cref="Keys.ControlKey"/> | <see cref="Keys.Menu"/> keys. /// </para> /// <para> /// This method only returns characters for the currently active keyboard layout (i.e. the system keyboard layout). If this keyboard interface represents another keyboard attached to the computer /// then it will default to using the system keyboard to retrieve the character. /// </para> /// <para> /// This method is not thread safe. Invalid data will be returned if multiple thread access this method. /// </para> /// <para> /// This method was derived from the answer at <a href="http://stackoverflow.com/questions/6929275/how-to-convert-a-virtual-key-code-to-a-character-according-to-the-current-keyboa"/>. /// </para> /// </remarks> public string KeyToCharacter(Keys key, Keys modifier) { const int shiftKey = (int)Keys.ShiftKey; const int ctrlKey = (int)Keys.ControlKey; const int menuKey = (int)Keys.Menu; // Shift key modifier if ((modifier & Keys.Shift) == Keys.Shift) { _charStates[shiftKey] = 0xff; } else { _charStates[shiftKey] = 0; } // AltGr modifiers if ((modifier & (Keys.Control | Keys.Menu)) == (Keys.Control | Keys.Menu)) { _charStates[ctrlKey] = 0xff; _charStates[menuKey] = 0xff; } else { _charStates[ctrlKey] = 0; _charStates[menuKey] = 0; } int result = UserApi.ToUnicode((uint)key, 0, _charStates, _characterBuffer, _characterBuffer.Length, 0); switch (result) { case -1: case 0: return(string.Empty); case 1: return(new string(_characterBuffer, 0, 1)); default: return(string.Empty); } }
private void btnMoveToGroup_Click(object sender, EventArgs e) { int togroup_id = 111;//输入分组ID if (togroup_id > 0) { IUserApi userBLL = new UserApi(); CommonResult result = userBLL.MoveUserToGroup(token, openId, togroup_id); Console.WriteLine("移动用户分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage)); } }
private void btnCreateGroup_Click(object sender, EventArgs e) { IUserApi userBLL = new UserApi(); GroupJson info = userBLL.CreateGroup(token, "创建测试分组"); if (info != null) { string tips = string.Format("GroupId:{0} GroupName:{1}", info.id, info.name); Console.WriteLine(tips); string newName = "创建测试修改"; CommonResult result = userBLL.UpdateGroupName(token, info.id, newName); Console.WriteLine("修改分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage)); } }
private void btnGetGroupList_Click(object sender, EventArgs e) { IUserApi userBLL = new UserApi(); List<GroupJson> list = userBLL.GetGroupList(token); foreach (GroupJson info in list) { string tips = string.Format("{0}:{1}", info.name, info.id); Console.WriteLine(tips); } }
private void btnFindUserGroup_Click(object sender, EventArgs e) { IUserApi userBLL = new UserApi(); int groupId = userBLL.GetUserGroupId(token, openId); string tips = string.Format("GroupId:{0}", groupId); Console.WriteLine(tips); }
public void WithAuthenticationCallToMethodRequiringAuthenticationShouldBeSuccessful() { var authenticator = ObjectFactory.GetInstance<IAuthenticator>(); var api = new UserApi(GitHubUrl).WithAuthentication(authenticator); var user = api.GetUser("sgrassie"); Assert.That(user.DiskUsage, Is.GreaterThan(0)); }
public void WhenNotAuthenticatedFollowShouldThrowNotAuthenticatedException() { var api = new UserApi(GitHubUrl); var user = api.GetUser("sgrassie"); Assert.Throws<GitHubAuthorizationException>(() => api.Follow("mono")); }
private void btnGetUsers_Click(object sender, EventArgs e) { IUserApi userBLL = new UserApi(); List<string> userList = userBLL.GetUserList(token); foreach (string openId in userList) { UserJson userInfo = userBLL.GetUserDetail(token, openId); if (userInfo != null) { string tips = string.Format("{0}:{1}", userInfo.nickname, userInfo.openid); Console.WriteLine(tips); } } }
private void btnUpdateGroup_Click(object sender, EventArgs e) { int groupId = 111; string newName = "创建测试修改"; IUserApi userBLL = new UserApi(); CommonResult result = userBLL.UpdateGroupName(token, groupId, newName); Console.WriteLine("修改分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage)); }
public void Should_Get_List_Of_Followers() { var result = new UserApi(GitHubUrl).GetFollowers("sgrassie"); Assert.That(result, Has.Count.GreaterThan(0)); }