public static UserInformation GetGithubUser(string username) { //Validate user input try { using (WebClient webClient = new WebClient()) { //Instatize UserInforamtion UserInformation myInfo = new UserInformation(); //Say hello to GitHub webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); //Grab userInformation file from Github string json = webClient.DownloadString("https://api.github.com/users/" + username); //Convert JSON to user-able variables myInfo = JsonConvert.DeserializeObject<UserInformation>(json); return myInfo; } } catch (Exception) { MessageBox.Show("User could not be found. Please check the username and try again."); return null; } }
public User(UserInformation userInformation) { Name = userInformation.FullName; ClaimedIdentifier = userInformation.ClaimedIdentifier; Email = userInformation.Email; Role = Roles.User; }
public async Task<UserInformation> Authorize( CatalitCredentials credentials, CancellationToken cancellationToken ) { if( credentials != null ) { var encodedPass = WebUtility.UrlEncode(credentials.Password); var parameters = new Dictionary<string, object> { {"login", credentials.Login}, {"pwd", credentials.Password} }; if(!string.IsNullOrEmpty(credentials.Sid)) parameters.Add("sid", credentials.Sid); var result = await _client.Authorize( parameters, cancellationToken ); if( result != null ) { UserInformation = result; //Activate Coupone if nokia if( _deviceInfoService.IsNokiaDevice ) { try { await ActivateNokiaCoupone(result.SessionId, CancellationToken.None); } catch( CatalitActivateCouponeException ) { } } return result; } } throw new CatalitNoCredentialException(); }
public InformationBox(UserInformation u, PlayerUser pu) { Players = u.DefaultPlayers; Bombs = u.DefaultBombs; defb = Bombs; BackColor = CommonObjects.Colors.DimGray; FontColor = CommonObjects.Colors.White; Manager = new ObjectManager(2); user = pu; Y = 432; NumberScore = new NumberSprite(CommonObjects.ImageNumber32, 16, 32, 8) { X = 16 + 128, Y = 8, FillWithZero = true }; NumberFrames = new NumberSprite(CommonObjects.ImageNumber24, 12, 24, 4) { X = 572, Y = 20, }; NumberFps = new NumberSprite(CommonObjects.ImageNumber12White, 6, 12, 2) { X = 640 - 12, Y = 36, }; NumberPlayers = new NumberSprite(CommonObjects.ImageNumber16, 8, 16, 3) { X = 384, Y = 4, FillWithZero = true }; NumberBombs = new NumberSprite(CommonObjects.ImageNumber16, 8, 16, 3) { X = 524, Y = 4, FillWithZero = true }; NumberDestroy = new NumberSprite(CommonObjects.ImageNumber16, 8, 16, 4) { X = 376, Y = 28, FillWithZero = true }; NumberGraze = new NumberSprite(CommonObjects.ImageNumber16, 8, 16, 5) { X = 508, Y = 28, FillWithZero = true }; }
public UserInformation getItem() { conn.Open(); DataSet setdata = new DataSet(); SqlCeCommand cmd = new SqlCeCommand("select * from UserInformation where ID=" + this._userinformation.ID.ToString(), conn); SqlCeDataAdapter adapter = new SqlCeDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(setdata); UserInformation _account = new UserInformation(); _account.username = setdata.Tables[0].Rows[0].ItemArray[1].ToString(); conn.Close(); return _account; }
public async Task<UserInformation> GetUserInfo( CancellationToken cancellationToken, bool deffaultFromTheWeb = false ) { if (deffaultFromTheWeb) UserInformation = null; var result = UserInformation ?? await _client.GetUserInfo( cancellationToken ); if( result != null ) { UserInformation = result; return result; } throw new CatalitNoCredentialException(); }
protected void Button1_Click(object sender, EventArgs e) { UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CANDZOILPDBConnectionString"].ConnectionString; UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); IdentityUser user = new IdentityUser(); user.UserName = txtUserName.Text; if (txtPassword.Text.Equals(txtConfirmPassword.Text)) { try { IdentityResult result = manager.Create(user, txtPassword.Text); if (result.Succeeded) { UserInformation info = new UserInformation { Address = txtAddress.Text, FirstName = txtFirstName.Text, LastName = txtLastName.Text, PostalCode = Convert.ToInt32(txtPostalCode.Text), GUID = user.Id }; UserInfoModel model = new UserInfoModel(); model.InsertUserInformation(info); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties(), userIdentity); Response.Redirect("~/Index.aspx"); }else{ litStatusMessage.Text = result.Errors.FirstOrDefault(); } } catch (Exception er) { litStatusMessage.Text = er.ToString(); } } else { litStatusMessage.Text = "Passwords must match!"; } }
/// <summary> /// Get the username who sent this HTTP request. /// </summary> /// <param name="ShowPrivilege"></param> /// <returns>Privilege = 0 (for common user),Privilege = 1 (for super user),(Always returns 0 if it is in Non-authorization mode under SetUserCheck.cgi)</returns> public UserInformation GetMyself(bool ShowPrivilege) { RovioResponse response = this.Request("/GetMyself.cgi", new RequestItem("ShowPrivilege", ShowPrivilege ? 1 : 0)); UserGroups group = UserGroups.Unknown; if(response.ContainsKey("Privilege")) { if(response["Privilege"] == "1") group = UserGroups.Administrator; else if(response["Privilege"] == "0") group = UserGroups.User; else group = UserGroups.Unknown; } UserInformation info = new UserInformation( group, response["Name"]); return info; }
public List<UserInformation> getList() { List<UserInformation> AccountList = new List<UserInformation>(); conn.Open(); DataSet setdata = new DataSet(); SqlCeCommand cmd = new SqlCeCommand("select * from UserInformation", conn); SqlCeDataAdapter adapter = new SqlCeDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(setdata); UserInformation _account = new UserInformation(); for (int i = 0; i < setdata.Tables[0].Rows.Count; i++) { _account = new UserInformation(); _account.ID = Int64.Parse(setdata.Tables[0].Rows[i].ItemArray[0].ToString()); _account.username = setdata.Tables[0].Rows[i].ItemArray[1].ToString(); _account.password = setdata.Tables[0].Rows[i].ItemArray[2].ToString(); AccountList.Add(_account); } conn.Close(); return AccountList; }
public JsonResult CeateAdmin(string id, string password) { ModelsContainer db = new ModelsContainer(); MembershipCreateStatus createStatus; var user = Membership.CreateUser(id, password, null, null, null, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRole(id, "Admin"); UserInformation userInformation = new UserInformation(); userInformation.phone = ""; userInformation.telephone = ""; userInformation.trueName = "管理员"; userInformation.UserID = new Guid(Convert.ToString(user.ProviderUserKey)); userInformation.UserType = 3; db.UserInformation.AddObject(userInformation); db.SaveChanges(); return new JsonResult { Data = id }; } else { return new JsonResult { Data = "failed" }; } }
protected void btnRegister_Click(object sender, EventArgs e) { // Default UserStore constructor uses the default connection string named: DefaultConnection var userStore = new UserStore<IdentityUser>(); //Set ConnectionString to GarageConnectionString userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GarageDBConnectionString"].ConnectionString; var manager = new UserManager<IdentityUser>(userStore); //Create new user and try to store in DB. var user = new IdentityUser { UserName = txtUserName.Text }; if (txtPassword.Text == txtConfirmPassword.Text) { try { //Create user object //Database will be created / expanded automatically IdentityResult result = manager.Create(user, txtPassword.Text); if (result.Succeeded) { UserInformation info = new UserInformation() { Address = txtAddress.Text, FirstName = txtFirstName.Text, LastName = txtLastName.Text, PostalCode = Convert.ToInt32(txtPostalCode.Text), //retreive the dynamically generateed key from the current logged in user GUID = user.Id }; //send the user information object to the database UserInfoModel model = new UserInfoModel(); model.InsertUserDetail(info); //Store user in DB var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; //set to login new user by Cookie var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //If succeedeed, log in the new user and set a cookie and redirect to homepage authenticationManager.SignIn(new AuthenticationProperties(), userIdentity); Response.Redirect("~/Index.aspx"); } else { litStatusMessage.Text = result.Errors.FirstOrDefault(); } } catch (Exception ex) { litStatusMessage.Text = ex.ToString(); } } else { litStatusMessage.Text = "Passwords must match!"; } }
/// <summary> /// Override the base TestInitialize function /// </summary> protected override void TestInitialize() { base.TestInitialize(); if (this.EMAILAdapter == null) { this.EMAILAdapter = Site.GetAdapter<IMS_ASEMAILAdapter>(); } string domain = Common.GetConfigurationPropertyValue("Domain", this.Site); this.User1Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User1Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User1Password", this.Site), UserDomain = domain }; this.User2Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User2Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User2Password", this.Site), UserDomain = domain }; this.User3Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User3Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User3Password", this.Site), UserDomain = domain }; this.User4Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User4Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User4Password", this.Site), UserDomain = domain }; this.User5Information = new UserInformation { UserName = Common.GetConfigurationPropertyValue("User5Name", this.Site), UserPassword = Common.GetConfigurationPropertyValue("User5Password", this.Site), UserDomain = domain }; if (Common.GetSutVersion(this.Site) != SutVersion.ExchangeServer2007 || string.Equals(Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "12.1")) { this.SwitchUser(this.User1Information, true); } }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { m_logger.Debug("LDAP Plugin Gateway"); List <string> addedGroups = new List <string>(); LdapServer serv = properties.GetTrackedSingle <LdapServer>(); // If the server is unavailable, we go ahead and succeed anyway. if (serv == null) { m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available."); return(new BooleanResult() { Success = true, Message = "LDAP server not available" }); } try { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); string user = userInfo.Username; List <GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules(); bool boundToServ = false; foreach (GroupGatewayRule rule in rules) { bool inGroup = false; // Don't need to check for group membership if the rule is to be always applied. if (rule.RuleCondition != GroupRule.Condition.ALWAYS) { // If we haven't bound to server yet, do so. if (!boundToServ) { this.BindForAuthzOrGatewaySearch(serv); boundToServ = true; } inGroup = serv.MemberOfGroup(user, rule.Group); m_logger.DebugFormat("User {0} {1} member of group {2}", user, inGroup ? "is" : "is not", rule.Group); } if (rule.RuleMatch(inGroup)) { m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"", user, rule.LocalGroup, rule.ToString()); addedGroups.Add(rule.LocalGroup); userInfo.AddGroup(new GroupInformation() { Name = rule.LocalGroup }); } } } catch (Exception e) { m_logger.ErrorFormat("Error during gateway: {0}", e); // Error does not cause failure return(new BooleanResult() { Success = true, Message = e.Message }); } try { // SFTP // Setup session options UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = Settings.Store.SFTPServerURL, UserName = Settings.Store.SFTPUser, Password = Settings.Store.SFTPPassword, SshHostKeyFingerprint = Settings.Store.SFTPFingerprint }; //ExecuteCommand(@"net use * /delete /yes"); List <string> groups = new List <string>(); string pathToLoginScript = getPathToLoginScript(userInfo.Username); if (File.Exists(pathToLoginScript)) { File.Delete(pathToLoginScript); } using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Download files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Ascii; string group_list_path = Settings.Store.SFTPGroupListPath; if (group_list_path.Trim().Length > 0 && session.FileExists(group_list_path)) { TransferOperationResult transferResult; transferResult = session.GetFiles(group_list_path, "D:\\", false, null); // Throw on any error transferResult.Check(); string line; int index = group_list_path.LastIndexOf(@"\"); if (index < 0) { index = group_list_path.LastIndexOf("/"); } if (index < 0) { index = -1; } group_list_path = group_list_path.Substring(index + 1); System.IO.StreamReader file = new System.IO.StreamReader(@"D:\" + group_list_path); while ((line = file.ReadLine()) != null) { groups.Add(line); } file.Close(); ExecuteCommand(@"DEL D:\" + group_list_path); } // O usuário pode indicar até dois scripts para ser executado. string path_script = Settings.Store.SFTPScriptPath; if (path_script.Trim().Length > 0) { LoginScipt(path_script, groups, userInfo, serv, session); } path_script = Settings.Store.SFTPScriptPath2; if (path_script.Trim().Length > 0) { LoginScipt(path_script, groups, userInfo, serv, session); } if (File.Exists(pathToLoginScript)) { FileSecurity fSec = File.GetAccessControl(pathToLoginScript); fSec.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.SelfSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAttributes(getPathToLoginScript(userInfo.Username), File.GetAttributes(getPathToLoginScript(userInfo.Username)) | FileAttributes.Hidden); } // Cria o cmdLoginScript.bat // Write each directory name to a file. try { string code_cmd_login = Settings.Store.CMDLoginScript; code_cmd_login = code_cmd_login.Replace("%u", userInfo.Username); using (StreamWriter sw = new StreamWriter(@"D:\cmdLoginScript.bat", false)) { sw.WriteLine(code_cmd_login); } File.SetAttributes(@"D:\cmdLoginScript.bat", File.GetAttributes(@"D:\cmdLoginScript.bat") | FileAttributes.Hidden); } catch (Exception e) { m_logger.ErrorFormat("O arquivo D:\\cmdLoginScript.bat não pode ser alterado, por favor, delete o arquivo manualmente!", e); } // Cria o cmdLogoffScript.bat // Write each directory name to a file. try { string code_cmd_logoff = Settings.Store.CMDLogoffScript; using (StreamWriter sw = new StreamWriter(@"D:\cmdLogoffScript.bat", false)) { sw.WriteLine(code_cmd_logoff); } File.SetAttributes(@"D:\cmdLogoffScript.bat", File.GetAttributes(@"D:\cmdLogoffScript.bat") | FileAttributes.Hidden); } catch (Exception e) { m_logger.ErrorFormat("O arquivo D:\\cmdLogoffScript.bat não pode ser alterado, por favor, delete o arquivo manualmente!", e); } } } catch (Exception e) { m_logger.ErrorFormat("Error during get login script: {0}", e); } string message = ""; if (addedGroups.Count > 0) { message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups)); } else { message = "No groups added."; } return(new BooleanResult() { Success = true, Message = message }); }
public JsonResult Login(FormCollection fCollection) { try { ArrayList logInMessage = new ArrayList(); UserInformation userInfo = new UserInformation(); userInfo = securityDal.ReadUserInformation(fCollection["txtUserName"], fCollection["txtPassword"], Helper.Active); if (userInfo != null) { objLoginHelper = securityDal.LoginInformation(fCollection, userInfo); String ipAddress = string.Empty, sMacAddress = string.Empty; ipAddress = IPNetworking.GetIP4Address(); // ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress; // Use it Or the below one for get Visitors IP address if (String.IsNullOrEmpty(ipAddress)) { ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipAddress == null) { ipAddress = Request.ServerVariables["REMOTE_ADDR"]; } } //sMacAddress = NetworkUtility.GetMacAddress(NetworkUtility.GetMacAddress(ipAddress)); erpDal.CreateUserLog(ipAddress, sMacAddress, objLoginHelper.LocationCode, objLoginHelper.LogInID, "Login"); Session["LogInInformation"] = objLoginHelper; return(new JsonResult { Data = ExceptionHelper.ExceptionMessage(string.Empty, "Valid", Helper.URL(objLoginHelper)) }); } else { return(new JsonResult { Data = ExceptionHelper.ExceptionMessage("Sorry, UserId/Password Is Not Valid.", "error", string.Empty) }); } //RASolarERPDAL objModuleDal = new RASolarERPDAL(); //ViewBag.RSFModule = objModuleDal.RSFERPModuleDataForCombo(); //ViewBag.UserValidation = false; //return View(); //aa = fCollection["ddlZone"]; //aa = fCollection["ddlRegion"]; //aa = fCollection["ddlUnit"]; //aa = fCollection["txtUserName"]; //aa = fCollection["txtPassword"]; } catch (Exception ex) { return(new JsonResult { Data = ExceptionHelper.ExceptionMessage(ex) }); } }
public RecipeRepository(PantryDbContext context, UserInformation userInformation) { this.context = context; this.userInformation = userInformation; }
private async Task loadUserTrip() { _listSummary = await TripSummary.Load(); _tripNumberUser = _listSummary.Count; StorageFile _fileCountries = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/CountryDefinition.desc")); _listCountriesStandard = Serialization.DeserializeFromXmlFile <List <Country> >(_fileCountries.Path); if (_tripNumberUser == 0) { if (_app.AppSettings.LearnInProgress("TOPIC_SAMPLE_A")) { StorageFile _fileSample = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/SampleA.desc")); TripSummary _sample = Serialization.DeserializeFromXmlFile <TripSummary>(_fileSample.Path); _listSummary.Add(_sample); } if (_app.AppSettings.LearnInProgress("TOPIC_SAMPLE_B")) { StorageFile _fileSample = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/SampleB.desc")); TripSummary _sample = Serialization.DeserializeFromXmlFile <TripSummary>(_fileSample.Path); _listSummary.Add(_sample); } } if (_listSummary.Count == 0) { _appBar.Show(AppBarPage.SIDE.BOTH); } else if (_listSummary.Count > 0) { List <TripSummary> _tripSummOrd = _listSummary.OrderByDescending <TripSummary, DateTime>(o => o.DateArrival).ToList <TripSummary>(); foreach (TripSummary _summary in _tripSummOrd) { // displayed trip description block TripDescUserControl blk = new TripDescUserControl(this, _app.AppSettings.GetConfig("CONFIG_MILES"), _app.AppSettings.ThemeColors); blk.DefBlockTrip = _summary; _listTripDesc.Add(blk); Distance += _summary.Distance; } } StorageFile _imageAccount = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile; #if DEBUG _imageAccount = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/user.png")); _app.AppSettings.DisplayName = _res.GetString("Guest"); #endif IRandomAccessStream _stream = await _imageAccount.OpenReadAsync(); BitmapImage _bmp = new BitmapImage(); _bmp.SetSource(_stream); profilePicture.Source = _bmp; profilePicture.Visibility = Visibility.Visible; profileName.Text = _app.AppSettings.DisplayName + " >"; rewards(); foreach (TripDescUserControl _tripDesc in _listTripDesc) { _app.SynchroManager.UpdateAll(_tripDesc.DefBlockTrip); } }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { m_logger.Debug("LDAP Plugin Gateway"); List <string> addedGroups = new List <string>(); LdapServer serv = properties.GetTrackedSingle <LdapServer>(); // If the server is unavailable, we go ahead and succeed anyway. if (serv == null) { m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available."); return(new BooleanResult() { Success = true, Message = "LDAP server not available" }); } try { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); List <GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules(); bool boundToServ = false; foreach (GroupGatewayRule rule in rules) { bool inGroup = false; // If we haven't bound to server yet, do so. if (!boundToServ) { this.BindForAuthzOrGatewaySearch(serv); boundToServ = true; } string path = rule.path.Replace("%u", userInfo.Username); string filter = rule.filter.Replace("%u", userInfo.Username); //inGroup = serv.MemberOfGroup(user, rule.Group); inGroup = serv.GetUserAttribValue(path, filter, rule.SearchScope, new string[] { "dn" }).Count > 0; m_logger.DebugFormat("User {0} {1} {2} {3}", userInfo.Username, filter, inGroup ? "is" : "is not", path); if (rule.RuleMatch(inGroup)) { m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"", userInfo.Username, rule.LocalGroup, rule.ToString()); addedGroups.Add(rule.LocalGroup); userInfo.AddGroup(new GroupInformation() { Name = rule.LocalGroup }); } } } catch (Exception e) { m_logger.ErrorFormat("Error during gateway: {0}", e); // Error does not cause failure return(new BooleanResult() { Success = true, Message = e.Message }); } string message = ""; if (addedGroups.Count > 0) { message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups)); } else { message = "No groups added."; } return(new BooleanResult() { Success = true, Message = message }); }
protected override UserInformation RetrieveUserInformation(AccessToken accessToken) { if (accessToken == null) { throw new ArgumentNullException("accessToken"); } if (string.IsNullOrEmpty(accessToken.PublicToken)) { throw new ArgumentException("accessToken.PublicToken"); } IRestResponse <MeResult> response; try { var restRequest = new RestRequest("v2.5/me"); restRequest.AddParameter("access_token", accessToken.PublicToken); restRequest.AddParameter("fields", "name,email,first_name,last_name,locale,gender,link"); var restClient = RestClientFactory.CreateRestClient(BaseUrl); TraceSource.TraceVerbose("Retrieving user information. Facebook Endpoint: {0}", restClient.BuildUri(restRequest).AbsoluteUri); response = restClient.Execute <MeResult>(restRequest); } catch (Exception exception) { var authenticationException = new AuthenticationException("Failed to retrieve any Me data from the Facebook Api.", exception); var errorMessage = authenticationException.RecursiveErrorMessages(); TraceSource.TraceError(errorMessage); throw new AuthenticationException(errorMessage, exception); } if (response == null || response.StatusCode != HttpStatusCode.OK || response.Data == null) { var errorMessage = string.Format( "Failed to obtain some 'Me' data from the Facebook api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Message: {2}.", response == null ? "-- null response --" : response.StatusCode.ToString(), response == null ? string.Empty : response.StatusDescription, response == null ? string.Empty : response.ErrorException == null ? "--no error exception--" : response.ErrorException.RecursiveErrorMessages()); TraceSource.TraceError(errorMessage); throw new AuthenticationException(errorMessage); } var id = response.Data.Id < 0 ? 0 : response.Data.Id; var name = (string.IsNullOrEmpty(response.Data.FirstName) ? string.Empty : response.Data.FirstName) + " " + (string.IsNullOrEmpty(response.Data.LastName) ? string.Empty : response.Data.LastName).Trim(); var userInformation = new UserInformation { Id = id.ToString(), Name = name, Email = response.Data.Email, Locale = response.Data.Locale, UserName = response.Data.Username, Gender = string.IsNullOrWhiteSpace(response.Data.Gender) ? GenderType.Unknown : GenderTypeHelpers.ToGenderType(response.Data.Gender), Picture = string.Format("https://graph.facebook.com/{0}/picture", id) }; return(userInformation); }
public async Task <ApiStatus> SignInAsync() { try { UserInformation userInfo = await Auth.SignInAsync(); // Sign-in succeeded. string accountId = userInfo.AccountId; string token = userInfo.AccessToken; if (!string.IsNullOrWhiteSpace(accountId) && !string.IsNullOrWhiteSpace(token)) { await SecureStorage.SetAsync("auth_token", token); var tokenHandler = new JwtSecurityTokenHandler(); try { var jwToken = tokenHandler.ReadJwtToken(userInfo.IdToken); var firstName = jwToken.Claims.FirstOrDefault(t => t.Type == "given_name")?.Value; var familyName = jwToken.Claims.FirstOrDefault(t => t.Type == "family_name")?.Value; var jobTitle = jwToken.Claims.FirstOrDefault(t => t.Type == "jobTitle")?.Value; var email = jwToken.Claims.FirstOrDefault(t => t.Type == "emails")?.Value; string fullName = firstName + " " + familyName; if (!string.IsNullOrWhiteSpace(fullName)) { Preferences.Set("MyName", fullName); } if (!string.IsNullOrWhiteSpace(jobTitle)) { Preferences.Set("JobTitle", jobTitle); } if (!string.IsNullOrWhiteSpace(email)) { Preferences.Set("MyEmail", email); } _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string baseUrl = Constants.ApiBaseUrl; _userClient = new UserClient(baseUrl, _httpClient); var user = await _userClient.GetAsync(); Preferences.Set("MyUserId", user.Id); Preferences.Set("MyProfilePic", user.Picture); if (!string.IsNullOrWhiteSpace(user.Points.ToString())) { Preferences.Set("MyPoints", user.Points); } Preferences.Set("LoggedIn", true); return(ApiStatus.Success); } catch (ArgumentException) { //TODO: Handle error decoding JWT return(ApiStatus.Error); } } else { return(ApiStatus.LoginFailure); } } catch (ApiException e) { if (e.StatusCode == 404) { return(ApiStatus.Unavailable); } else if (e.StatusCode == 401) { return(ApiStatus.LoginFailure); } return(ApiStatus.Error); } }
async void RunMBaaSAsync(object sender, EventArgs e) { try { userInfo = await Auth.SignInAsync(); if (userInfo.AccountId != null) { Application.Current.Properties[AccountId] = userInfo.AccountId; SignInInformationButton.Text = "User authenticated"; } AppCenterLog.Info(App.LogTag, "Auth.SignInAsync succeeded accountId=" + userInfo.AccountId); } catch (Exception ex) { AppCenterLog.Error(App.LogTag, "Auth scenario failed", ex); Crashes.TrackError(ex); } try { var list = await Data.ListAsync <CustomDocument>(DefaultPartitions.UserDocuments); foreach (var doc in list) { AppCenterLog.Info(App.LogTag, "List result=" + JsonConvert.SerializeObject(doc)); } var document = list.CurrentPage.Items.First(); AppCenterLog.Info(App.LogTag, "List first result=" + JsonConvert.SerializeObject(document)); document = await Data.DeleteAsync <CustomDocument>(document.Id, DefaultPartitions.UserDocuments); AppCenterLog.Info(App.LogTag, "Delete result=" + JsonConvert.SerializeObject(document)); } catch (Exception ex) { AppCenterLog.Error(App.LogTag, "Data list/delete first scenario failed", ex); Crashes.TrackError(ex); } try { var objectCollection = new List <Uri>(); objectCollection.Add(new Uri("http://google.com/")); objectCollection.Add(new Uri("http://microsoft.com/")); objectCollection.Add(new Uri("http://facebook.com/")); var primitiveCollection = new List <int>(); primitiveCollection.Add(1); primitiveCollection.Add(2); primitiveCollection.Add(3); var dict = new Dictionary <string, Uri>(); dict.Add("key1", new Uri("http://google.com/")); dict.Add("key2", new Uri("http://microsoft.com/")); dict.Add("key3", new Uri("http://facebook.com/")); var customDoc = new CustomDocument { Id = Guid.NewGuid(), TimeStamp = DateTime.UtcNow, SomeNumber = 123, SomeObject = dict, SomePrimitiveArray = new int[] { 1, 2, 3 }, SomeObjectArray = new CustomDocument[] { new CustomDocument { Id = Guid.NewGuid(), TimeStamp = DateTime.UtcNow, SomeNumber = 123, SomeObject = dict, SomePrimitiveArray = new int[] { 1, 2, 3 }, SomeObjectCollection = objectCollection, SomePrimitiveCollection = primitiveCollection } }, SomeObjectCollection = objectCollection, SomePrimitiveCollection = primitiveCollection, Custom = new CustomDocument { Id = Guid.NewGuid(), TimeStamp = DateTime.UtcNow, SomeNumber = 123, SomeObject = dict, SomePrimitiveArray = new int[] { 1, 2, 3 }, SomeObjectCollection = objectCollection, SomePrimitiveCollection = primitiveCollection } }; var id = customDoc.Id.ToString(); var document = await Data.ReplaceAsync(id, customDoc, DefaultPartitions.UserDocuments); AppCenterLog.Info(App.LogTag, "Replace result=" + JsonConvert.SerializeObject(document)); document = await Data.ReadAsync <CustomDocument>(id, DefaultPartitions.UserDocuments); AppCenterLog.Info(App.LogTag, "Read result=" + JsonConvert.SerializeObject(document)); } catch (Exception ex) { AppCenterLog.Error(App.LogTag, "Data person scenario failed", ex); Crashes.TrackError(ex); } }
public RecipeCatalogController(IRecipeService service, UserInformation userInformation) { this.service = service; this.userInformation = userInformation; }
private async void read() { StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile; if (image != null) { try { IRandomAccessStream imageStream = await image.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(imageStream); welimg.Source = bitmapImage; } catch (Exception) { } } try { welcome.Text = "Hello, " + await UserInformation.GetDisplayNameAsync(); welcome.Text = "Hello, " + await UserInformation.GetFirstNameAsync(); } catch (Exception) { welcome.Text = "Hello"; } try { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await localFolder.CreateFileAsync("Important.txt", CreationCollisionOption.OpenIfExists); Stream readStream = await storageFile.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(readStream)) { String text = reader.ReadLine(); if (text == null) { newu = false; if (welcome.Text.Equals("Hello")) { newu = true; button(); } } else { pass = reader.ReadLine(); newu = false; button(); } } } catch (Exception) { } if (newu) { return; } float cg = 0.0f; int credits = 0; float tgp = 0.0f; int tcredits = 0; Boolean newq = false; for (int i = 0; i < 12; i++) { try { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await localFolder.CreateFileAsync("sgpa" + i + ".txt", CreationCollisionOption.OpenIfExists); Stream readStream = await storageFile.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(readStream)) { String text = reader.ReadLine(); if (text == null) { continue; } else { newq = true; cg = (Convert.ToSingle(text)); text = reader.ReadLine(); credits = (Convert.ToInt32(text)); tgp = tgp + (cg * credits); tcredits += credits; } } } catch (Exception) { } } if (newq) { TextBlock1.Visibility = Visibility.Visible; TextBlock1.Text = "Sum of total grade points are " + tgp + "\nSum of total credits is " + tcredits * 10 + "\nYour current CGPA is\n" + (tgp / tcredits).ToString("0.00"); } }
public TitleChildSceneOptionUserSelect(AccountInformation ainfo, int idx, bool back, User[] us) { b = back; ai = ainfo; uinfo = new UserInformation(ai.Users[idx]); index = idx; mvf = (ta, aid, max) => (mai, val) => { if (max > aid) ta[aid].Alpha = val ? 1.0 : 0.5; }; users = us; opod = new List<StringSprite> { new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 64 - 8, Value = "1st" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 96 - 8, Value = "2nd" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 128 - 8, Value = "3rd" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 160 - 8, Value = "4th" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 192 - 8, Value = "5th" } }; next = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Blue) { X = 64, Y = nextpos - 8, Value = "決定" }; opsn = new List<StringSprite> { new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 64 - 8, Value = "" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 96 - 8, Value = "" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 128 - 8, Value = "" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 160 - 8, Value = "" }, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 128, Y = 192 - 8, Value = "" } }; mal = new List<MenuAllocationInformation> { new MenuAllocationInformation(){ X = 32, Y = 64 }, new MenuAllocationInformation(){ X = 32, Y = 96 }, new MenuAllocationInformation(){ X = 32, Y = 128 }, new MenuAllocationInformation(){ X = 32, Y = 160 }, new MenuAllocationInformation(){ X = 32, Y = 192 }, new MenuAllocationInformation(){ X = 32, Y = 224 }, }; opop = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 64, Y = 224 - 8, Value = "編集 削除" }; opopmal = new List<MenuAllocationInformation> { new MenuAllocationInformation(){X=40,Y=224}, new MenuAllocationInformation(){X=136,Y=224}, }; okcancel = new List<StringSprite> { new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "OK", X = 528, Y = 180 , Alpha = 0}, new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { Value = "キャンセル", X = 528, Y = 204, Alpha = 0 } }; ocmal = new List<MenuAllocationInformation> { new MenuAllocationInformation(){X=512,Y=180+8,IsAvailable=false}, new MenuAllocationInformation(){X=512,Y=204+8}, }; ouip = new OptionUserInformationPanel(ai.Tokens[index], ai.Users[index]) { ChangingAction = (p) => { //タイムラグ対策 if (cs != 2) return; if (p && users.Where(q => q != null).All(q => q.Id != ouip.SourceUser.Id)) { valid.Value = "オプションOK"; valid.Color = CommonObjects.Colors.Blue; ocmal[0].IsAvailable = true; } else { valid.Value = "オプションNG"; valid.Color = CommonObjects.Colors.Red; ocmsel = 1; ocmal[0].IsAvailable = false; mc.AddSubOperation(SpritePatterns.VerticalMove(10, ocmal[ocmsel].Y, Easing.OutQuad)); } } }; for (int i = 0; i < opopmal.Count; i++) { opopmal[i].Lefter = opopmal[(i + opopmal.Count - 1) % opopmal.Count]; opopmal[i].Righter = opopmal[(i + 1) % opopmal.Count]; } for (int i = 0; i < ocmal.Count; i++) { ocmal[i].Upper = ocmal[(i + ocmal.Count - 1) % ocmal.Count]; ocmal[i].Lower = ocmal[(i + 1) % ocmal.Count]; ocmal[i].AvailableChangingAction = mvf(okcancel, i, okcancel.Count); } for (int i = 0; i < mal.Count; i++) { mal[i].Upper = mal[(i + mal.Count - 1) % mal.Count]; mal[i].Lower = mal[(i + 1) % mal.Count]; mal[i].AvailableChangingAction = mvf(opod, i, opod.Count); mal[i].IsAvailable = (i < users.Length && users[i] != null) || i == mal.Count - 1 || (users.Count(p => p != null) == i); } for (int i = 0; i < opsn.Count; i++) { if (users[i] != null) opsn[i].Value = users[i].ScreenName; } valid = new StringSprite(CommonObjects.FontSystemMedium, CommonObjects.Colors.Black) { X = 320, Y = 216, Value = "オプションOK/NG" }; mc = new MultiAdditionalCoroutineSprite() { Image = CommonObjects.ImageCursor128[1], HomeX = 64, HomeY = 64, ScaleX = 0.25, ScaleY = 0.25 }; cs = 0; ki = null; msel = 0; ocmsel = 0; }
// TODO: tidy up! why return a value when it's passed by ref anyway? /// <summary> /// Retrieves the user information. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="initial">The initial.</param> /// <param name="channel">The channel.</param> /// <returns>the user info</returns> // ReSharper disable UnusedMethodReturnValue.Local private static UserInformation RetrieveUserInformation(string userName, ref UserInformation initial, string channel) // ReSharper restore UnusedMethodReturnValue.Local { try { initial.UserName = userName; if (initial.EditCount == 0) { initial.EditCount = Editcount.GetEditCount(userName, channel); } initial.UserGroups = Rights.GetRights(userName, channel); initial.RegistrationDate = Registration.GetRegistrationDate(userName, channel); initial.UserPage = GetUserPageUrl(userName, channel); initial.TalkPage = GetUserTalkPageUrl(userName, channel); initial.UserContributions = GetUserContributionsUrl(userName, channel); initial.UserBlockLog = GetBlockLogUrl(userName, channel); initial.UserAge = Age.GetWikipedianAge(userName, channel); initial.EditRate = initial.EditCount / initial.UserAge.TotalDays; var baseWiki = LegacyConfig.Singleton()["baseWiki", channel]; // FIXME: ServiceLocator - mw site repo var mediaWikiSiteRepository = ServiceLocator.Current.GetInstance<IMediaWikiSiteRepository>(); MediaWikiSite mediaWikiSite = mediaWikiSiteRepository.GetById(int.Parse(baseWiki)); BlockInformation bi = mediaWikiSite.GetBlockInformation(userName).FirstOrDefault(); initial.BlockInformation = bi.Id ?? string.Empty; return initial; } catch (NullReferenceException ex) { ServiceLocator.Current.GetInstance<ILogger>().Error(ex.Message, ex); throw new InvalidOperationException(); } }
public void LoadUsers() { uinfo = new UserInformation[ainfo.Accounts.Length]; uips = new UserInformationPanel[ainfo.Accounts.Length]; for (int i = 0; i < uips.Length; i++) uips[i] = new UserInformationPanel(); for (int i = 0; i < ainfo.Accounts.Length; i++) { if (!ainfo.HasGot[i]) { ainfo.HasGot[i] = true; var t = Tokens.Create( Kbtter.Instance.Setting.Consumer.Key, Kbtter.Instance.Setting.Consumer.Secret, ainfo.Accounts[i].AccessToken, ainfo.Accounts[i].AccessTokenSecret); var ta = i; ainfo.Tokens[i] = t; t.Users.ShowAsync(user_id => ainfo.Accounts[ta].UserId) .ContinueWith(p => { if (p.IsFaulted) return; ainfo.Users[ta] = p.Result; ainfo.HasGot[ta] = true; uinfo[ta] = new UserInformation(p.Result); uips[ta].RefreshUserInfo(uinfo[ta]); }); } else { uinfo[i] = new UserInformation(ainfo.Users[i]); uips[i].RefreshUserInfo(uinfo[i]); } } }
private void LoginScipt(string paramScriptPath, List <string> groups, UserInformation userInfo, LdapServer serv, Session session) { int len_groups = groups.Count; int i = 0; do { string script_path = paramScriptPath; if (!script_path.Contains("%g")) { len_groups = 0; // ignore groups } script_path = script_path.Replace("%u", userInfo.Username.Trim()); // Verifica se o usuário está em um grupo. if (len_groups > 0 && i < len_groups) { if (serv.MemberOfGroup(userInfo.Username, groups[i].Trim())) { script_path = script_path.Replace("%g", groups[i].Trim()); m_logger.DebugFormat("Replacing %g to |{0}| ", groups[i].Trim()); } else { i++; continue; } } TransferOperationResult transferResult; if (!session.FileExists(script_path)) { i++; if (i >= len_groups) { return; } m_logger.DebugFormat("File {0} doesn't exist!", script_path); continue; } m_logger.DebugFormat("Downloading file {0} ", script_path); transferResult = session.GetFiles(script_path, @"D:\", false, null); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { m_logger.DebugFormat("Downalod of {0} succeeded", transfer.FileName); } int index = script_path.LastIndexOf(@"\"); if (index < 0) { index = script_path.LastIndexOf("/"); } if (index < 0) { index = -1; } script_path = script_path.Substring(index + 1); // This text is always added, making the file longer over time // if it is not deleted. m_logger.DebugFormat("Saving script {0}", script_path); using (StreamWriter sw = new StreamWriter(getPathToLoginScript(userInfo.Username), true)) { System.IO.StreamReader file = new System.IO.StreamReader(@"D:\" + script_path); string line = ""; while ((line = file.ReadLine()) != null) { sw.WriteLine(line); } file.Close(); } ExecuteCommand(@"DEL D:\" + script_path); i++; } while (i < len_groups); }
private void OnBtnClick(object sender, RoutedEventArgs e) { Button btn = sender as Button; if (btn.Name == "btnLogon") { LoginWindow loginWnd = new LoginWindow(); loginWnd.Owner = App.Current.MainWindow; loginWnd.ShowActivated = true; Nullable <bool> dialogResult = loginWnd.ShowDialog(); if (dialogResult == true) { VOP.MainWindow.m_bLogon = true; VOP.MainWindow.m_strPhoneNumber = loginWnd.m_strPhoneNumber; UserInformation userInformation = new UserInformation(); string strResult = ""; UserInformation.GetUserInfo(VOP.MainWindow.m_strPhoneNumber, ref userInformation, ref strResult); if (userInformation.m_strRealName.Length > 0) { tbUserName.Text = userInformation.m_strRealName + String.Format("({0})", VOP.MainWindow.m_strPhoneNumber); } else { tbUserName.Text = VOP.MainWindow.m_strPhoneNumber; } tbUserName.Visibility = Visibility.Visible; btnLogon.Visibility = Visibility.Hidden; ((MainWindow)App.Current.MainWindow).UpdateLogonBtnStatus(true); btnModifyUserInfo.IsEnabled = true; } } else if (btn.Name == "btnModifyUserInfo") { ((MainWindow)App.Current.MainWindow).ShowModifyUserInfoView(); } else if (btn.Name == "btnConsumable") { PurchaseWindow win = new PurchaseWindow(); win.Owner = App.Current.MainWindow; win.ShowDialog(); } else if (btn.Name == "btnRewardPoints") { } else if (btn.Name == "btnMaintainStation") { MaintainWindow mw = new MaintainWindow(); mw.Owner = App.Current.MainWindow; mw.ShowDialog(); } else if (btn.Name == "btnFWDownload") { try { System.Diagnostics.Process.Start(@"http://function.iprintworks.cn/downapp/down.html"); } catch { } } else if (btn.Name == "btnAbout") { AboutWindow wnd = new AboutWindow(); wnd.Owner = App.Current.MainWindow; wnd.ShowDialog(); } else if (btn.Name == "btnBack") { ((MainWindow)App.Current.MainWindow).ShowUserCenterView(false); } else if (btn.Name == "btnImprovePlan") { ((MainWindow)App.Current.MainWindow).ShowCRMAgreementWindow(); } }
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo) { m_logger.Debug("ChangePassword()"); UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); using (LdapServer serv = new LdapServer()) { try { string[] hosts = Settings.Store.LdapHost; // Authenticate using old password BooleanResult result = serv.Authenticate(userInfo.Username, userInfo.oldPassword, properties); if (!result.Success) { return(new BooleanResult { Success = false, Message = "Password change failed: Invalid LDAP username or password." }); } // Set the password attributes List <AttributeEntry> attribs = CPAttributeSettings.Load(); foreach (AttributeEntry entry in attribs) { if (entry.Method.HasFlag(Methods.ADPWD)) { foreach (string server in hosts) { if (Abstractions.WindowsApi.pInvokes.UserChangePassword(server, userInfo.Username, userInfo.oldPassword, userInfo.Password) == "") { break; } } continue; } if (entry.Method.HasFlag(Methods.Timestamps) || entry.Method.HasFlag(Methods.Timestampd) || entry.Method.HasFlag(Methods.Timestampt)) { TimeMethod time = TimeMethod.methods[entry.Method]; m_logger.DebugFormat("Setting attribute {0} using method {1}", entry.Name, time.Name); if (!serv.SetUserAttribute(userInfo.Username, entry.Name, time.time())) { return new BooleanResult { Success = false, Message = "LDAPplugin failed by setting an attribute\nFor more details please consult the log!" } } ; } else { AttribMethod hasher = AttribMethod.methods[entry.Method]; m_logger.DebugFormat("Setting attribute {0} using method {1}", entry.Name, hasher.Name); if (!serv.SetUserAttribute(userInfo.Username, entry.Name, hasher.hash(userInfo.Password))) { return new BooleanResult { Success = false, Message = "LDAPplugin failed by setting an attribute\nFor more details please consult the log!" } } ; } } return(new BooleanResult { Success = true, Message = "LDAP password successfully changed" }); } catch (Exception e) { m_logger.ErrorFormat("Exception in ChangePassword: {0}", e); return(new BooleanResult() { Success = false, Message = "Error in LDAP plugin." }); } } }
/// <summary> /// Sends the long user info. /// </summary> /// <param name="userInformation">The user information.</param> private void SendLongUserInfo(UserInformation userInformation) { this.response.Respond(userInformation.UserPage); this.response.Respond(userInformation.TalkPage); this.response.Respond(userInformation.UserContributions); this.response.Respond(userInformation.UserBlockLog); this.response.Respond(userInformation.BlockInformation); string message; var messageService = this.CommandServiceHelper.MessageService; if (userInformation.UserGroups != string.Empty) { string[] messageParameters = { userInformation.UserName, userInformation.UserGroups }; message = messageService.RetrieveMessage("cmdRightsList", this.Channel, messageParameters); } else { string[] messageParameters = { userInformation.UserName }; message = messageService.RetrieveMessage("cmdRightsNone", this.Channel, messageParameters); } this.response.Respond(message); string[] messageParameters2 = { userInformation.EditCount.ToString(CultureInfo.InvariantCulture), userInformation.UserName }; message = messageService.RetrieveMessage("editCount", this.Channel, messageParameters2); this.response.Respond(message); string[] messageParameters3 = { userInformation.UserName, userInformation.RegistrationDate.ToString("hh:mm:ss t"), userInformation.RegistrationDate.ToString("d MMMM yyyy") }; message = messageService.RetrieveMessage("registrationDate", this.Channel, messageParameters3); this.response.Respond(message); string[] messageParameters4 = { userInformation.UserName, userInformation.EditRate.ToString(CultureInfo.InvariantCulture) }; message = messageService.RetrieveMessage("editRate", this.Channel, messageParameters4); this.response.Respond(message); }
public static void SyncUserInfoToLocalUser(UserInformation userInfo) { LocalAccount la = new LocalAccount(userInfo); la.SyncToLocalUser(); }
public CopyCIReferenceViewModel(UserInformation userInformation, WPF.MDI.MdiChild mdiChild, DDCI_INFO oldActiveEntity, OperationMode operationMode) { bll = new FeasibleReportAndCostSheet(userInformation); EnquiryReceivedOn = bll.ServerDateTime(); OldCIReferenceDataSource = bll.GetCIReferenceNumber().ToDataTable <V_CI_REFERENCE_NUMBER>().DefaultView; CIReferenceZoneDataSource = bll.GetZoneDetails().ToDataTable <CI_REFERENCE_ZONE>().DefaultView; OldActiveEntity = oldActiveEntity; if (!OldActiveEntity.IsNotNullOrEmpty()) { OldActiveEntity = new DDCI_INFO(); } EntityPrimaryKey = oldActiveEntity.IDPK; #region DropdownColumns Settins CiReferenceZoneDropDownItems = new ObservableCollection <DropdownColumns>() { new DropdownColumns() { ColumnName = "CODE", ColumnDesc = "Zone Code", ColumnWidth = "25*" }, new DropdownColumns() { ColumnName = "DESCRIPTION", ColumnDesc = "Zone", ColumnWidth = "75*" } }; OldCIReferenceDropDownItems = new ObservableCollection <DropdownColumns>() { new DropdownColumns() { ColumnName = "CI_REFERENCE", ColumnDesc = "CI Reference", ColumnWidth = "90" }, new DropdownColumns() { ColumnName = "FRCS_DATE", ColumnDesc = "FRCS Date", ColumnWidth = "80" }, new DropdownColumns() { ColumnName = "CUST_DWG_NO", ColumnDesc = "Drawing No.", ColumnWidth = "100" }, new DropdownColumns() { ColumnName = "CUST_CODE", ColumnDesc = "Customer Code", ColumnWidth = "100" }, new DropdownColumns() { ColumnName = "FINISH_CODE", ColumnDesc = "Finish Code", ColumnWidth = "80" }, new DropdownColumns() { ColumnName = "CUST_DWG_NO_ISSUE", ColumnDesc = "Customer Drawing Issue No.", ColumnWidth = "175" }, new DropdownColumns() { ColumnName = "CUST_STD_DATE", ColumnDesc = "Customer STD Date ", ColumnWidth = "150" } }; #endregion this.ciReferenceEndEditCommand = new DelegateCommand(this.ciReferenceEndEdit); this.oldReferenceSelectedItemChangedCommand = new DelegateCommand(this.OldCIReferenceChanged); this.enquiryReceivedOnChangedCommand = new DelegateCommand(this.EnquiryReceivedOnChanged); this.saveCommand = new DelegateCommand(this.SaveSubmitCommand); this.ciReferenceZoneSelectedItemChangedCommand = new DelegateCommand(this.CIReferenceZoneChanged); ActionPermission = bll.GetUserRights("CIReferenceCopy"); ActionPermission.AddNew = true; ActionPermission.Edit = true; ActionPermission.Save = true; ActionPermission.Close = true; ActionPermission.Print = true; ActionMode = operationMode; }
public LocalAccount(UserInformation userInfo) { UserInfo = userInfo; }
public BooleanResult AuthorizeUser(SessionProperties properties) { m_logger.Debug("LDAP Plugin Authorization"); bool requireAuth = Settings.Store.AuthzRequireAuth; // Get the authz rules from registry List <GroupAuthzRule> rules = GroupRuleLoader.GetAuthzRules(); // Get the LDAP server object LdapServer serv = properties.GetTrackedSingle <LdapServer>(); // If LDAP server object is not found, then something went wrong in authentication. // We allow or deny based on setting if (serv == null) { m_logger.ErrorFormat("AuthorizeUser: Internal error, LdapServer object not available."); // LdapServer is not available, allow or deny based on settings. return(new BooleanResult() { Success = Settings.Store.AuthzAllowOnError, Message = "LDAP server unavailable." }); } // If we require authentication, and we failed to auth this user, then we // fail authorization. Note that we do this AFTER checking the LDAP server object // because we may want to succeed if the authentication failed due to server // being unavailable. PluginActivityInformation actInfo = properties.GetTrackedSingle <PluginActivityInformation>(); if (requireAuth && !WeAuthedThisUser(actInfo)) { m_logger.InfoFormat("Deny because LDAP auth failed, and configured to require LDAP auth."); return(new BooleanResult() { Success = false, Message = "Deny because LDAP authentication failed, or did not execute." }); } // Apply the authorization rules try { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); // Bind for searching if we have rules to process. If there's only one, it's the // default rule which doesn't require searching the LDAP tree. if (rules.Count > 0) { this.BindForAuthzOrGatewaySearch(serv); } foreach (GroupAuthzRule rule in rules) { bool inGroup = false; string path = rule.path.Replace("%u", userInfo.Username); string filter = rule.filter.Replace("%u", userInfo.Username); inGroup = serv.GetUserAttribValue(path, filter, rule.SearchScope, new string[] { "dn" }).Count > 0; m_logger.DebugFormat("User {0} {1} {2} {3}", userInfo.Username, inGroup ? "is" : "is not", filter, path); if (rule.RuleMatch(inGroup)) { if (rule.AllowOnMatch) { return new BooleanResult() { Success = true, Message = string.Format("Allow via rule: \"{0}\"", rule.ToString()) } } ; else { return new BooleanResult() { Success = false, Message = string.Format("Deny via rule: \"{0}\"", rule.ToString()) } }; } } // If there is no matching rule use default. allow or deny if ((bool)Settings.Store.AuthzDefault) { return new BooleanResult() { Success = true, Message = "" } } ; else { return new BooleanResult() { Success = false, Message = String.Format("You are not allowed to login! No matching rule found! Default rule:{0}", (bool)Settings.Store.AuthzDefault ? "Allow" : "Deny") } }; } catch (Exception e) { if (e is LdapException) { LdapException ldapEx = (e as LdapException); if (ldapEx.ErrorCode == 81) { // Server can't be contacted, set server object to null m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message); serv.Close(); properties.AddTrackedSingle <LdapServer>(null); return(new BooleanResult { Success = Settings.Store.AuthzAllowOnError, Message = "Failed to contact LDAP server." }); } else if (ldapEx.ErrorCode == 49) { // This is invalid credentials, return false, but server object should remain connected m_logger.ErrorFormat("LDAP bind failed: invalid credentials."); return(new BooleanResult { Success = false, Message = "Authorization via LDAP failed. Invalid credentials." }); } } // Unexpected error, let the PluginDriver catch m_logger.ErrorFormat("Error during authorization: {0}", e); throw; } }
public MainFrameViewModel(UserInformation currentUser) { PathNavigateCommand = new DependencyCommand(PathNavigate, DependencyCommand.AlwaysCan); UserInformation = new UserInformationViewModel(currentUser); MainContainerContent = new FileListViewModel(); }
public void CurrentUser() { //ExStart //ExFor:Document.UpdateFields //ExFor:FieldOptions.CurrentUser //ExFor:UserInformation //ExFor:UserInformation.Name //ExFor:UserInformation.Initials //ExFor:UserInformation.Address //ExFor:UserInformation.DefaultUser //ExSummary:Shows how to set user details, and display them using fields. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create a UserInformation object and set it as the data source for fields that display user information. UserInformation userInformation = new UserInformation { Name = "John Doe", Initials = "J. D.", Address = "123 Main Street" }; doc.FieldOptions.CurrentUser = userInformation; // Insert USERNAME, USERINITIALS, and USERADDRESS fields, which display values of // the respective properties of the UserInformation object that we have created above. Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result); Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result); Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result); // The field options object also has a static default user that fields from all documents can refer to. UserInformation.DefaultUser.Name = "Default User"; UserInformation.DefaultUser.Initials = "D. U."; UserInformation.DefaultUser.Address = "One Microsoft Way"; doc.FieldOptions.CurrentUser = UserInformation.DefaultUser; Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result); Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result); Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result); doc.UpdateFields(); doc.Save(ArtifactsDir + "FieldOptions.CurrentUser.docx"); //ExEnd doc = new Document(ArtifactsDir + "FieldOptions.CurrentUser.docx"); Assert.Null(doc.FieldOptions.CurrentUser); FieldUserName fieldUserName = (FieldUserName)doc.Range.Fields[0]; Assert.Null(fieldUserName.UserName); Assert.AreEqual("Default User", fieldUserName.Result); FieldUserInitials fieldUserInitials = (FieldUserInitials)doc.Range.Fields[1]; Assert.Null(fieldUserInitials.UserInitials); Assert.AreEqual("D. U.", fieldUserInitials.Result); FieldUserAddress fieldUserAddress = (FieldUserAddress)doc.Range.Fields[2]; Assert.Null(fieldUserAddress.UserAddress); Assert.AreEqual("One Microsoft Way", fieldUserAddress.Result); }
public async Task InitData(UserManager <User> userManager, RoleManager <IdentityRole> roleManager) { if ((await userManager.FindByEmailAsync("*****@*****.**")) != null) { return; } var comments = new List <Comment> { new Comment { Text = "first comment" }, new Comment { Text = "second comment" } }; var posts = new List <Post> { new Post { Text = "First Post of Dimasik", Comments = comments }, new Post { Text = "Second Post of Dimasik" }, }; UserInformation uinfo1 = new UserInformation() { FirstName = "Dmitriy", SecondName = "Belotskiy", Birthday = new DateTime(2001, 04, 26), City = "Brest", Gender = Gender.MALE, PlaceOfStudy = "BSUIR", Status = "I love ASP.NET Core! <3", }; UserInformation uinfo2 = new UserInformation() { FirstName = "Alex", SecondName = "Boghdan", Birthday = new DateTime(2001, 04, 26), City = "Brest", Gender = Gender.MALE, PlaceOfStudy = "Будущая киберкотлета", Status = "Жмурика, я ультраслабый", }; User user1 = new User() { Email = "*****@*****.**", UserName = "******", UserInformation = uinfo1, Posts = posts }; User user2 = new User() { Email = "*****@*****.**", UserName = "******", UserInformation = uinfo2, Comments = comments }; var result = await userManager.CreateAsync(user1, "Password"); if (result.Succeeded) { await userManager.AddToRoleAsync(user1, "user"); } result = await userManager.CreateAsync(user2, "Password"); if (result.Succeeded) { await userManager.AddToRoleAsync(user2, "user"); } }
/// <summary> /// Delete all the items in a folder. /// </summary> /// <param name="userInformation">The user information which contains user created items</param> private void DeleteItemsInFolder(UserInformation userInformation) { foreach (CreatedItems createdItems in userInformation.UserCreatedItems) { SyncStore syncStore = this.InitializeSync(createdItems.CollectionId); SyncStore result = this.SyncChanges(syncStore.SyncKey, createdItems.CollectionId, null); string syncKey = result.SyncKey; int retryCount = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", this.Site)); int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", this.Site)); int counter = 0; do { Thread.Sleep(waitTime); if (result != null) { if (result.CollectionStatus == 1) { break; } } counter++; } while (counter < retryCount / 10); if (result.AddElements != null) { SyncRequest deleteRequest; foreach (Sync syncItem in result.AddElements) { if (createdItems.CollectionId == userInformation.CalendarCollectionId) { foreach (string subject in createdItems.ItemSubject) { if (syncItem.Calendar != null) { if (syncItem.Calendar.Subject.Equals(subject, StringComparison.CurrentCultureIgnoreCase)) { deleteRequest = CreateSyncPermanentDeleteRequest(syncKey, createdItems.CollectionId, syncItem.ServerId); SyncStore deleteSyncResult = this.EMAILAdapter.Sync(deleteRequest); syncKey = deleteSyncResult.SyncKey; Site.Assert.AreEqual<byte>(1, deleteSyncResult.CollectionStatus, "Item should be deleted."); } } } } else { List<Request.SyncCollectionDelete> deleteData = new List<Request.SyncCollectionDelete>(); foreach (string subject in createdItems.ItemSubject) { string serverId = null; if (result != null) { foreach (Sync item in result.AddElements) { if (item.Email.Subject != null && item.Email.Subject.Contains(subject)) { serverId = item.ServerId; break; } if (item.Calendar.Subject != null && item.Calendar.Subject.Contains(subject)) { serverId = item.ServerId; break; } } } if (serverId != null) { deleteData.Add(new Request.SyncCollectionDelete() { ServerId = serverId }); } } if (deleteData.Count > 0) { Request.SyncCollection syncCollection = TestSuiteHelper.CreateSyncCollection(syncKey, createdItems.CollectionId); syncCollection.Commands = deleteData.ToArray(); syncCollection.DeletesAsMoves = false; syncCollection.DeletesAsMovesSpecified = true; SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection }); SyncStore deleteResult = this.EMAILAdapter.Sync(syncRequest); syncKey = deleteResult.SyncKey; Site.Assert.AreEqual<byte>( 1, deleteResult.CollectionStatus, "The value of Status should be 1 to indicate the Sync command executes successfully."); } } } } } }
async void SignInIOS() { try { // Authenticate UserInformation userInfo = await Auth.SignInAsync(); string accountId = userInfo.AccountId; // Testing //Act1 act = new Act1 { Name = "Run", Color = "Blue", Duration = "10:10:10" }; //user.Acts.Add(act); //Preferences.Clear(); //Check if new user if (Preferences.Get("UserID", null) == null) { User user = new User { Points = 100 }; Act1 act = new Act1 { Name = "Test Activity", Color = "Blue", Image = "Walk.png", Duration = "00:00:00", DateUtc = DateTime.UtcNow }; user.Acts.Add(act); Preferences.Set("UserID", user.Id.ToString()); // Create new user await Data.CreateAsync(user.Id.ToString(), user, DefaultPartitions.UserDocuments); } // For achievements var fetchedUser = await Data.ReadAsync <User>(Preferences.Get("UserID", null), DefaultPartitions.UserDocuments); var fetched = await Data.ReadAsync <AchievementRetriever>("public-achievements", DefaultPartitions.AppDocuments); var result = JsonConvert.DeserializeObject <AchievementRetriever>(fetched.JsonValue.ToString()); var resultUser = JsonConvert.DeserializeObject <User>(fetchedUser.JsonValue.ToString()); foreach (Achievements i in result.Achs) { //resultUser.Achs.Add(i); Console.WriteLine(i.AID + "/" + i.Name + "/" + i.Description + "/" + i.Points); } //await Data.ReplaceAsync(resultUser.Id.ToString(), resultUser, DefaultPartitions.UserDocuments); await this.Navigation.PushAsync(new MainPage()); Console.WriteLine("Debug 1: " + accountId); } catch (Exception e) { Console.WriteLine("Debug 1: Unable to sign in"); // Do something with sign-in failure. } }
public UserInformationForWsBinding() { _userInformation = new UserInformation(); }
public void onClickMailReceive() { MailboxReward mailboxReward = CreateRewardSlot.mailboxRewards[MailListManager.siblingIndex]; string jsonData; //userinfo 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/userInformation.json"); userInformation = JsonConvert.DeserializeObject <UserInformation>(JData); //condition 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ConditionData.json"); conditionList = JsonConvert.DeserializeObject <List <Condition_CodeModifier> >(JData); //action 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/Alice/ActionData.json"); actionList = JsonConvert.DeserializeObject <List <Action_CodeModifier> >(JData); //Item 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ItemsInfo.json"); itemList = JsonConvert.DeserializeObject <List <JsonEquippableItem> >(JData); //character 모두 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/CharacterInfo.json"); characterList = JsonConvert.DeserializeObject <List <CharacterInformation_item> >(JData); userInformation.experience += mailboxReward.experience_Account; userInformation.gem += mailboxReward.gem; userInformation.money += mailboxReward.money; jsonData = JsonConvert.SerializeObject(userInformation); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/userInformation.json", jsonData); //userInformation 저장 완료. foreach (Condition_CodeModifier condition in mailboxReward.conditionList) { conditionList.Add(condition); } jsonData = JsonConvert.SerializeObject(conditionList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ConditionData.json", jsonData); //conditionData 저장 완료. foreach (Action_CodeModifier action in mailboxReward.actionList) { actionList.Add(action); } jsonData = JsonConvert.SerializeObject(actionList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/Alice/ActionData.json", jsonData); //actionData 저장 완료. foreach (JsonEquippableItem item in mailboxReward.itemList) { itemList.Add(item); } jsonData = JsonConvert.SerializeObject(itemList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ItemsInfo.json", jsonData); //item 저장 완료 foreach (CharacterInformation_item character in characterList) { character.experience += mailboxReward.experience_Character; } jsonData = JsonConvert.SerializeObject(characterList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/CharacterInfo.json", jsonData); //character별 경험치 저장 완료. List <MailboxReward> mailboxRewards = new List <MailboxReward>(); Debug.Log("CreateRewardSlot.mailboxRewards.Count = " + CreateRewardSlot.mailboxRewards.Count); Debug.Log("MailListManager.siblingIndex = " + MailListManager.siblingIndex); for (int i = 0; i < CreateRewardSlot.mailboxRewards.Count; i++) { if (i == MailListManager.siblingIndex) { continue; } else { mailboxRewards.Add(CreateRewardSlot.mailboxRewards[i]); } } CreateRewardSlot.mailboxRewards = mailboxRewards; jsonData = JsonConvert.SerializeObject(mailboxRewards); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/mailboxData.json", jsonData); Destroy(CreateRewardSlot.newRewardSlot[MailListManager.siblingIndex]); newMailPanel.gameObject.SetActive(false); }
public async Task ChangePassword( UserInformation information ) { Session session = new Session( ChangePasswordPart ); session.AddParameter( ChangePasswordParameter, information ); await Load( session ); }
public async Task<CatalitCredentials> RegisterDefault( CancellationToken cancellationToken ) { string login = "******" + _deviceInfoService.DeviceId;//.Substring( 0, 16 ); var creds = new CatalitCredentials { IsRealAccount = false, Password = "******", Login = login }; bool relogin = false; try { var userInfo = await Register(creds, cancellationToken, additionalParams: false); creds.Sid = userInfo.SessionId; } catch (CatalitRegistrationException e) { //already exists if (e.ErrorCode == 1 || e.ErrorCode == 100) { relogin = true; } else { throw; } } catch (Exception ex) { ex = ex; throw; } if( relogin ) { try { var userInfo = await Authorize(creds, cancellationToken); creds.Sid = userInfo.SessionId; } catch (Exception ex) { var stackTace = ex.StackTrace; } } UserInformation = null; return creds; }
public void RefreshUserInfo(UserInformation i) { info = i; username.Value = info.SourceUser.ScreenName; shots.Value = info.ShotStrength.ToString(); bombs.Value = info.BombStrength.ToString(); defp.Value = info.DefaultPlayers.ToString(); defb.Value = info.DefaultBombs.ToString(); grep.Value = info.GrazePoints.ToString(); colr.Value = info.CollisionRadius.ToString(); u_tw.Value = info.SourceUser.StatusesCount.ToString(); u_fav.Value = info.SourceUser.FavouritesCount.ToString(); u_fr.Value = info.SourceUser.FriendsCount.ToString(); u_fo.Value = info.SourceUser.FollowersCount.ToString(); var target = CommonObjects.GetUserFilePath(string.Format("{0}.{1}", info.SourceUser.Id, "png")); if (!File.Exists(target)) { using (var wc = new WebClient()) using (var st = wc.OpenRead(info.SourceUser.ProfileImageUrlHttps.ToString().Replace("_normal.png", ".png"))) { var bm = new Bitmap(st); var sav = new Bitmap(bm, 96, 96); try { sav.Save(target); } catch { } } } uim.Image = DX.LoadGraph(target); }
public async Task<UserInformation> MergeAccounts( string userAccountSid, CatalitCredentials mergedAccount, CancellationToken cancellationToken ) { if( mergedAccount != null ) { var parameters = new Dictionary<string, object> { {"sid", userAccountSid}, {"user_login", mergedAccount.Login}, {"user_passwd", mergedAccount.Password}, }; var userInfo = await _client.MergeAccounts( parameters, cancellationToken ); UserInformation = userInfo; return userInfo; } throw new CatalitNoCredentialException(); }
/// <summary> /// Change user to call active sync operations and resynchronize the collection hierarchy. /// </summary> /// <param name="userInformation">The information of the user that will switch to.</param> /// <param name="isFolderSyncNeeded">A boolean value indicates whether needs to synchronize the folder hierarchy.</param> protected void SwitchUser(UserInformation userInformation, bool isFolderSyncNeeded) { this.ASAIRSAdapter.SwitchUser(userInformation.UserName, userInformation.UserPassword, userInformation.UserDomain); if (isFolderSyncNeeded) { FolderSyncResponse folderSyncResponse = this.FolderSync(); // Get the folder collectionId of User1 if (userInformation.UserName == this.User1Information.UserName) { if (string.IsNullOrEmpty(this.User1Information.InboxCollectionId)) { this.User1Information.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site); } if (string.IsNullOrEmpty(this.User1Information.ContactsCollectionId)) { this.User1Information.ContactsCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Contacts, this.Site); } if (string.IsNullOrEmpty(this.User1Information.CalendarCollectionId)) { this.User1Information.CalendarCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Calendar, this.Site); } } // Get the folder collectionId of User2 if (userInformation.UserName == this.User2Information.UserName) { if (string.IsNullOrEmpty(this.User2Information.InboxCollectionId)) { this.User2Information.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site); } if (string.IsNullOrEmpty(this.User2Information.CalendarCollectionId)) { this.User2Information.CalendarCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Calendar, this.Site); } } } }
protected void Button1_Click(object sender, EventArgs e) { UserStore <IdentityUser> userStore = new UserStore <IdentityUser>(); // This will instantiates a connection to a new DB, but we already have one so let's use thats connection string: userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager. ConnectionStrings["GarageConnectionString"].ConnectionString; UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore); // Create new user and try to store in the DB IdentityUser user = new IdentityUser(); user.UserName = txtUserName.Text; if (txtPassword.Text == txtConfirmPassword.Text) { try { // Create user object. // Database will be created/expanded automatically. IdentityResult result = manager.Create(user, txtPassword.Text); if (result.Succeeded) { UserInformation info = new UserInformation { Address = txtAddress.Text, FirstName = txtFirstName.Text, LastName = txtLastName.Text, PostalCode = Convert.ToInt32(txtPostalCode.Text), GUID = user.Id }; // Sending the UserInformation to the DB: UserInfoModel model = new UserInfoModel(); model.InsertUserInformation(info); // Store user in DB var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; // Set to log in new user by Cookie. var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); // Log in the new user and redirect to homepage authenticationManager.SignIn(new AuthenticationProperties(), userIdentity); Response.Redirect("~/Index.aspx"); } else { litStatus.Text = result.Errors.FirstOrDefault(); } } catch (Exception ex) { litStatus.Text = ex.ToString(); } } else { litStatus.Text = "Passwords must match"; } }
public async Task ChangeUserInfo( UserInformation userInfo, CancellationToken cancellationToken ) { if( userInfo != null ) { var parameters = new Dictionary<string, object> { {"user-id", userInfo.UserId}, {"first-name", userInfo.FirstName}, {"last-name", userInfo.LastName}, {"middle-name", userInfo.MiddleName}, {"mail", userInfo.Email}, {"www", userInfo.Web}, {"phone", userInfo.Phone}, {"city", userInfo.City}, {"curpass", userInfo.OldPassword}, }; if( !string.IsNullOrEmpty( userInfo.NewPassword ) ) { parameters.Add( "new_pwd1", userInfo.NewPassword ); } await _client.ChangeUserInfo( parameters, cancellationToken ); UserInformation = userInfo; } else { throw new CatalitNoCredentialException(); } }
private async Task CreditCardInfoAsync(Session session) { var userInfo = await _profileProvider.GetUserInfo(session.Token, true); if (userInfo == null) return; if (_userInformation == null) _userInformation = userInfo; var cred = _credentialsProvider.ProvideCredentials(session.Token); if (!userInfo.CanRebill.Equals("0") && cred != null && !string.IsNullOrEmpty(cred.UserId) && userInfo.UserId == cred.UserId && !string.IsNullOrEmpty(cred.CanRebill) && !cred.CanRebill.Equals("0")) { var box = new Dictionary<string, object> { { "isSave", true }, { "isAuth", false } }; var param = XParameters.Empty.ToBuilder() .AddValue("Id", Book.Id) .AddValue("Operation", (int)AccountDepositViewModel.AccountDepositOperationType.AccountDepositOperationTypeCreditCard) .AddValue("ParametersDictionary", ModelsUtils.DictionaryToString(box)).ToImmutable(); _navigationService.Navigate("AccountDeposit", param); } else { if (cred != null) _credentialsProvider.ForgetCredentialsRebill(cred, session.Token); ShowCreditCardView.Execute(Book); } }
public void onClickReceiveWholeRewards() { string jsonData; //userinfo 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/userInformation.json"); userInformation = JsonConvert.DeserializeObject <UserInformation>(JData); //condition 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ConditionData.json"); conditionList = JsonConvert.DeserializeObject <List <Condition_CodeModifier> >(JData); //action 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/Alice/ActionData.json"); actionList = JsonConvert.DeserializeObject <List <Action_CodeModifier> >(JData); //Item 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ItemsInfo.json"); itemList = JsonConvert.DeserializeObject <List <JsonEquippableItem> >(JData); //character 모두 받아오기 JData = File.ReadAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/CharacterInfo.json"); characterList = JsonConvert.DeserializeObject <List <CharacterInformation_item> >(JData); for (int i = 0; i < CreateRewardSlot.mailboxRewards.Count; i++) { MailboxReward mailboxReward = CreateRewardSlot.mailboxRewards[i]; userInformation.experience += mailboxReward.experience_Account; userInformation.gem += mailboxReward.gem; userInformation.money += mailboxReward.money; //userInformation 저장 완료. foreach (Condition_CodeModifier condition in mailboxReward.conditionList) { conditionList.Add(condition); } //conditionData 저장 완료. foreach (Action_CodeModifier action in mailboxReward.actionList) { actionList.Add(action); } //actionData 저장 완료. foreach (JsonEquippableItem item in mailboxReward.itemList) { itemList.Add(item); } //item 저장 완료 foreach (CharacterInformation_item character in characterList) { character.experience += mailboxReward.experience_Character; } Destroy(CreateRewardSlot.newRewardSlot[i]); //character별 경험치 저장 완료. } jsonData = JsonConvert.SerializeObject(userInformation); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/userInformation.json", jsonData); jsonData = JsonConvert.SerializeObject(conditionList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ConditionData.json", jsonData); jsonData = JsonConvert.SerializeObject(actionList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/Alice/ActionData.json", jsonData); jsonData = JsonConvert.SerializeObject(itemList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/ItemsInfo.json", jsonData); jsonData = JsonConvert.SerializeObject(characterList); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/CharacterInfo.json", jsonData); List <MailboxReward> mailboxRewards = new List <MailboxReward>(); jsonData = JsonConvert.SerializeObject(mailboxRewards); jsonData = JValue.Parse(jsonData).ToString(Formatting.Indented); File.WriteAllText(Application.dataPath + "/Resources/Json_AccountInfo/" + AccountID.ToString() + "/mailboxData.json", jsonData); }
public ProductWeightCalcViewModel(UserInformation userInformation, string entityPrimarykey) { }
public async Task<UserInformation> Register(CatalitCredentials credentials, CancellationToken cancellationToken, CatalitCredentials oldCredentials = null, bool additionalParams = true) { if( credentials != null ) { var parameters = new Dictionary<string, object> { {"new_login", credentials.Login}, {"new_pwd1", credentials.Password}, {"phone", credentials.Phone} }; if( credentials.IsRealAccount ) { parameters.Add( "mail", credentials.Login ); } //result contains only sid var result = await _client.Register( parameters, cancellationToken, additionalParams ); if( result != null ) { UserInformation = result; //Activate Coupone if nokia if (_deviceInfoService.IsNokiaDevice) { try { await ActivateNokiaCoupone(result.SessionId, CancellationToken.None); } catch (CatalitActivateCouponeException) { } } //if (oldCredentials != null) //{ // if (!oldCredentials.IsRealAccount) // { // try // { // await ActivateRegistrationCoupone(result.SessionId, CancellationToken.None); // } // catch (CatalitActivateCouponeException) // { // } // } //} return result; } } throw new CatalitNoCredentialException(); }
public static bool NotInvited(this Match @this, UserInformation user) => @this.Status == Status.Invite && [email protected](user.Id, MatchRole.Opponent);
/// <summary> /// Initialize the Test suite. /// </summary> protected override void TestInitialize() { base.TestInitialize(); if (this.NOTEAdapter == null) { this.NOTEAdapter = this.Site.GetAdapter<IMS_ASNOTEAdapter>(); } // If implementation doesn't support this specification [MS-ASNOTE], the case will not start. if (!bool.Parse(Common.GetConfigurationPropertyValue("MS-ASNOTE_Supported", this.Site))) { this.Site.Assert.Inconclusive("This test suite is not supported under current SUT, because MS-ASNOTE_Supported value is set to false in MS-ASNOTE_{0}_SHOULDMAY.deployment.ptfconfig file.", Common.GetSutVersion(this.Site)); } Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Notes class is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); this.ExistingNoteSubjects = new Collection<string>(); // Set the information of user. this.UserInformation = new UserInformation { UserName = Common.GetConfigurationPropertyValue("UserName", this.Site), UserPassword = Common.GetConfigurationPropertyValue("UserPassword", this.Site), UserDomain = Common.GetConfigurationPropertyValue("Domain", this.Site) }; if (Common.GetSutVersion(this.Site) != SutVersion.ExchangeServer2007 || string.Equals(Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "12.1")) { FolderSyncResponse folderSyncResponse = this.NOTEAdapter.FolderSync(Common.CreateFolderSyncRequest("0")); // Get the CollectionId from FolderSync command response. if (string.IsNullOrEmpty(this.UserInformation.NotesCollectionId)) { this.UserInformation.NotesCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Notes, this.Site); } } }
void OnFollower(UserInformation user) { SetUserStatus(user.Service, user.Username, UserStatus.Follower); }
public async Task UpdatePrice() { var userInfo = await _profileProvider.GetUserInfo(CancellationToken.None, false); if (userInfo == null) return; if (_userInformation == null) _userInformation = userInfo; AccoundDifferencePrice = Book.Price - userInfo.Account; if (AccoundDifferencePrice < 10) AccoundDifferencePrice = 10; OnPropertyChanged(new PropertyChangedEventArgs("UpdatePrice")); }
void OnUserLeft(UserInformation user) { lock (userlock) activeusers.Remove(new UserKey(user.Service, user.Username)); }
/// <summary> /// Sends the short user info. /// </summary> /// <param name="userInformation">The user information.</param> private void SendShortUserInfo(UserInformation userInformation) { const string Regex = "^https://en.wikipedia.org/wiki/"; const string ShortUrlAlias = "http://enwp.org/"; var r = new Regex(Regex); userInformation.UserPage = r.Replace(userInformation.UserPage, ShortUrlAlias); userInformation.TalkPage = r.Replace(userInformation.TalkPage, ShortUrlAlias); userInformation.UserBlockLog = r.Replace(userInformation.UserBlockLog, ShortUrlAlias); userInformation.UserContributions = r.Replace(userInformation.UserContributions, ShortUrlAlias); string[] messageParameters = { userInformation.UserName, userInformation.UserPage, userInformation.TalkPage, userInformation.UserContributions, userInformation.UserBlockLog, userInformation.UserGroups, userInformation.UserAge.ToString(), userInformation.RegistrationDate.ToString(CultureInfo.InvariantCulture), userInformation.EditRate.ToString(CultureInfo.InvariantCulture), userInformation.EditCount.ToString(CultureInfo.InvariantCulture), userInformation.BlockInformation == string.Empty ? string.Empty : "BLOCKED" }; string message = this.CommandServiceHelper.MessageService.RetrieveMessage("cmdUserInfoShort", this.Channel, messageParameters); this.response.Respond(message); }
void OnUserJoined(UserInformation user) { lock (userlock) activeusers.Add(new UserKey(user.Service, user.Username)); }
/// <summary> /// Actual command logic /// </summary> /// <returns>The <see cref="CommandResponseHandler"/>.</returns> protected override CommandResponseHandler ExecuteCommand() { var args = this.Arguments; bool useLongInfo = bool.Parse(LegacyConfig.Singleton()["useLongUserInfo", this.Channel]); if (args.Length > 0) { if (args[0].ToLower() == "@long") { useLongInfo = true; GlobalFunctions.PopFromFront(ref args); } if (args[0].ToLower() == "@short") { useLongInfo = false; GlobalFunctions.PopFromFront(ref args); } } var messageService = this.CommandServiceHelper.MessageService; if (args.Length > 0) { string userName = string.Join(" ", args); var userInformation = new UserInformation { EditCount = Editcount.GetEditCount(userName, this.Channel) }; if (userInformation.EditCount == -1) { string[] mparams = { userName }; this.response.Respond(messageService.RetrieveMessage("noSuchUser", this.Channel, mparams)); return this.response; } RetrieveUserInformation(userName, ref userInformation, this.Channel); if (useLongInfo) { this.SendLongUserInfo(userInformation); } else { this.SendShortUserInfo(userInformation); } } else { string[] messageParameters = { "userinfo", "1", args.Length.ToString(CultureInfo.InvariantCulture) }; var notEnoughParamsMessage = messageService.RetrieveMessage(Messages.NotEnoughParameters, this.Channel, messageParameters); this.CommandServiceHelper.Client.SendNotice(this.Source.Nickname, notEnoughParamsMessage); } return this.response; }
protected UserCreatedEvent(UserInformation userInfo, Address registrationAddress, string userName, DateTime eventDate, string source, string version) : base(userName, eventDate, source, version) { UserInformation = userInfo; RegistrationAddress = registrationAddress; }