protected void btnDistribute_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { if (checkValidation(row)) { CheckBox cb = (CheckBox)row.FindControl("selector"); if (cb.Checked) { deptId = Convert.ToInt32(row.Cells[2].Text); stationeryId = Convert.ToInt32(row.Cells[3].Text); new DisbursementController().actionUpdateToDisbursement(deptId, stationeryId); refreshNeed = true; } } } Department department = new DepartmentController().actionGetDepartmentByID(deptId); User head = new UserController().actionGetUserByID(Convert.ToInt32(department.department_head)); String email_title = "Stationery Requesitions Update Information."; String email_body = "<p>Hello " + head.firstname + " " + head.lastname + ",</p>" + "<p>The stationeries requested from "+ department.department_name+ " are distributed " + "to " + department.representative_name + ".</p>" + "<br />Thank you,<br/> Logic University.<p>This is system generated mail. Please do not reply.</p>"; Helper.sendMail(head.email, "*****@*****.**", email_title, email_body); new SMSController().sendSMS(head.phone_number, "Requested stationeries from " + department.department_name + " are distributed."); showSuccess(refreshNeed, "Successfully Recorded Distributed Items."); }
public void UpdatePost_ShouldBeAnnotatedWithHttpPost() { UserController userController = new UserController(); userController .ActionHasAttribute<UserController>(u => u.Update(), typeof(HttpPostAttribute)); }
private void InsertOrUpdateUser() { if (ValidateValues()) { User patient = new User(); if (!string.IsNullOrEmpty(Request.QueryString["Id"])) { patient.UserId = Convert.ToInt32(Request.QueryString["Id"]); } patient.FirstName = txtFirstName.Text; patient.LastName = txtLastName.Text; patient.Address = txtAddress.Text; patient.ZipCode = txtZipCode.Text; patient.City = txtCity.Text; patient.Country = txtCountry.Text; patient.PhoneHome = txtHomePhone.Text; patient.Gender = Convert.ToInt16(ddlGender.SelectedValue); patient.MaritalStatus = Convert.ToInt16(ddlMaritalStatus.SelectedValue); patient.PhoneOffice = txtWorkPhone.Text; patient.SocialSecurityNo = txtSSN.Text; patient.Other = txtOther.Text; patient.UserPassword = txtPassword.Text; patient.DOB = Convert.ToDateTime(txtDOB.Text, frmt); patient.Email = txtEmail.Text; UserController inicontroller = new UserController(); inicontroller.InsertOrUpdateUser(patient); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "gameplay" layout resource SetContentView(Resource.Layout.profile); // find our text fields usernameText = FindViewById<EditText>(Resource.Id.text_username); emailText = FindViewById<EditText>(Resource.Id.text_email); Button button_save_profile = FindViewById<Button>(Resource.Id.button_save_profile); button_save_profile.Click += delegate { // get the current User User user = Session.CurrentSession.User; // update his values user.Login = usernameText.Text; user.EmailAddress = emailText.Text; // set up a request observer ProfileRequestControllerObserver observer = new ProfileRequestControllerObserver(this); // with our observer, set up the request controller UserController userController = new UserController(observer); // pass the user into the controller userController.SetUser(user); ShowDialog(DIALOG_PROGRESS); // submit our changes userController.SubmitUser(); }; }
private UserController _CreateUser(Regulus.Utility.Updater<Regulus.Utility.IUpdatable> frameworkRoot) { Console.WriteLine("建立使用者."); UserController user = new UserController(); frameworkRoot.Add(user); return user; }
/************************************************************ * Event Handlers ************************************************************/ private void Awake() { _userController = global::UserController.Instance; _friendlyFire = ServerData.serverInfo.settings.FriendlyFire; // Object will destroy after 2 seconds Destroy(this.gameObject, 2); }
public void UpdatePost_ReturnsRedirectToShowAction() { UserController userController = new UserController(); userController .Update() .ReturnsRedirectToRouteResult() .ToAction<UserController>(u => u.Show()); }
private void Start() { _teamsController = global::TeamsController.Instance; _cameraController = global::CameraController.Instance; _hudController = global::HUDController.Instance; _hudController.UpdateHealthHUD(Health); _userController = global::UserController.Instance; _userController.SetDead(false); }
public void UserController_Has_a_Login_Method_That_Renders_The_LoginView() { UserController controller = new UserController(userService); ActionResult result = controller.Login(); Assert.IsInstanceOfType(result, typeof(RenderViewResult)); RenderViewResult renderResult = result as RenderViewResult; Assert.AreEqual("Login", renderResult.ViewName); }
public void UserController_Index_Redirects_To_Login() { UserController controller = new UserController(userService); ActionResult result = controller.Index(); Assert.IsInstanceOfType(result, typeof(ActionRedirectResult)); ActionRedirectResult renderResult = result as ActionRedirectResult; Assert.AreEqual("Login", renderResult.Values["action"]); }
public void Index_ReturnsModelWithUserList() { UserController userController = new UserController(); userController .Index() .ReturnsViewResult() .WithModel<IList<User>>() .ShouldNotBeNull(); }
protected void Start_Period(object sender, EventArgs e) { int periodaccountid = Int32.Parse(((LinkButton)sender).CommandArgument); String username = getUsername(); var user = new UserController().ByUsername(username); new TFS.Intranet.Data.Billing.TimesheetController().Insert(username, periodaccountid, user.Rategroup); OpenTimesheets.DataBind(); PendingTimesheets.DataBind(); ReportableTimesheets.DataBind(); }
public void Users() { // Arrange UserController controller = new UserController(); // Act ViewResult result = controller.Users() as ViewResult; // Assert Assert.IsNotNull(result); }
/************************************************** * Event Handlers **************************************************/ private void Awake() { if (networkView.isMine == true) { _userController = global::UserController.Instance; _hudController = global::HUDController.Instance; _damage = 10; _currentAmmo = 40; _fireRate = 0; _hudController.AmmoText.text = _currentAmmo.ToString(); } }
/************************************************************ * Event Handlers ************************************************************/ // Use this for initialization private void Awake() { _teamsController = global::TeamsController.Instance; _animator = GetComponent<Animator>(); _spriteRenderers = GetComponentsInChildren<SpriteRenderer>(); if (networkView.isMine) { _userController = global::UserController.Instance; _userController.SetPlayer(GetComponent<Player>()); } }
protected override void Awake() { base.Awake(); _teamsController = global::TeamsController.Instance; _userController = global::UserController.Instance; _hudController = global::HUDController.Instance; _weaponModels = new List<WeaponModel>(global::WeaponContainer.Instance.WeaponModels); _currentWeapon = _weaponModels.First(w => w.Type == WeaponType.Pistol); ToggleKey = KeyCode.B; ToggleEnabled = true; }
public void Detail_ReturnsViewEditWithModelUser() { UserController userController = new UserController(); userController .Detail(1) .ReturnsViewResult() .WithName("Edit") .WithModel<User>() .ShouldBeEqual(1, u => u.Id) .ShouldBeEqual("John Due", u => u.Name); }
public void UserController_Authenticate_Action_Redirects_For_User1_To_TestUrl() { UserController controller = new UserController(userService); controller.SetFakeControllerContextWithLogin("user1", "first1last1", "testurl"); ActionResult result = controller.Authenticate(); //a redirect result is a pass - which in this case it should be Assert.IsInstanceOfType(result, typeof(HttpRedirectResult)); HttpRedirectResult redirectResult = result as HttpRedirectResult; Assert.AreEqual("testurl", redirectResult.Url); }
public void Can_SaveUser_Info() { var user = new User() { DisplayName = "sdgsdf" }; var identifier = Identifier.Parse("http://uniqueId/"); mockUserRepo.Setup(repo => repo.InsertOrUpdate(user)).Callback(() => { user.Id = 2; }); mockUserRepo.Setup(repo => repo.Save()); mockUserRepo.Setup(repo => repo.All).Returns( (new System.Collections.Generic.List<User>() { new User() {Id = 1,DisplayName = "Admin"}, user }).AsQueryable() ); formService.Setup(serv => serv.SetAuthCookie(null, false)); sessionState.SetupSet(k => { k[SessionConstants.DisplayName] = user.DisplayName; }); var uctrl = new UserController(mockUserRepo.Object, formService.Object); uctrl.ControllerContext = new ControllerContext(mockhttpContext.Object, new RouteData(), uctrl); sessionState.SetupGet(k => k[SessionConstants.OpenId]).Returns(identifier); uctrl .Register(user) .ReturnsRedirectToRouteResult() .RedirectsTo<UserController>(ctr=>ctr.Details(user.Id, true)); //.ForView("Detail").WithViewModel<User>(); sessionState.VerifyAll(); mockUserRepo.VerifyAll(); Assert.NotNull(user.Id); Assert.NotNull(user.OpenId); Assert.NotNull(user.CreatedBy); Assert.NotNull(user.CreatedOn); Assert.NotNull(user.LastUpdatedBy); Assert.NotNull(user.LastUpdatedOn); Assert.AreNotEqual(user.Id, default(int)); Assert.AreEqual(user.Id, 2); Assert.AreEqual(user.OpenId, identifier.ToString()); Assert.AreNotEqual(user.CreatedBy, default(int)); Assert.AreNotEqual(user.CreatedOn, default(DateTime)); Assert.AreNotEqual(user.LastUpdatedBy, default(int)); Assert.AreNotEqual(user.LastUpdatedOn, default(DateTime)); Assert.AreEqual(user.CreatedBy, 1); Assert.AreEqual(user.LastUpdatedBy, 1); }
public Vector3 FindPosition (UserController.UserType type) { foreach (RoomSpaces rs in roomsInfo) { if(rs.uType == type){ foreach(RoomPosition rp in rs.positions){ if(rp.isFree){ rp.isFree = false; return rp.positionRef.position; } } return rs.positions[0].positionRef.position; } } return Vector3.zero; }
public void Setup() { UserController userController = new UserController(); projectAdminUser = userController.FindUsersByUserName("nsw").FirstOrDefault(); project1 = new Project("World Domination", "Self Explainatory", @"WorldDomination", projectAdminUser); project2 = new Project("Bridge Construction", "Bridge over Klisterkanalen", @"BridgeConstruction", projectAdminUser); project3 = new Project("Recruiting", "Get more members", @"Recruiters", projectAdminUser); project4 = new Project("Server code", "Backend server code", @"Backend", projectAdminUser); project5 = new Project("Life and Universe", "What is 42?", @"42", projectAdminUser); projectController.AddProject(project1.Title,project1.Description,project1.ProjectFolder,project1.ProjectAdministrators.FirstOrDefault()); projectController.AddProject(project2.Title, project2.Description, project2.ProjectFolder, project2.ProjectAdministrators.FirstOrDefault()); projectController.AddProject(project3.Title, project3.Description, project3.ProjectFolder, project3.ProjectAdministrators.FirstOrDefault()); projectController.AddProject(project4.Title, project4.Description, project4.ProjectFolder, project4.ProjectAdministrators.FirstOrDefault()); projectController.AddProject(project4.Title, project5.Description, project5.ProjectFolder, project5.ProjectAdministrators.FirstOrDefault()); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Master != null) { Label pageTitle = Master.FindControl("lblpageheader") as Label; if (pageTitle != null) pageTitle.Text = "Patient Profile"; } if (!string.IsNullOrEmpty(Request.QueryString["Id"])) { int id = Convert.ToInt32(Request.QueryString["Id"]); User init = new UserController().GetUserById(id); LoadUser(init); } } }
public void CreateTenantTest() { UserController target = new UserController(); // TODO: Initialize to an appropriate value string name = string.Empty; // TODO: Initialize to an appropriate value string email = string.Empty; // TODO: Initialize to an appropriate value string organization = string.Empty; // TODO: Initialize to an appropriate value ActionResult expected = null; // TODO: Initialize to an appropriate value ActionResult actual; actual = target.CreateTenant(name, email, organization); name = "Manjunath SiddeGowda"; email = "*****@*****.**"; organization = "Aditi"; Assert.AreEqual(expected, actual); // Assert.Inconclusive("Verify the correctness of this test method."); }
public void Edit(int memberIndex, string gender, bool? marketing, string first, string last, string phone, string email, string dob) { // Arrange var member = db.Members.OrderBy(m => m.UserId).Skip(memberIndex - 1).FirstOrDefault(); var controller = new UserController { DbContext = db }; controller.ControllerContext = MockHelpers.GetControllerContext(db, member); db.SaveChanges(); var postedMember = new Member { User = new ApplicationUser { Id = member.User.Id, UserName = member.User.UserName, Email = email ?? member.User.Email, DateOfBirth = dob == null ? member.User.DateOfBirth : DateTime.ParseExact(dob, "dd/mm/yyyy", CultureInfo.InvariantCulture), PhoneNumber = phone ?? member.User.PhoneNumber, Gender = gender ?? member.User.Gender, LastName = last ?? member.User.LastName, FirstName = first ?? member.User.FirstName, }, Id = member.Id, IsEmailMarketingAllowed = marketing ?? member.IsEmailMarketingAllowed, }; // Detact both user and member from context before calling action db.Entry(member.User).State = EntityState.Detached; db.Entry(member).State = EntityState.Detached; // Act var result = controller.Edit(postedMember, null, null,null); var memberFromDb = db.Members.Find(member.Id); // Get the member back from the db context if (gender != null) Assert.AreEqual(gender, memberFromDb.User.Gender, "Gender didn't get set"); if (marketing != null) Assert.AreEqual(marketing, memberFromDb.IsEmailMarketingAllowed, "Marketing didn't get set"); if (first != null) Assert.AreEqual(first, memberFromDb.User.FirstName, "First name didn't get set"); if (last != null) Assert.AreEqual(last, memberFromDb.User.LastName, "Last name didn't get set"); if (phone != null) Assert.AreEqual(phone, memberFromDb.User.PhoneNumber, "Phone number didn't get set"); if (email != null) Assert.AreEqual(email, memberFromDb.User.Email, "Email didn't get set"); if (dob != null) Assert.AreEqual(DateTime.ParseExact(dob, "dd/mm/yyyy", CultureInfo.InvariantCulture), memberFromDb.User.DateOfBirth, "Date of birth didn't get set"); Console.WriteLine(controller.TempData["message"]); Assert.IsInstanceOf<RedirectToRouteResult>(result, "Controller must redirect after successful change"); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); ResourceManager.EnsureResources( typeof(UserController).Assembly, $"/data/data/{Application.Context.PackageName}/files"); SetContentView(Resource.Layout.Main); var webView = FindViewById<WebView>(Resource.Id.webView); var politicianController = new UserController( new HybridWebView(webView)); if (!RouteHandler.Controllers.ContainsKey("User")) RouteHandler.RegisterController("User", politicianController); politicianController.ShowLogin(); }
public static void ClassInit(TestContext context) { usersData = mockUsers(3); mockDatabase = new Mock<IZippyDatabase>(MockBehavior.Strict); mockDatabase.SetupGet(x => x.Users) .Returns(() => usersData.AsQueryable()); mockDatabase.Setup(x => x.Add(It.IsAny<User>())) .Callback<User>(x => { x.Id = new Random().Next(5, int.MaxValue); usersData.Add(x); }) .Returns((User x) => x); mockDatabase.Setup(x => x.Remove(It.IsAny<User>())) .Callback<User>(x => usersData.Remove(x)) .Returns((User x) => x); mockDatabase.Setup(x => x.Remove(It.IsAny<Medication>())) .Returns((Medication x) => x); mockDatabase.Setup(x => x.Remove(It.IsAny<Cabinet>())) .Returns((Cabinet x) => x); mockDatabase.Setup(x => x.Commit()) .Returns(0); controller = new UserController(mockDatabase.Object); }
private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings settings, Dictionary <string, string> testFields) { var httpAlias = testFields["Alias"]; var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); var tabName = testFields["Page Name"]; var scheme = testFields["Scheme"]; var parameters = testFields["Params"]; var result = testFields["Expected Url"]; var customPage = testFields.GetValue("Custom Page Name", _defaultPage); string vanityUrl = testFields.GetValue("VanityUrl", string.Empty); var httpAliasFull = scheme + httpAlias + "/"; var expectedResult = result.Replace("{alias}", httpAlias) .Replace("{usealias}", defaultAlias) .Replace("{tabName}", tabName) .Replace("{tabId}", tab.TabID.ToString()) .Replace("{vanityUrl}", vanityUrl) .Replace("{defaultPage}", _defaultPage); if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) { parameters = "&" + parameters; } var userName = testFields.GetValue("UserName", string.Empty); if (!string.IsNullOrEmpty(userName)) { var user = UserController.GetUserByName(this.PortalId, userName); if (user != null) { expectedResult = expectedResult.Replace("{userId}", user.UserID.ToString()); parameters = parameters.Replace("{userId}", user.UserID.ToString()); } } var baseUrl = httpAliasFull + "Default.aspx?TabId=" + tab.TabID + parameters; string testUrl; if (test == "Base") { testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl( tab, baseUrl, customPage, httpAlias, settings); } else { testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( tab, baseUrl, customPage, httpAlias, true, settings, Guid.Empty); } Assert.IsTrue(expectedResult.Equals(testUrl, StringComparison.InvariantCultureIgnoreCase)); }
private bool Validate() { CreateStatus = UserCreateStatus.AddUser; var portalSecurity = new PortalSecurity(); //Check User Editor bool _IsValid = userForm.IsValid; if (RegistrationFormType == 0) { //Update UserName if (UseEmailAsUserName) { User.Username = User.Email; if (String.IsNullOrEmpty(User.DisplayName)) { User.DisplayName = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)); } } //Check Password is valid if (!RandomPassword) { //Check Password is Valid if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(User.Membership.Password)) { CreateStatus = UserCreateStatus.InvalidPassword; } if (RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType)) { if (User.Membership.Password != User.Membership.PasswordConfirm) { CreateStatus = UserCreateStatus.PasswordMismatch; } } } else { //Generate a random password for the user User.Membership.Password = UserController.GeneratePassword(); User.Membership.PasswordConfirm = User.Membership.Password; } } else { //Set Username to Email if (String.IsNullOrEmpty(User.Username)) { User.Username = User.Email; } //Set DisplayName if (String.IsNullOrEmpty(User.DisplayName)) { User.DisplayName = String.IsNullOrEmpty(User.FirstName + " " + User.LastName) ? User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)) : User.FirstName + " " + User.LastName; } //Random Password if (String.IsNullOrEmpty(User.Membership.Password)) { //Generate a random password for the user User.Membership.Password = UserController.GeneratePassword(); } //Password Confirm if (!String.IsNullOrEmpty(User.Membership.PasswordConfirm)) { if (User.Membership.Password != User.Membership.PasswordConfirm) { CreateStatus = UserCreateStatus.PasswordMismatch; } } } ////Validate Exclude Terms //if (!String.IsNullOrEmpty(ExcludeTerms)) //{ // string[] excludeTerms = ExcludeTerms.Split(','); // foreach (string term in excludeTerms) // { // var trimmedTerm = term.Trim().ToLowerInvariant(); // if (User.Username.ToLowerInvariant().Contains(trimmedTerm)) // { // CreateStatus = UserCreateStatus.InvalidUserName; // } // if (User.DisplayName.ToLowerInvariant().Contains(trimmedTerm)) // { // CreateStatus = UserCreateStatus.InvalidDisplayName; // } // } //} //Validate Profanity if (UseProfanityFilter) { if (!portalSecurity.ValidateInput(User.Username, PortalSecurity.FilterFlag.NoProfanity)) { CreateStatus = UserCreateStatus.InvalidUserName; } if (!String.IsNullOrEmpty(User.DisplayName)) { if (!portalSecurity.ValidateInput(User.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) { CreateStatus = UserCreateStatus.InvalidDisplayName; } } } //Validate Unique User Name UserInfo user = UserController.GetUserByName(PortalId, User.Username); if (user != null) { if (UseEmailAsUserName) { CreateStatus = UserCreateStatus.DuplicateEmail; } else { CreateStatus = UserCreateStatus.DuplicateUserName; int i = 1; string userName = null; while (user != null) { userName = User.Username + "0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.GetUserByName(PortalId, userName); i++; } User.Username = userName; } } //Validate Unique Display Name if (CreateStatus == UserCreateStatus.AddUser && RequireUniqueDisplayName) { user = TestableUserController.Instance.GetUserByDisplayname(PortalId, User.DisplayName); if (user != null) { CreateStatus = UserCreateStatus.DuplicateDisplayName; int i = 1; string displayName = null; while (user != null) { displayName = User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); user = TestableUserController.Instance.GetUserByDisplayname(PortalId, displayName); i++; } User.DisplayName = displayName; } } //Check Question/Answer if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) { if (string.IsNullOrEmpty(User.Membership.PasswordQuestion)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidQuestion; } if (CreateStatus == UserCreateStatus.AddUser) { if (string.IsNullOrEmpty(User.Membership.PasswordAnswer)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidAnswer; } } } if (CreateStatus != UserCreateStatus.AddUser) { _IsValid = false; } return(_IsValid); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); imgAddModule.Click += imgAddModule_Click; optMode.SelectedIndexChanged += optMode_SelectedIndexChanged; optModuleType.SelectedIndexChanged += optModuleType_SelectedIndexChanged; cboTabs.SelectedIndexChanged += cboTabs_SelectedIndexChanged; cmdVisibility.Click += cmdVisibility_Click; cboPanes.SelectedIndexChanged += cboPanes_SelectedIndexChanged; cboPosition.SelectedIndexChanged += cboPosition_SelectedIndexChanged; imgAdmin.Click += imgAdmin_Click; cmdAdmin.Click += cmdAdmin_Click; imgHost.Click += imgHost_Click; cmdHost.Click += cmdHost_Click; cmdAddModule.Click += AddModule_Click; cmdAddTab.Click += PageFunctions_Click; cmdAddTabIcon.Click += PageFunctions_Click; cmdEditTab.Click += PageFunctions_Click; cmdEditTabIcon.Click += PageFunctions_Click; cmdDeleteTab.Click += PageFunctions_Click; cmdDeleteTabIcon.Click += PageFunctions_Click; cmdCopyTab.Click += PageFunctions_Click; cmdCopyTabIcon.Click += PageFunctions_Click; cmdExportTab.Click += PageFunctions_Click; cmdExportTabIcon.Click += PageFunctions_Click; cmdImportTab.Click += PageFunctions_Click; cmdImportTabIcon.Click += PageFunctions_Click; cmdExtensions.Click += CommonTasks_Click; cmdExtensionsIcon.Click += CommonTasks_Click; cmdFiles.Click += CommonTasks_Click; cmdFilesIcon.Click += CommonTasks_Click; cmdRoles.Click += CommonTasks_Click; cmdRolesIcon.Click += CommonTasks_Click; cmdSite.Click += CommonTasks_Click; cmdSiteIcon.Click += CommonTasks_Click; cmdUsers.Click += CommonTasks_Click; cmdUsersIcon.Click += CommonTasks_Click; try { if (IsPageAdmin()) { tblControlPanel.Visible = true; cmdVisibility.Visible = true; rowControlPanel.Visible = true; Localize(); if (Globals.IsAdminControl()) { cmdAddModule.Enabled = false; } if (!Page.IsPostBack) { optModuleType.Items.FindByValue("0").Selected = true; if (!TabPermissionController.CanAddPage()) { DisableAction(imgAddTabIcon, "iconbar_addtab_bw.gif", cmdAddTabIcon, cmdAddTab); } if (!TabPermissionController.CanManagePage()) { DisableAction(imgEditTabIcon, "iconbar_edittab_bw.gif", cmdEditTabIcon, cmdEditTab); } if (!TabPermissionController.CanDeletePage() || TabController.IsSpecialTab(TabController.CurrentPage.TabID, PortalSettings)) { DisableAction(imgDeleteTabIcon, "iconbar_deletetab_bw.gif", cmdDeleteTabIcon, cmdDeleteTab); } else { ClientAPI.AddButtonConfirm(cmdDeleteTab, Localization.GetString("DeleteTabConfirm", LocalResourceFile)); ClientAPI.AddButtonConfirm(cmdDeleteTabIcon, Localization.GetString("DeleteTabConfirm", LocalResourceFile)); } if (!TabPermissionController.CanCopyPage()) { DisableAction(imgCopyTabIcon, "iconbar_copytab_bw.gif", cmdCopyTabIcon, cmdCopyTab); } if (!TabPermissionController.CanExportPage()) { DisableAction(imgExportTabIcon, "iconbar_exporttab_bw.gif", cmdExportTabIcon, cmdExportTab); } if (!TabPermissionController.CanImportPage()) { DisableAction(imgImportTabIcon, "iconbar_importtab_bw.gif", cmdImportTabIcon, cmdImportTab); } if (!TabPermissionController.CanAddContentToPage()) { pnlModules.Visible = false; } if (!GetModulePermission(PortalSettings.PortalId, "Site Settings")) { DisableAction(imgSiteIcon, "iconbar_site_bw.gif", cmdSiteIcon, cmdSite); } if (GetModulePermission(PortalSettings.PortalId, "User Accounts") == false) { DisableAction(imgUsersIcon, "iconbar_users_bw.gif", cmdUsersIcon, cmdUsers); } if (GetModulePermission(PortalSettings.PortalId, "Security Roles") == false) { DisableAction(imgRolesIcon, "iconbar_roles_bw.gif", cmdRolesIcon, cmdRoles); } if (GetModulePermission(PortalSettings.PortalId, "File Manager") == false) { DisableAction(imgFilesIcon, "iconbar_files_bw.gif", cmdFilesIcon, cmdFiles); } if (GetModulePermission(PortalSettings.PortalId, "Extensions") == false) { DisableAction(imgExtensionsIcon, "iconbar_extensions_bw.gif", cmdExtensionsIcon, cmdExtensions); } UserInfo objUser = UserController.GetCurrentUserInfo(); if (objUser != null) { if (objUser.IsSuperUser) { hypMessage.ImageUrl = Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, Request.IsLocal, Request.IsSecureConnection); if (!String.IsNullOrEmpty(hypMessage.ImageUrl)) { hypMessage.ToolTip = Localization.GetString("hypUpgrade.Text", LocalResourceFile); hypMessage.NavigateUrl = Upgrade.UpgradeRedirect(); } cmdHost.Visible = true; } else //branding { if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) && Host.DisplayCopyright) { hypMessage.ImageUrl = "~/images/branding/iconbar_logo.png"; hypMessage.ToolTip = DotNetNukeContext.Current.Application.Description; hypMessage.NavigateUrl = Localization.GetString("hypMessageUrl.Text", LocalResourceFile); } else { hypMessage.Visible = false; } cmdHost.Visible = false; cmdAdmin.Visible = GetModulePermission(PortalSettings.PortalId, "Console"); } imgHost.Visible = cmdHost.Visible; imgAdmin.Visible = cmdAdmin.Visible; } BindData(); int intItem; for (intItem = 0; intItem <= PortalSettings.ActiveTab.Panes.Count - 1; intItem++) { cboPanes.Items.Add(Convert.ToString(PortalSettings.ActiveTab.Panes[intItem])); } if (cboPanes.Items.FindByValue(Globals.glbDefaultPane) != null) { cboPanes.Items.FindByValue(Globals.glbDefaultPane).Selected = true; } if (cboPermission.Items.Count > 0) { cboPermission.SelectedIndex = 0; //view } LoadPositions(); if (!string.IsNullOrEmpty(Host.HelpURL)) { var version = Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, false); cmdHelp.NavigateUrl = Globals.FormatHelpUrl(Host.HelpURL, PortalSettings, version); cmdHelpIcon.NavigateUrl = cmdHelp.NavigateUrl; cmdHelp.Enabled = true; cmdHelpIcon.Enabled = true; } else { cmdHelp.Enabled = false; cmdHelpIcon.Enabled = false; } SetMode(false); SetVisibility(false); } //Register jQuery jQuery.RequestRegistration(); } else if (IsModuleAdmin()) { tblControlPanel.Visible = true; cmdVisibility.Visible = false; rowControlPanel.Visible = false; if (!Page.IsPostBack) { SetMode(false); SetVisibility(false); } } else { tblControlPanel.Visible = false; } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
protected void Page_Load(object sender, EventArgs e) { try { spnStatus.Visible = true; lblMsg.Visible = false; string secret_key = "ed70df7a017654499542ff0a5515812824b74142"; string data = ""; string txnId = Request["TxId"]; string txnStatus = Request["TxStatus"]; string amount = Request["amount"]; string pgTxnId = Request["pgTxnNo"]; string issuerRefNo = Request["issuerRefNo"]; string authIdCode = Request["authIdCode"]; string firstName = Request["firstName"]; string lastName = Request["lastName"]; string pgRespCode = Request["pgRespCode"]; string zipCode = Request["addressZip"]; string resSignature = Request["signature"]; bool flag = true; if (txnId != null) { data += txnId; } if (txnStatus != null) { data += txnStatus; } if (amount != null) { data += amount; } if (pgTxnId != null) { data += pgTxnId; } if (issuerRefNo != null) { data += issuerRefNo; } if (authIdCode != null) { data += authIdCode; } if (firstName != null) { data += firstName; } if (lastName != null) { data += lastName; } if (pgRespCode != null) { data += pgRespCode; } if (zipCode != null) { data += zipCode; } System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key)); System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data)); string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower(); if (resSignature != null && !signature.Equals(resSignature)) { flag = false; } if (flag == true) { //Response.Write("Thank You for using citrus payment Your Unique Transaction Status:" + Convert.ToString(txnStatus)); if (Session["Bed"] != null || Session["Surgery"] != null || Session["AppointmentDetail"] != null || Session["HealthCheck-upComprehensive"] != null || Session["OutstandingBillPayment"] != null || Session["permenantRegistration"] != null || Session["ConsultationAppointment"] != null) { if (Session["Bed"] != null) { sessionData = (DataAccessEntities)Session["Bed"]; } else if (Session["Surgery"] != null) { sessionData = (DataAccessEntities)Session["Surgery"]; } else if (Session["AppointmentDetail"] != null) { sessionData = (DataAccessEntities)Session["AppointmentDetail"]; sessionData.FacilityName = "Appointment"; } else if (Session["HealthCheck-upComprehensive"] != null) { sessionData = (DataAccessEntities)Session["HealthCheck-upComprehensive"]; } else if (Session["OutstandingBillPayment"] != null) { sessionData = (DataAccessEntities)Session["OutstandingBillPayment"]; } else if (Session["permenantRegistration"] != null) { sessionData = (DataAccessEntities)Session["permenantRegistration"]; } else if (Session["ConsultationAppointment"] != null) { sessionData = (DataAccessEntities)Session["ConsultationAppointment"]; sessionData.FacilityName = "Appointment"; } //double Damount = Convert.ToDouble(amount); sessionData.Tranrefid = Convert.ToString(issuerRefNo); sessionData.Transtatus = Convert.ToString(txnStatus); sessionData.Amount = Convert.ToInt32(Session["Amount"]); sessionData.UserId = user.UserID; lblUserName.Text = user.DisplayName; lblMNo.Text = user.Username; //= Convert.ToString(user.UserID); lblTxtnId.Text = sessionData.Transactionid = Convert.ToString(txnId); lblPaidAgainst.Text = sessionData.FacilityName; lblDateTime.Text = Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")); lblAmount.Text = Convert.ToString(Session["Amount"]) + ".00 INR"; if (txnStatus != null) { if (Session["Bed"] != null) { if (txnStatus == "CANCELED") { Session["Bed"] = null; Response.Redirect("/Bed-Booking"); } //objBusinessLogic.SavePaymentBedSurgery(sessionData); ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, sessionData.Category, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "BedBookingPayment"); Session["Bed"] = null; } else if (Session["Surgery"] != null) { if (txnStatus == "CANCELED") { Session["Surgery"] = null; Response.Redirect("/surgery-booking"); } //objBusinessLogic.SavePaymentBedSurgery(sessionData); ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, sessionData.Category, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "SurgeryBookingPayment"); Session["Surgery"] = null; } else if (Session["HealthCheck-upComprehensive"] != null) { if (txnStatus == "CANCELED") { Session["HealthCheck-upComprehensive"] = null; Response.Redirect("/health-check-up-comprehensive"); } // objBusinessLogic.SavePaymentBedSurgery(sessionData); string _categoryName = sessionData.Category; if (_categoryName == "Male" || _categoryName == "Female") { _categoryName = "Package B (" + sessionData.Category + ")"; } ServiceBookingSendEmail(user.DisplayName, user.Email, sessionData.FacilityName, _categoryName, lblDateTime.Text, Convert.ToString(Session["Amount"]) + ".00 INR", "HealthCheckPayment"); Session["HealthCheck-upComprehensive"] = null; } else if (Session["OutstandingBillPayment"] != null) { if (txnStatus == "CANCELED") { Session["OutstandingBillPayment"] = null; Response.Redirect("/outstandingbillpayment"); } // objBusinessLogic.SavePaymentBedSurgery(sessionData); OutStandingSendEmail(sessionData.FacilityName, Convert.ToString(Session["Amount"]) + ".00 INR", "OutstandingPayment"); Session["OutstandingBillPayment"] = null; } else if (Session["permenantRegistration"] != null) { if (txnStatus == "CANCELED") { Session["permenantRegistration"] = null; Response.Redirect("/"); } Session["permenantRegistration"] = null; lblMsg.Visible = true; string Gender = user.Profile.GetPropertyValue("Gender"); if (Gender == "Male") { Gender = "M"; } else { Gender = "F"; } string Age = user.Profile.GetPropertyValue("Age"); string Address = user.Profile.GetPropertyValue("Address"); string PhoneNumber = user.Profile.GetPropertyValue("PhoneNumber"); string[] X = PhoneNumber.Split('-'); PhoneNumber = X[1]; string Username; string Fname; string Lname; string Email; if (user.Username.Length > 20) { Username = user.Username.Substring(0, 20); } else { Username = user.Username; } if (user.FirstName.Length > 30) { Fname = user.FirstName.Substring(0, 30); } else { Fname = user.FirstName; } if (user.LastName.Length > 30) { Lname = user.LastName.Substring(0, 30); } else { Lname = user.LastName; } if (user.Email.Length > 50) { Email = user.Email.Substring(0, 50); } else { Email = user.Email; } if (Address.Length > 30) { Address = Address.Substring(0, 30); } if (PhoneNumber.Length > 12) { PhoneNumber = PhoneNumber.Substring(0, 12); } // objBusinessLogic.SavePaymentBedSurgery(sessionData); var PatientDetails = NapierService(user.Username, user.FirstName, user.LastName, Gender, Age, "01/01/2000", Address, Address, Address, PhoneNumber, Email); //var PatientDetails = objPatIndex.UpdateorInsertPatient(user.Username, user.FirstName, user.LastName, Gender, Age, "01/01/2000", Address, Address, Address, PhoneNumber, Email); if (!string.IsNullOrEmpty(PatientDetails.MRNO)) { if (!string.IsNullOrEmpty(PatientDetails.WEBPWD)) { bool _isMrNumberExists = objBusinessLogic.IsExistMRNumber(PatientDetails.MRNO); if (_isMrNumberExists) { Clear(); lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); lblMsg.Text = "You are already registered as a permanent User!"; } else { bool IsUserExist = objBusinessLogic.IsUserExist(PatientDetails.MRNO); if (!IsUserExist) { if (PatientDetails.PatSex == "M") { PatientDetails.PatSex = "Male"; } else { PatientDetails.PatSex = "Female"; } DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge); lblMNo.Text = PatientDetails.MRNO; if (dsVal.Tables[0].Rows.Count > 0) { // SendMail & MSG try { PermanentUserSendEmail(PatientDetails.PatFName, PatientDetails.PatEmail, PatientDetails.MRNO, PatientDetails.WEBPWD, PhoneNumber, "PermanentRegistration"); } catch (Exception ex) { lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); lblMsg.Text = "SMS Service is stoped Due to technical problem!"; Exceptions.LogException(ex); } lblMsg.Text = "You are now the permanent user! Please login with your MR Number that has been sent to your registered mobile number"; lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000"); UserController.DeleteUser(ref user, false, false); UserController.RemoveUser(user); if (user.UserID != -1) { secure.SignOut(); } } } else { Clear(); lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); lblMsg.Text = "UserName already exist!"; } } } else { Clear(); lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); lblMsg.Text = "You are already register as a permanent user, Please login with MR Number"; } } else { Clear(); lblMsg.Visible = true; lblMsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000"); lblMsg.Text = "Due to some technical problem MRNumber is not generated please contact Jaslok Hospital!"; plcDivSucces.Visible = true; plcDivError.Visible = false; } } else if (Session["ConsultationAppointment"] != null || Session["AppointmentDetail"] != null) { if (txnStatus == "CANCELED") { Session["ConsultationAppointment"] = null; Session["AppointmentDetail"] = null; Response.Redirect("/"); } sessionData.FacilityName = "Consultation Appointment"; objBusinessLogic.SavePaymentBookAppointment(sessionData); AppointmentSendEmail(Convert.ToString(sessionData.PhoneNo), Convert.ToString(sessionData.MobileNo), Convert.ToString(sessionData.Location), Convert.ToString(sessionData.Address), Convert.ToString(sessionData.Email), Convert.ToString(sessionData.TimeDate), Convert.ToString(Session["Amount"]) + ".00 INR", Convert.ToString(sessionData.AppointmentType), Convert.ToString(sessionData.Description), sessionData.dName, "ConsultationAppointment"); Session["ConsultationAppointment"] = null; Session["AppointmentDetail"] = null; } // Save Deposit var details = (dynamic)null; try { details = NapierService(lblTxtnId.Text, lblMNo.Text, Convert.ToDouble(Session["Amount"]), Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy")), sessionData.FacilityName); } catch (Exception ex) { Exceptions.LogException(ex); sessionData.JeevaStatus = "Service Unavailable"; } if (details != null && !string.IsNullOrEmpty(details.MRNO)) { sessionData.JeevaStatus = details.MRNO; } //End of Save Deposit // insert payment details if (sessionData.FacilityName != "Consultation Appointment") { InsertPaymentDetails(); } // end of insert payment details } else { plcDivSucces.Visible = false; plcDivError.Visible = true; spnStatus.Attributes["Class"] = "highlight"; spnStatus.InnerText = "Payment Fail !"; } Session["Amount"] = null; } else { plcDivSucces.Visible = false; plcDivError.Visible = true; spnStatus.Attributes["Class"] = "highlight"; spnStatus.InnerText = "Payment Fail !"; } } else { Response.Write("Citrus Response Signature and Our (Merchant)Signature Mis - Match"); } } catch (Exception ex) { Exceptions.LogException(ex); } }
private void CreateSite(PortalConfig portal, InstallConfig installConfig) { var domain = ""; if ((HttpContext.Current != null)) { domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", "").Replace("/install", "").Replace("/runinstall", ""); } var serverPath = Globals.ApplicationMapPath + "\\"; //Get the Portal Alias var portalAlias = domain; if (portal.PortAliases.Count > 0) { portalAlias = portal.PortAliases[0]; } //Verify that portal alias is not present if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) { string description = Localization.Localization.GetString("SkipCreatingSite", LocalInstallResourceFile); Details = string.Format(description, portalAlias); return; } //Create default email var email = portal.AdminEmail; if (string.IsNullOrEmpty(email)) { email = "admin@" + domain.Replace("www.", ""); //Remove any domain subfolder information ( if it exists ) if (email.IndexOf("/") != -1) { email = email.Substring(0, email.IndexOf("/")); } } //install LP if installing in a different language string culture = installConfig.InstallCulture; if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); string lpFilePath = installFolder + "\\installlanguage.resources"; if (File.Exists(lpFilePath)) { if (!Upgrade.InstallPackage(lpFilePath, "Language", false)) { culture = Localization.Localization.SystemLocale; } } else { culture = Localization.Localization.SystemLocale; } } var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); UserInfo userInfo; if (!String.IsNullOrEmpty(portal.AdminUserName)) { userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); } else { userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); } var childPath = string.Empty; if (portal.IsChild) { childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); } //Create Folder Mappings config if (!String.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } //add item to identity install from install wizard. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("InstallFromWizard", true); } //Create Portal var portalId = PortalController.Instance.CreatePortal(portal.PortalName, userInfo, portal.Description, portal.Keywords, template, portal.HomeDirectory, portalAlias, serverPath, serverPath + childPath, portal.IsChild); if (portalId > -1) { foreach (var alias in portal.PortAliases) { PortalController.Instance.AddPortalAlias(portalId, alias); } } //remove en-US from portal if installing in a different language if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { var locale = LocaleController.Instance.GetLocale("en-US"); Localization.Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); } //Log user in to site var loginStatus = UserLoginStatus.LOGIN_FAILURE; UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, "", "", "", ref loginStatus, false); InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); }
public virtual void SendMessage(Message message, IList <RoleInfo> roles, IList <UserInfo> users, IList <int> fileIDs, UserInfo sender) { if (sender == null || sender.UserID <= 0) { throw new ArgumentException(Localization.Localization.GetString("MsgSenderRequiredError", Localization.Localization.ExceptionsResourceFile)); } if (message == null) { throw new ArgumentException(Localization.Localization.GetString("MsgMessageRequiredError", Localization.Localization.ExceptionsResourceFile)); } if (string.IsNullOrEmpty(message.Subject) && string.IsNullOrEmpty(message.Body)) { throw new ArgumentException(Localization.Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.Localization.ExceptionsResourceFile)); } if (roles == null && users == null) { throw new ArgumentException(Localization.Localization.GetString("MsgRolesOrUsersRequiredError", Localization.Localization.ExceptionsResourceFile)); } if (!string.IsNullOrEmpty(message.Subject) && message.Subject.Length > ConstMaxSubject) { throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgSubjectTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxSubject, message.Subject.Length)); } if (roles != null && roles.Count > 0 && !IsAdminOrHost(sender)) { if (!roles.All(role => sender.Social.Roles.Any(userRoleInfo => role.RoleID == userRoleInfo.RoleID))) { throw new ArgumentException(Localization.Localization.GetString("MsgOnlyHostOrAdminOrUserInGroupCanSendToRoleError", Localization.Localization.ExceptionsResourceFile)); } } var sbTo = new StringBuilder(); var replyAllAllowed = true; if (roles != null) { foreach (var role in roles.Where(role => !string.IsNullOrEmpty(role.RoleName))) { sbTo.Append(role.RoleName + ","); replyAllAllowed = false; } } if (users != null) { foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) { sbTo.Append(user.DisplayName + ","); } } if (sbTo.Length == 0) { throw new ArgumentException(Localization.Localization.GetString("MsgEmptyToListFoundError", Localization.Localization.ExceptionsResourceFile)); } if (sbTo.Length > ConstMaxTo) { throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgToListTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); } //Cannot send message if within ThrottlingInterval var waitTime = InternalMessagingController.Instance.WaitTimeForNextMessage(sender); if (waitTime > 0) { var interval = GetPortalSettingAsInteger("MessagingThrottlingInterval", sender.PortalID, Null.NullInteger); throw new ThrottlingIntervalNotMetException(string.Format(Localization.Localization.GetString("MsgThrottlingIntervalNotMet", Localization.Localization.ExceptionsResourceFile), interval)); } //Cannot have attachments if it's not enabled if (fileIDs != null && !InternalMessagingController.Instance.AttachmentsAllowed(sender.PortalID)) { throw new AttachmentsNotAllowed(Localization.Localization.GetString("MsgAttachmentsNotAllowed", Localization.Localization.ExceptionsResourceFile)); } //Cannot exceed RecipientLimit var recipientCount = 0; if (users != null) { recipientCount += users.Count; } if (roles != null) { recipientCount += roles.Count; } if (recipientCount > InternalMessagingController.Instance.RecipientLimit(sender.PortalID)) { throw new RecipientLimitExceededException(Localization.Localization.GetString("MsgRecipientLimitExceeded", Localization.Localization.ExceptionsResourceFile)); } //Profanity Filter var profanityFilterSetting = GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); if (profanityFilterSetting.Equals("YES", StringComparison.InvariantCultureIgnoreCase)) { message.Subject = InputFilter(message.Subject); message.Body = InputFilter(message.Body); } message.To = sbTo.ToString().Trim(','); message.MessageID = Null.NullInteger; message.ReplyAllAllowed = replyAllAllowed; message.SenderUserID = sender.UserID; message.From = sender.DisplayName; message.MessageID = _dataService.SaveMessage(message, PortalController.GetEffectivePortalId(UserController.GetCurrentUserInfo().PortalID), UserController.GetCurrentUserInfo().UserID); //associate attachments if (fileIDs != null) { foreach (var attachment in fileIDs.Select(fileId => new MessageAttachment { MessageAttachmentID = Null.NullInteger, FileID = fileId, MessageID = message.MessageID })) { _dataService.SaveMessageAttachment(attachment, UserController.GetCurrentUserInfo().UserID); } } //send message to Roles if (roles != null) { var roleIds = string.Empty; roleIds = roles .Select(r => r.RoleID) .Aggregate(roleIds, (current, roleId) => current + (roleId + ",")) .Trim(','); _dataService.CreateMessageRecipientsForRole(message.MessageID, roleIds, UserController.GetCurrentUserInfo().UserID); } //send message to each User - this should be called after CreateMessageRecipientsForRole. if (users == null) { users = new List <UserInfo>(); } foreach (var recipient in from user in users where InternalMessagingController.Instance.GetMessageRecipient(message.MessageID, user.UserID) == null select new MessageRecipient { MessageID = message.MessageID, UserID = user.UserID, Read = false, RecipientID = Null.NullInteger }) { _dataService.SaveMessageRecipient(recipient, UserController.GetCurrentUserInfo().UserID); } if (users.All(u => u.UserID != sender.UserID)) { //add sender as a recipient of the message var recipientId = _dataService.SaveMessageRecipient(new MessageRecipient { MessageID = message.MessageID, UserID = sender.UserID, Read = false, RecipientID = Null.NullInteger }, UserController.GetCurrentUserInfo().UserID); InternalMessagingController.Instance.MarkMessageAsDispatched(message.MessageID, recipientId); } // Mark the conversation as read by the sender of the message. InternalMessagingController.Instance.MarkRead(message.MessageID, sender.UserID); }
internal virtual UserInfo GetCurrentUserInfo() { return(UserController.GetCurrentUserInfo()); }
public static void DeleteAuthentication(AuthenticationInfo authSystem) { provider.DeleteAuthentication(authSystem.AuthenticationID); var objEventLog = new EventLogController(); objEventLog.AddLog(authSystem, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.AUTHENTICATION_DELETED); }
/// ----------------------------------------------------------------------------- /// <summary> /// AddUserAuthentication adds a new UserAuthentication to the User. /// </summary> /// <param name="userID">The new Authentication System to add</param> /// <param name="authenticationType">The authentication type</param> /// <param name="authenticationToken">The authentication token</param> /// <history> /// [cnurse] 07/12/2007 Created /// [skydnn] 11/14/2013 DNN-4016 /// </history> /// ----------------------------------------------------------------------------- public static int AddUserAuthentication(int userID, string authenticationType, string authenticationToken) { var objEventLog = new EventLogController(); UserAuthenticationInfo userAuth = GetUserAuthentication(userID); if (userAuth == null || String.IsNullOrEmpty(userAuth.AuthenticationType)) { objEventLog.AddLog("userID/authenticationType", userID + "/" + authenticationType, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.AUTHENTICATION_USER_CREATED); return(provider.AddUserAuthentication(userID, authenticationType, authenticationToken, UserController.GetCurrentUserInfo().UserID)); } else { objEventLog.AddLog("userID/authenticationType already exists", userID + "/" + authenticationType, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.AUTHENTICATION_USER_UPDATED); return(userAuth.UserAuthenticationID); } }
protected void LogUser(object sender, EventArgs e) { if (userTextBox.TextName != string.Empty) { if (passwrdTextBox.TextName != string.Empty) { var userController = new UserController(); var user = new User(); user.email = userTextBox.TextName; user.password = passwrdTextBox.TextName; loadingForm = new LoadingForm(); loadingForm.Show(); var token = userController.LoginAsync(user).Result; if (token != null) { Constants.token = token.access_token; Constants.user = new User(); Constants.user = token.user; // Obtengo los tours var tourController = new TourController(); Constants.tours = tourController.GetAllToursAsync().Result; loadingForm.Close(); new PopupNotification("App Asistime!", "Bienvenido " + token.user.name); if (token.user.rol == "Adulto") { ////Active notifications of new tours Thread threadNewTour = new Thread(NewTourThread.DoWork); threadNewTour.IsBackground = true; threadNewTour.Start(); NavigatorAdult mod = new NavigatorAdult(); mod.Show(); this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; } else if (token.user.rol == "Responsable") { ////Active notifications Thread threadNotification = new Thread(NotificationThread.DoWork); threadNotification.IsBackground = true; threadNotification.Start(); NavigatorAssistant mod = new NavigatorAssistant(); mod.Show(); this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; } } else { loadingForm.Close(); new PopupNotification("Error Login", "Usuario o contraseña incorrecta."); userTextBox.TextName = ""; passwrdTextBox.TextName = ""; } } } else { new PopupNotification("Error Login", "Todos los campos deben tenes un valor."); } }
/// ----------------------------------------------------------------------------- /// <summary> /// AddAuthentication adds a new Authentication System to the Data Store. /// </summary> /// <param name="authSystem">The new Authentication System to add</param> /// <history> /// [cnurse] 07/10/2007 Created /// </history> /// ----------------------------------------------------------------------------- public static int AddAuthentication(AuthenticationInfo authSystem) { var objEventLog = new EventLogController(); objEventLog.AddLog(authSystem, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.AUTHENTICATION_CREATED); return(provider.AddAuthentication(authSystem.PackageID, authSystem.AuthenticationType, authSystem.IsEnabled, authSystem.SettingsControlSrc, authSystem.LoginControlSrc, authSystem.LogoffControlSrc, UserController.GetCurrentUserInfo().UserID)); }
public SecurityService() { UserController = new UserController(); }
public void DeleteAllForPortal() { UserController.DeleteUsers(PortalId, false, false); UserController.RemoveDeletedUsers(PortalId); }
public int CountOfAll() { var users = UserController.GetUsers(PortalId); return(users == null ? 0 : users.Count); }
public void EditQuestionSet(EditQuestionSetRequest request) { AuthToken authToken = null; try { Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.AntiForgeryToken, "Anti Forgery Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.Name, "Name"); Common.Helpers.ValidationHelper.ValidateStringLength(request.Name, "Name", Constants.MaxNameLength); Common.Helpers.ValidationHelper.Assert(request.QuestionIDs.Any(), "No questions selected."); if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken); DbContext context = DataController.CreateDbContext(); if (string.IsNullOrEmpty(request.Name)) { throw new Common.Exceptions.ValidationException("Please fill in the name field."); } E::QuestionSet questionSet = context.QuestionSets.FirstOrDefault(q => q.ID == request.QuestionSetID); E::QuestionSetQuestion[] questionSetQuestions = context.QuestionSetQuestions.Where(iq => iq.QuestionSetID == request.QuestionSetID).ToArray(); foreach (E::QuestionSetQuestion questionSetQuestion in questionSetQuestions) { if (!request.QuestionIDs.Contains(questionSetQuestion.QuestionID)) { context.QuestionSetQuestions.Remove(questionSetQuestion); } } foreach (Guid questionId in request.QuestionIDs.Except(questionSetQuestions.Select(iq => iq.QuestionID))) { E::QuestionSetQuestion newQuestionSetQuestion = new E.QuestionSetQuestion(); newQuestionSetQuestion.QuestionSetID = request.QuestionSetID; newQuestionSetQuestion.QuestionID = questionId; context.QuestionSetQuestions.Add(newQuestionSetQuestion); } questionSet.Name = request.Name; questionSet.LastUpdatedBy = authToken.Username; questionSet.LastUpdatedDate = DateTime.UtcNow; context.SaveChanges(); } catch (AuthenticationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } }
/************************************************** * Event Handlers **************************************************/ private void Awake() { _userController = UserController.Instance; }
public CreateQuestionSetResponse CreateQuestionSet(CreateQuestionSetRequest request) { CreateQuestionSetResponse response = new CreateQuestionSetResponse(); AuthToken authToken = null; try { Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.AntiForgeryToken, "Anti Forgery Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.Name, "Name"); Common.Helpers.ValidationHelper.ValidateStringLength(request.Name, "Name", Constants.MaxNameLength); Common.Helpers.ValidationHelper.Assert(request.QuestionIDs.Any(), "No questions selected."); if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken); DbContext context = DataController.CreateDbContext(); E::QuestionSet newQuestionSet = new E::QuestionSet(); newQuestionSet.ID = Guid.NewGuid(); newQuestionSet.Name = request.Name; newQuestionSet.CreatedBy = authToken.Username; newQuestionSet.CreatedDate = DateTime.UtcNow; newQuestionSet.LastUpdatedBy = authToken.Username; newQuestionSet.LastUpdatedDate = DateTime.UtcNow; context.QuestionSets.Add(newQuestionSet); foreach (Guid questionId in request.QuestionIDs) { E::QuestionSetQuestion newQuestionSetQuestion = new E.QuestionSetQuestion(); newQuestionSetQuestion.QuestionSetID = newQuestionSet.ID; newQuestionSetQuestion.QuestionID = questionId; context.QuestionSetQuestions.Add(newQuestionSetQuestion); } context.SaveChanges(); response.QuestionSetID = newQuestionSet.ID; } catch (AuthenticationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } return(response); }
public Response<User> getUsersWithParameter(string group_id, string emailFilter, string limit, string page, string order_by, string order) { IncomingWebRequestContext requestContext = WebOperationContext.Current.IncomingRequest; Dictionary<string, string> data = new Dictionary<string, string>(); string authString = requestContext.Headers[HttpRequestHeader.Authorization]; data.Add("user_group_id", group_id); data.Add("email", emailFilter); data.Add("limit", limit); data.Add("page", page); data.Add("order by", order_by); data.Add("order", order); Request request = makeRequest(requestContext, trimData(data), authString); UserController controller = new UserController(); return controller.Call(request); }
public virtual void SendMessage(Message message, IList <RoleInfo> roles, IList <UserInfo> users, IList <int> fileIDs) { SendMessage(message, roles, users, fileIDs, UserController.GetCurrentUserInfo()); }
private void cmdUpdate_Click(Object sender, EventArgs e) { if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha) { if (IsUserOrAdmin == false) { return; } //1. Check New Password and Confirm are the same if (txtNewPassword.Text != txtNewConfirm.Text) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMismatch)); return; } //2. Check New Password is Valid if (!UserController.ValidatePassword(txtNewPassword.Text)) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordInvalid)); return; } //3. Check old Password is Provided if (!IsAdmin && String.IsNullOrEmpty(txtOldPassword.Text)) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordMissing)); return; } //4. Check New Password is ddifferent if (!IsAdmin && txtNewPassword.Text == txtOldPassword.Text) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); return; } //5. Check New Password is not same as username or banned var settings = new MembershipPasswordSettings(User.PortalID); if (settings.EnableBannedList) { var m = new MembershipPasswordController(); if (m.FoundBannedPassword(txtNewPassword.Text) || User.Username == txtNewPassword.Text) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.BannedPasswordUsed)); return; } } if (!IsAdmin && txtNewPassword.Text == txtOldPassword.Text) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordNotDifferent)); return; } if (!IsAdmin) { try { OnPasswordUpdated(UserController.ChangePassword(User, txtOldPassword.Text, txtNewPassword.Text) ? new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success) : new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } catch (MembershipPasswordException exc) { //Password Answer missing Logger.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (ThreadAbortException) { //Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception exc) { //Fail Logger.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } else { try { OnPasswordUpdated(UserController.ResetAndChangePassword(User, txtNewPassword.Text) ? new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success) : new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } catch (MembershipPasswordException exc) { //Password Answer missing Logger.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (ThreadAbortException) { //Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception exc) { //Fail Logger.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } } } }
/// ----------------------------------------------------------------------------- /// <summary> /// This handler handles requests for LinkClick.aspx, but only those specifc /// to file serving /// </summary> /// <param name = "context">System.Web.HttpContext)</param> /// <remarks> /// </remarks> /// <history> /// [cpaterra] 4/19/2006 Created /// </history> /// ----------------------------------------------------------------------------- public void ProcessRequest(HttpContext context) { PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); int UserId = Null.NullInteger; int PortalId = _portalSettings.PortalId; try { //try UserId if (!string.IsNullOrEmpty(context.Request.QueryString["UserId"])) { UserId = Int32.Parse(context.Request.QueryString["UserId"]); if (UserController.GetUserById(PortalId, UserId) == null) { //The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } } if (UserId == Null.NullInteger) { //try userName if (!string.IsNullOrEmpty(context.Request.QueryString["UserName"])) { UserId = GetUserId(context.Request.QueryString["UserName"], PortalId); } } if (UserId == Null.NullInteger) { //try user string user = context.Request.QueryString["User"]; if (!string.IsNullOrEmpty(user)) { if (!Int32.TryParse(user, out UserId)) { //User is not an integer, so try it as a name UserId = GetUserId(user, PortalId); } else { if (UserController.GetUserById(PortalId, UserId) == null) { //The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } } } } if (UserId == Null.NullInteger) { //The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } } catch (Exception exc) { Logger.Debug(exc); //The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } //Redirect to Userprofile Page context.Response.Redirect(Globals.UserProfileURL(UserId), true); }
internal static bool CheckUserProfileReplacement(string newPath, TabInfo tab, PortalSettings portalSettings, FriendlyUrlSettings settings, FriendlyUrlOptions options, out string changedPath, out bool changeToSiteRoot, out bool allowOtherParameters, ref List <string> meessages, Guid parentTraceId) { if (meessages == null) { meessages = new List <string>(); } bool urlWasChanged = false; //initialise defaults to always return valid items changedPath = newPath; changeToSiteRoot = false; allowOtherParameters = true; //determine if this url should be converted to a userprofile url by checking the saved rules matching the tab/portalid if (portalSettings != null && tab.PortalID == portalSettings.PortalId && (tab.TabID == portalSettings.UserTabId || portalSettings.UserTabId == -1 || tab.ParentId == portalSettings.UserTabId)) //-1 == all tabs in portal { int userId; string rawUserId, remainingPath; //split the userid and other profile parameters from the friendly url path, //and return the userid and remaining parts as separate items SplitUserIdFromFriendlyUrlPath(newPath, "UserId", "", out rawUserId, out remainingPath); if (rawUserId != null) { meessages.Add("User Profile Url : RawUserId = " + rawUserId + " remainingPath = " + remainingPath); } else { meessages.Add("User Profile Url : RawUserId = " + "null" + " remainingPath = " + remainingPath); } //the rawuserid is just the string representation of the userid from the path. //It should be considered 'untrusted' until cleaned up, //converted to an int and checked against the database if (!String.IsNullOrEmpty(rawUserId) && Int32.TryParse(rawUserId, out userId)) { bool doReplacement = false; string urlName = String.Empty; //Get the User var user = UserController.GetUserById(portalSettings.PortalId, userId); if (user != null && !String.IsNullOrEmpty(user.VanityUrl)) { doReplacement = true; urlName = (!String.IsNullOrEmpty(settings.VanityUrlPrefix)) ? String.Format("{0}/{1}", settings.VanityUrlPrefix, user.VanityUrl) : user.VanityUrl; urlWasChanged = true; } if (doReplacement) { //check to see whether this is a match on the parentid or not if (portalSettings.UserTabId == tab.ParentId && portalSettings.UserTabId > -1) { //replacing for the parent tab id string childTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId); if (string.IsNullOrEmpty(childTabPath) == false) { //remove the parent tab path from the child tab path TabInfo profilePage = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); string profilePagePath = TabIndexController.GetTabPath(profilePage, options, parentTraceId); if (childTabPath.Contains(profilePagePath)) { //only replace when the child tab path contains the parent path - if it's a custom url that //doesn't incorporate the parent path, then leave it alone childTabPath = childTabPath.Replace(profilePagePath, ""); childTabPath = childTabPath.Replace("//", "/"); urlName += FriendlyUrlController.EnsureLeadingChar("/", childTabPath); } } } changedPath = "/" + urlName; //append any extra remaining path value to the end if (!string.IsNullOrEmpty(remainingPath)) { if (remainingPath.StartsWith("/") == false) { changedPath += "/" + remainingPath; } else { changedPath += remainingPath; } } urlWasChanged = true; changeToSiteRoot = true; //we will be doing domain.com/urlname allowOtherParameters = false; //can't have any others (wouldn't have matched in the regex if there were) } else { meessages.Add("User Profile : doReplacement = false"); } } } return(urlWasChanged); }
public Response<User> getUsersInGroup(string groupId) { IncomingWebRequestContext requestContext = WebOperationContext.Current.IncomingRequest; Dictionary<string, string> data = new Dictionary<string, string>(); string authString = requestContext.Headers[HttpRequestHeader.Authorization]; data.Add("user_group_id", groupId); Request request = makeRequest(requestContext, trimData(data), authString); UserController controller = new UserController(); return controller.Call(request); }
public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (this.CheckCancelled(importJob)) { return; } var pageIndex = 0; const int pageSize = Constants.DefaultPageSize; var totalUserRolesImported = 0; var totalProfilesImported = 0; var totalProcessed = 0; var totalUsers = this.Repository.GetCount <ExportUser>(); if (totalUsers == 0) { this.CheckPoint.Completed = true; this.CheckPointStageCallback(this); return; } var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); // Skip the import if all the users has been processed already. if (this.CheckPoint.Stage >= totalPages) { return; } pageIndex = this.CheckPoint.Stage; var totalUsersToBeProcessed = totalUsers - (pageIndex * pageSize); // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; if (this.CheckPointStageCallback(this)) { return; } var includeProfile = importDto.ExportDto.IncludeProperfileProperties; try { this.Repository.RebuildIndex <ExportUserRole>(x => x.ReferenceId); if (includeProfile) { this.Repository.RebuildIndex <ExportUserProfile>(x => x.ReferenceId); } var portalId = importJob.PortalId; using (var tableUserProfile = new DataTable("UserProfile")) using (var tableUserRoles = new DataTable("UserRoles")) { // must create the columns from scratch with each iteration tableUserProfile.Columns.AddRange(UserProfileDatasetColumns.Select(column => new DataColumn(column.Item1, column.Item2)).ToArray()); tableUserRoles.Columns.AddRange(UserRolesDatasetColumns.Select(column => new DataColumn(column.Item1, column.Item2)).ToArray()); var dataProvider = DotNetNuke.Data.DataProvider.Instance(); while (totalProcessed < totalUsersToBeProcessed) { if (this.CheckCancelled(importJob)) { return; } var users = this.Repository.GetAllItems <ExportUser>(null, true, pageIndex * pageSize, pageSize).ToList(); var tempUserRolesCount = 0; var tempUserProfileCount = 0; try { foreach (var user in users) { if (this.CheckCancelled(importJob)) { return; } // Find the correct userId from the system which was added/updated by UserExportService. var userId = UserController.GetUserByName(user.Username)?.UserID; if (userId != null) { var userRoles = this.Repository.GetRelatedItems <ExportUserRole>(user.Id).ToList(); foreach (var userRole in userRoles) { var roleId = Util.GetRoleIdByName(importJob.PortalId, userRole.RoleId, userRole.RoleName); if (roleId == null) { continue; } if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) { continue; } var userRoleRow = tableUserRoles.NewRow(); userRoleRow["PortalId"] = portalId; userRoleRow["UserId"] = userId; userRoleRow["RoleId"] = roleId; userRoleRow["ExpiryDate"] = dataProvider.GetNull(userRole.ExpiryDate); userRoleRow["IsTrialUsed"] = userRole.IsTrialUsed; userRoleRow["EffectiveDate"] = dataProvider.GetNull(userRole.EffectiveDate); userRoleRow["CreatedByUserId"] = Util.GetUserIdByName(importJob, user.CreatedByUserId, user.CreatedByUserName); userRoleRow["LastModifiedByUserId"] = Util.GetUserIdByName(importJob, user.LastModifiedByUserId, user.LastModifiedByUserName); userRoleRow["Status"] = userRole.Status; userRoleRow["IsOwner"] = userRole.IsOwner; userRoleRow["IsSuperUser"] = user.IsSuperUser; tableUserRoles.Rows.Add(userRoleRow); tempUserRolesCount++; } if (includeProfile) { var userProfiles = this.Repository.GetRelatedItems <ExportUserProfile>(user.Id).ToList(); foreach (var userProfile in userProfiles) { var profileDefinitionId = Util.GetProfilePropertyId( importJob.PortalId, userProfile.PropertyDefinitionId, userProfile.PropertyName); if (profileDefinitionId == null || profileDefinitionId == -1) { continue; } var value = userProfile.PropertyValue; if (userProfile.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) && (value = this.GetUserPhotoId(portalId, value, user)) == null) { continue; } var userProfileRow = tableUserProfile.NewRow(); userProfileRow["PortalId"] = importJob.PortalId; userProfileRow["UserId"] = userId; userProfileRow["PropertyDefinitionId"] = profileDefinitionId.Value; userProfileRow["PropertyValue"] = value; userProfileRow["PropertyText"] = userProfile.PropertyText; userProfileRow["Visibility"] = userProfile.Visibility; userProfileRow["ExtendedVisibility"] = userProfile.ExtendedVisibility; userProfileRow["IsSuperUser"] = user.IsSuperUser; tableUserProfile.Rows.Add(userProfileRow); tempUserProfileCount++; } } } } var overwrite = importDto.CollisionResolution == CollisionResolution.Overwrite; // Bulk insert the data in DB DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUserRolesBulk", "@DataTable", tableUserRoles, new Dictionary <string, object> { { "Overwrite", overwrite } }); totalUserRolesImported += tempUserRolesCount; if (includeProfile) { DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUsersProfilesBulk", "@DataTable", tableUserProfile, new Dictionary <string, object> { { "Overwrite", overwrite } }); totalProfilesImported += tempUserProfileCount; } this.CheckPoint.ProcessedItems += users.Count; totalProcessed += users.Count; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; this.CheckPoint.StageData = null; } catch (Exception ex) { this.Result.AddLogEntry($"Importing Users Data from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } tableUserRoles.Rows.Clear(); tableUserProfile.Rows.Clear(); pageIndex++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; this.CheckPoint.Stage++; this.CheckPoint.StageData = null; if (this.CheckPointStageCallback(this)) { return; } } } this.CheckPoint.Completed = true; this.CheckPoint.Progress = 100; } finally { this.CheckPointStageCallback(this); this.Result.AddSummary("Imported User Roles", totalUserRolesImported.ToString()); if (includeProfile) { this.Result.AddSummary("Imported User Profiles", totalProfilesImported.ToString()); } } }
public Response<User> insertUser(User user) { IncomingWebRequestContext requestContext = WebOperationContext.Current.IncomingRequest; Dictionary<string, string> data = new Dictionary<string, string>(); string authString = requestContext.Headers[HttpRequestHeader.Authorization]; data.Add("email", user.email); data.Add("password", user.password); Request request = makeRequest(requestContext, data, authString); UserController controller = new UserController(); return controller.Call(request); }
public UpdateUserShould() { _svc = new Mock <IUserService>(); _controller = UserControllerFactory.Create(_svc.Object); }
// NOTE - While making modifications in this method, developer must refer to call tree in Register.ascx.cs. // Especially Validate and CreateUser methods. Register class inherits from UserModuleBase, which also contains bunch of logic. // This method can easily be modified to pass passowrd, display name, etc. // It is recommended to write unit tests. public UserBasicDto Register(RegisterationDetails registerationDetails) { var portalSettings = registerationDetails.PortalSettings; var username = registerationDetails.UserName; var email = registerationDetails.Email; Requires.NotNullOrEmpty("email", email); var disallowRegistration = !registerationDetails.IgnoreRegistrationMode && ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) || (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration)); if (disallowRegistration) { throw new Exception(Localization.GetString("RegistrationNotAllowed", Library.Constants.SharedResources)); } // initial creation of the new User object var newUser = new UserInfo { PortalID = portalSettings.PortalId, Email = email, }; var cleanUsername = PortalSecurity.Instance.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); if (!cleanUsername.Equals(username)) { throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); } var valid = UserController.Instance.IsValidUserName(username); if (!valid) { throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); } // ensure this user doesn't exist if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null) { throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent", Library.Constants.SharedResources)); } // set username as email if not specified newUser.Username = string.IsNullOrEmpty(username) ? email : username; if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword) { newUser.Membership.Password = registerationDetails.Password; } else { // Generate a random password for the user newUser.Membership.Password = UserController.GeneratePassword(); } newUser.Membership.PasswordConfirm = newUser.Membership.Password; // set other profile properties newUser.Profile.InitialiseProfile(portalSettings.PortalId); newUser.Profile.PreferredLocale = new Localization().CurrentUICulture; newUser.Profile.PreferredTimeZone = portalSettings.TimeZone; // derive display name from supplied firstname, lastname or from email if (!string.IsNullOrEmpty(registerationDetails.FirstName) && !string.IsNullOrEmpty(registerationDetails.LastName)) { newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName; newUser.FirstName = registerationDetails.FirstName; newUser.LastName = registerationDetails.LastName; } else { newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal)); } // read all the user account settings var settings = UserController.GetUserSettings(portalSettings.PortalId); // Verify Profanity filter if (this.GetBoolSetting(settings, "Registration_UseProfanityFilter")) { var portalSecurity = PortalSecurity.Instance; if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) { throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed", Library.Constants.SharedResources)); } } // Email Address Validation var emailValidator = this.GetStringSetting(settings, "Security_EmailValidation"); if (!string.IsNullOrEmpty(emailValidator)) { var regExp = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Email); if (matches.Count == 0) { throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed", Library.Constants.SharedResources)); } } // Excluded Terms Verification var excludeRegex = this.GetExcludeTermsRegex(settings); if (!string.IsNullOrEmpty(excludeRegex)) { var regExp = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Username); if (matches.Count > 0) { throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed", Library.Constants.SharedResources)); } } // User Name Validation var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation"); if (!string.IsNullOrEmpty(userNameValidator)) { var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Username); if (matches.Count == 0) { throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed", Library.Constants.SharedResources)); } } // ensure unique username var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username); if (user != null) { if (this.GetBoolSetting(settings, "Registration_UseEmailAsUserName")) { throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail)); } var i = 1; string userName = null; while (user != null) { userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.GetUserByName(portalSettings.PortalId, userName); i++; } newUser.Username = userName; } // ensure unique display name if (this.GetBoolSetting(settings, "Registration_RequireUniqueDisplayName")) { user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName); if (user != null) { var i = 1; string displayName = null; while (user != null) { displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName); i++; } newUser.DisplayName = displayName; } } // Update display name format var displaynameFormat = this.GetStringSetting(settings, "Security_DisplayNameFormat"); if (!string.IsNullOrEmpty(displaynameFormat)) { newUser.UpdateDisplayName(displaynameFormat); } // membership is approved only for public registration newUser.Membership.Approved = (registerationDetails.IgnoreRegistrationMode || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize; newUser.Membership.PasswordQuestion = registerationDetails.Question; newUser.Membership.PasswordAnswer = registerationDetails.Answer; // final creation of user var createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify); // clear cache if (createStatus == UserCreateStatus.Success) { CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId)); } if (createStatus != UserCreateStatus.Success) { throw new Exception(UserController.GetUserCreateStatus(createStatus)); } // if (registerationDetails.IgnoreRegistrationMode) // { // Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings); // return UserBasicDto.FromUserInfo(newUser); // } // send notification to portal administrator of new user registration // check the receive notification setting first, but if register type is Private, we will always send the notification email. // because the user need administrators to do the approve action so that he can continue use the website. if (!registerationDetails.IgnoreRegistrationMode && (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration)) { Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings); SendAdminNotification(newUser, portalSettings); } return(UserBasicDto.FromUserInfo(newUser)); }
static void Main(string[] args) { // Создаем культуру. //var culture = CultureInfo.CreateSpecificCulture("ru"); var culture = CultureInfo.CurrentCulture; // Создаем менеджер ресурсов. var resourceManager = new ResourceManager("CodeBlogFitness.CMD.Languages.Messages", typeof(Program).Assembly); // Console.WriteLine(Languages.Messages.Hello); Console.WriteLine(resourceManager.GetString("Hello", culture)); Console.Write(resourceManager.GetString("EnterName", culture)); var name = Console.ReadLine(); var userController = new UserController(name); var eatingController = new EatingController(userController.CurrentUser); var exerciseController = new ExerciseController(userController.CurrentUser); // Если пользователь новый, то устанавливаем остальные свойства кроме Name if (userController.IsNewUser) { Console.Write("Введите пол:"); var gender = Console.ReadLine(); var birthDate = ParseDateTime("дата рождения"); var weight = ParseDouble("вес"); var height = ParseDouble("рост"); // Непосредственно тут устанавливаем остальные свойства. userController.SetNewUserData(gender, birthDate, weight, height); } // Вывод на консоль данных о текущем пользователе. Console.WriteLine(userController.CurrentUser); while (true) { Console.WriteLine("Что вы хотите сделать?"); Console.WriteLine("Е - ввести прием пищи"); Console.WriteLine("А - ввести упражнение"); Console.WriteLine("Q - выход"); var key = Console.ReadKey(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.E: var foods = EnterEating(); eatingController.Add(foods.Food, foods.Weight); foreach (var item in eatingController.Eating.Foods) { Console.WriteLine($"\t{item.Key} - {item.Value}"); } break; case ConsoleKey.A: var exe = EnterExercise(); exerciseController.Add(exe.Activity, exe.Begin, exe.End); foreach (var item in exerciseController.Exercises) { Console.WriteLine($"\t{item.Activity} с {item.Start.ToShortTimeString()} до { item.Finish.ToShortTimeString()}"); } break; case ConsoleKey.Q: Environment.Exit(0); break; } Console.ReadLine(); } }