public bool CheckIfUserHasFutureExaminationBookings(SystemUser user) { List<ExaminationBooking> exBookings = TimeBookings.GetUserExaminationBookings(user.LogonName); bool hasFutureBookings = exBookings.Where(booking => DateTime.Compare(DateTime.Today, booking.BookingDate) <= 0).Count() > 0; bool hasRecentApprovedExaminations = exBookings.Where(booking => DateTime.Compare(DateTime.Today.AddDays(-30), booking.ExaminationApproved) <= 0).Count() > 0; return hasFutureBookings || hasRecentApprovedExaminations; }
public CrmVcardUpdateService(string userEmail) { if (string.IsNullOrWhiteSpace(userEmail)) { throw new ArgumentException("userEmail must be a valid email address", "userEmail"); } // Establish CRM connection var crmConnection = CrmConnection.Parse(CloudConfigurationManager.GetSetting("CrmConnectionString")); var serviceUri = new Uri(crmConnection.ServiceUri + "/XRMServices/2011/Organization.svc"); this.service = new OrganizationServiceProxy(serviceUri, null, crmConnection.ClientCredentials, null); // This statement is required to enable early-bound type support. this.service.EnableProxyTypes(Assembly.GetAssembly(typeof(SystemUser))); // Create context this.orgContext = new OrganizationServiceContext(this.service); // Retrieve the system user ID of the user to impersonate. this.impersonatedUser = (from user in this.orgContext.CreateQuery<SystemUser>() where user.InternalEMailAddress == userEmail select user).FirstOrDefault(); // We impersonate the user that has sent the email if (this.impersonatedUser == null) { throw new Exception("User not found in CRM"); } this.service.CallerId = this.impersonatedUser.Id; }
public void SignIn(SystemUser user, bool createPersistentCookie) { var now = DateTime.UtcNow.ToLocalTime(); var ticket = new FormsAuthenticationTicket( 1, user.Username, now, now.Add(FormsAuthentication.Timeout), createPersistentCookie, user.Username, FormsAuthentication.FormsCookiePath); FormsAuthentication.SetAuthCookie(user.Username, createPersistentCookie); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { HttpOnly = true, Expires = now.Add(FormsAuthentication.Timeout), Secure = FormsAuthentication.RequireSSL, Path = FormsAuthentication.FormsCookiePath }; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } HttpContext.Current.Response.Cookies.Add(cookie); }
protected void btnLogin_Click(object sender, EventArgs e) { if (this.IsValid) { SystemUser user = null; usersTableAdapters.validateUserLoginTableAdapter sysusers = new usersTableAdapters.validateUserLoginTableAdapter(); users.validateUserLoginDataTable tbl = sysusers.validateUserLogin(this.txtUsername.Value.Trim(), this.txtPassword.Value.Trim()); if (tbl.Rows.Count > 0) { bool islogin; if (tbl[0].IsdatIsSignedInNull() == false){islogin = Convert.ToBoolean(tbl[0].datIsSignedIn);}else{islogin = false;} if (!islogin) { user = new SystemUser(); user.UserID = (int)tbl.Rows[0]["datID"]; user.BranchID = (int)tbl[0].datTeam; MySessionManager.BranchID = tbl[0].datTeam; //user.BranchName = tbl.Rows[0]["BranchName"].ToString(); //user.BranchCode = tbl.Rows[0]["BranchCode"].ToString(); user.RoleID = (int)tbl[0].datLevel; user.UserRole = tbl[0].datPosition.ToString(); user.UserEmailaddress = tbl[0].datEmailAddress.ToString(); if (tbl[0].IsdatCreatTeamIDNull() == false){user.TeamID = tbl[0].datCreatTeamID;}else{ } user.Username = tbl[0].datFirstnames.ToString() + " " +tbl[0].datSurname.ToString() ; if (!tbl[0].IsdatFirstnamesNull()) user.UserFullName = tbl[0].datFirstnames; if (!tbl[0].IsdatSurnameNull()) user.UserFullName = user.UserFullName + " " + tbl[0].datSurname; MySessionManager.CurrentUser = user; Response.Redirect("~/pages/dashboard.aspx"); } else { } } else { } } }
public ActionResult Edit(SystemUser systemuser) { if (ModelState.IsValid) { db.Entry(systemuser).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(systemuser); }
private void FillData(SystemUser systemUser) { // systemUser.UserName = txtUserName.Text; systemUser.FirstName = txtFisrtName.Text; systemUser.LastName = txtLastName.Text; systemUser.DOB = ctlCalender.SelectedDate.Value; systemUser.Email = txtEmail.Text; systemUser.ContactNo = txtContactNo.Text; systemUser.Address = txtAddress.Text; // su.AspUserID }
private void FillDefaultValue() { SystemUser userInfo = new SystemUser(); using (TheFacade _facade = new TheFacade()) { userInfo = _facade.TransactionFacade.GetSystemUserById(Convert.ToInt64(Session[GeneralConstant.LOGINUSERID].ToString())); } if (userInfo != null) { txtUserId.Text = userInfo.UserDesplayID; } }
public bool AddUser(SystemUser objUser) { try { repSystemUser.Add(objUser); SaveChanges(); return true; } catch (System.Exception ex) { return false; } }
public List<SystemRole> GetUserAssignRole(SystemUser user) { List<ICriterion> criterions = new List<ICriterion>(); criterions.Add(SystemUserRoleRelationBaseDao.PROPERTY_USERID.Eq(user)); List<SystemUserRoleRelation> listSystemUserRoleRelation = this.FindAll(criterions.ToArray()); List<SystemRole> assignRoles = new List<SystemRole>(); foreach (SystemUserRoleRelation relation in listSystemUserRoleRelation) { this.InitializeLazyProperties(relation); assignRoles.Add(relation.RoleID); } return assignRoles; }
protected void btn_CreateUser_Click(object sender, EventArgs e) { Result oResult = new Result(); try { SystemUser oSystemUser = new SystemUser(); SystemUserBO oSystemUserBO = new SystemUserBO(); if (IsValidSystemUserName(txt_UserName.Text) && IsValidSystemUserPassword(txt_Password.Text) && ISvalidEmail(txt_Email.Text)) { oSystemUser.SystemUserName = txt_UserName.Text; oSystemUser.SystemUserPassword = txt_Password.Text; oSystemUser.SystemUserEmail = txt_Email.Text; oResult = oSystemUserBO.SystemUserEntry(oSystemUser); if (oResult.ResultIsSuccess) { lbl_error.ForeColor = Color.Green; lbl_error.Text = oResult.ResultMessage; Object[] oObjArr = new Object[1]; oObjArr[0] = (SystemUser)oResult.ResultObject; object oObject = new object(); oObject = oObjArr; ThreadPool.QueueUserWorkItem(new WaitCallback(SendMailToSystemUser), oObject); clearControlValue(); } else { lbl_error.ForeColor = Color.Red; lbl_error.Text = oResult.ResultMessage; } } else { lbl_error.ForeColor = Color.Red; lbl_error.Text = "UserName, Password, Email cannot be empty."; } } catch (Exception oEx) { lbl_error.ForeColor = Color.Red; lbl_error.Text = "System User Entry Failed."; } }
protected void btn_Login_Click(object sender, EventArgs e) { try { if (IsValidLoginName(txt_LoginName.Text) && IsValidPassword(txt_Password.Text)) { SystemUser oSystemUser = new SystemUser(); SystemUserBO oSystemUserBO = new SystemUserBO(); Result oResult = new Result(); oSystemUser.SystemUserName = txt_LoginName.Text; oSystemUser.SystemUserPassword = txt_Password.Text; try { oResult = oSystemUserBO.SystemUserLogin(oSystemUser); if (oResult.ResultIsSuccess) { //Utils.csIsSystemUser = true; Utils.SetSession(SessionManager.csLoggedUser, oResult.ResultObject); //Utils.SetSession(SessionManager.csFromPage, PageNameManager.csDefault); Response.Redirect(ContainerManager.csMasterContainer+"?option="+OptionManager.csSystemUserMainPage); } else { lbl_Error.ForeColor = Color.Red; lbl_Error.Text = oResult.ResultMessage; } } catch (Exception oEx1) { lbl_Error.ForeColor = Color.Red; lbl_Error.Text = "Login Exception."; } } else { lbl_Error.ForeColor = Color.Red; lbl_Error.Text = "Login Name & Password Required."; } } catch (Exception oEx2) { lbl_Error.ForeColor = Color.Red; lbl_Error.Text = "Login Exception."; } }
public List<SystemRole> GetUserAssignRole(SystemUser user) { using (ISession session = GetSession()) { DetachedCriteria userAssignedRoleRelation = DetachedCriteria.For(typeof(SystemUserRoleRelation)); userAssignedRoleRelation.Add(SystemUserRoleRelationDao.PROPERTY_USERID.Eq(user)); DetachedCriteria userAssignedRole = DetachedCriteria.For(typeof(SystemRole)); userAssignedRole.Add( Subqueries.PropertyIn(SystemUserRoleRelation.PROPERTY_NAME_ROLEID, userAssignedRoleRelation)); return this.ConvertToTypedList(userAssignedRole.GetExecutableCriteria(session).List()); } }
private void LoadMenuBarByPermission(SystemUser oSystemUser, Candidate oCandidate) { String sJSMenu = String.Empty; String sLoadedControlName = String.Empty; try { PanelHorizontalMenu.Controls.Clear(); sLoadedControlName = Utils.GetSession(SessionManager.csLoadedPage).ToString(); if (oSystemUser != null && oCandidate == null) { //lbl_ControlName.Text = sLoadedControlName.Substring(0,sLoadedControlName.IndexOf(".")); if (oSystemUser.SystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { if (sLoadedControlName.Equals(ControlManager.csSystemUserMainPage) || sLoadedControlName.Equals(ControlManager.csCategoryEntry) || sLoadedControlName.Equals(ControlManager.csCategoryModification) || sLoadedControlName.Equals(ControlManager.csChangePassword) || sLoadedControlName.Equals(ControlManager.csExamEntry) || sLoadedControlName.Equals(ControlManager.csQuestionModification) || sLoadedControlName.Equals(ControlManager.csSystemUserEntry) || sLoadedControlName.Equals(ControlManager.csSystemUserModification) || sLoadedControlName.Equals(ControlManager.csQuestionEntry) || sLoadedControlName.Equals(ControlManager.csExamMofication) || sLoadedControlName.Equals(ControlManager.csLabelEntryAndModification)) { sJSMenu = File.ReadAllText(DirectoryManager.csJSMenuBarDirectory + FileManager.csAdminSystemUserMenuFile, System.Text.Encoding.Default); PanelHorizontalMenu.Controls.Add(new LiteralControl(sJSMenu)); } else if (sLoadedControlName.Equals(ControlManager.csCandidateSetup) || sLoadedControlName.Equals(ControlManager.csCandidateModification) || sLoadedControlName.Equals(ControlManager.csEvaluateCandidate) || sLoadedControlName.Equals(ControlManager.csExamineProcess) || sLoadedControlName.Equals(ControlManager.csQuestionSetup) || sLoadedControlName.Equals(ControlManager.csQuestionSetupRemove) || sLoadedControlName.Equals(ControlManager.csQuestionReportForAnExam) || sLoadedControlName.Equals(ControlManager.csResultView) || sLoadedControlName.Equals(ControlManager.csCandidateExtend)) { sJSMenu = File.ReadAllText(DirectoryManager.csJSMenuBarDirectory + FileManager.csAdminSystemUserSetupMenuFile, System.Text.Encoding.Default); PanelHorizontalMenu.Controls.Add(new LiteralControl(sJSMenu)); } } else //some controls will not shown for the Non Admin { if (sLoadedControlName.Equals(ControlManager.csSystemUserMainPage) || sLoadedControlName.Equals(ControlManager.csChangePassword) || sLoadedControlName.Equals(ControlManager.csQuestionModification) || sLoadedControlName.Equals(ControlManager.csQuestionEntry)) { sJSMenu = File.ReadAllText(DirectoryManager.csJSMenuBarDirectory + FileManager.csNonAdminSystemUserMenuFile, System.Text.Encoding.Default); PanelHorizontalMenu.Controls.Add(new LiteralControl(sJSMenu)); } else if (sLoadedControlName.Equals(ControlManager.csEvaluateCandidate) || sLoadedControlName.Equals(ControlManager.csExamineProcess) || sLoadedControlName.Equals(ControlManager.csQuestionSetup) || sLoadedControlName.Equals(ControlManager.csQuestionSetupRemove) || sLoadedControlName.Equals(ControlManager.csQuestionReportForAnExam) || sLoadedControlName.Equals(ControlManager.csResultView)) { sJSMenu = File.ReadAllText(DirectoryManager.csJSMenuBarDirectory + FileManager.csNonAdminSystemUserSetupMenuFile, System.Text.Encoding.Default); PanelHorizontalMenu.Controls.Add(new LiteralControl(sJSMenu)); } } } } catch (Exception oEx) { } }
private void CreateUser() { MembershipUser user = Membership.GetUser(txtUserName.Text.Trim()); if (user == null) { user = Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text); using (IM.Facade.TheFacade facade = new IM.Facade.TheFacade()) { systemUser = new IM.DAL.SystemUser(); systemUser.UserName = txtUserName.Text; systemUser.TypeID = Convert.ToInt32(IM.Framework.EnumHelper.UserTypeEnum.user); systemUser.IsRemoved = 0; systemUser.CreatedDate = DateTime.Now; systemUser.FirstName = txtFisrtName.Text; systemUser.LastName = txtLastName.Text; systemUser.ContactNo = txtContactNo.Text; systemUser.Email = txtEmail.Text; systemUser.DOB = Convert.ToDateTime(txtDOB.Text); systemUser.Address = txtAddress.Text; systemUser.AspUserID = new System.Guid(txtKey.Text); systemUser.UserDesplayID = (facade.TanviFacade.GetAllSystemUser().Count + 1).ToString().PadLeft(5, '0');// new string('0',4) + (facade.TanviFacade.GetAllSystemUser().Count+ 1).ToString(); systemUser.CreatedDate = DateTime.Now; systemUser.CreatedBy = Convert.ToInt64(Session[GeneralConstant.LOGINUSERID]); facade.Insert(systemUser); } Roles.AddUserToRole(txtUserName.Text, "user"); using (_facade = new TheFacade()) { UserKeyInfo userKeyInfo = _facade.TanviFacade.GetValidUserKeyInfoByUserKey(txtKey.Text); userKeyInfo.Status = 1; _facade.Update(userKeyInfo); } this.PopulateUI(); } else { } }
protected void btnSearch_Click(object sender, EventArgs e) { SystemUser sponserUserInfo = new SystemUser(); using (TheFacade _facade = new TheFacade()) { sponserUserInfo = _facade.TransactionFacade.GetSponserUserByUserDisplayId(txtUserId.Text.Trim()); } if (sponserUserInfo != null) { lblName.Text = sponserUserInfo.FirstName + " " + sponserUserInfo.LastName; lblDisplayName.Text = sponserUserInfo.UserName; lblContactNo.Text = sponserUserInfo.ContactNo; lblEmail.Text = sponserUserInfo.Email; tdInfo.Visible = true; } }
public void PopulateUI(SystemUser systemUser) { //if (Convert.ToInt64(Session[GeneralConstant.LOGINUSERID].ToString()) > 0) //{ using (TheFacade _facade = new TheFacade()) { //clientId = Convert.ToInt64(Session[GeneralConstant.LOGINUSERID].ToString()); //SystemUser systemUser = _facade.TanviFacade.GetSystemUserById(clientId); txtUserName.Text = systemUser.UserName; txtFisrtName.Text = ""; txtLastName.Text = ""; txtEmail.Text = ""; txtDOB.Text = ""; txtAddress.Text = ""; txtContactNo.Text = ""; //txtReferrer.Text = systemUser.SponsorID.ToString(); //ddlUserType.SelectedValue = systemUser.TypeID.ToString(); //ddlPayment.SelectedValue = systemUser.RegistrationPaymentTypeID.ToString(); } //} }
private void LoadControlInContainer() { String sOption = HttpContext.Current.Request.QueryString.Get("option"); //if (Utils.csIsSystemUser) if(Utils.GetSession(SessionManager.csLoggedUser).GetType().Name.Equals(TypeManager.csSystemUser)) { SystemUser oSystemUser = new SystemUser(); Guid gSystemUserID = Guid.Empty; String sSystemUserName = String.Empty; String sSystemUserPassword = String.Empty; oSystemUser = (SystemUser)Utils.GetSession(SessionManager.csLoggedUser); gSystemUserID = oSystemUser.SystemUserID; sSystemUserName = oSystemUser.SystemUserName; sSystemUserPassword = oSystemUser.SystemUserPassword; if (sOption.Equals(OptionManager.csSystemUserMainPage)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csSystemUserMainPage); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csSystemUserMainPage)); } else if (sOption.Equals(OptionManager.csExamEntry) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csExamEntry); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csExamEntry)); } else if (sOption.Equals(OptionManager.csDefault)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csDefault); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csDefault)); } else if (sOption.Equals(OptionManager.csSystemUserEntry) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csSystemUserEntry); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csSystemUserEntry)); } else if (sOption.Equals(OptionManager.csCategoryEntry) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csCategoryEntry); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csCategoryEntry)); } else if (sOption.Equals(OptionManager.csQuestionEntry)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csQuestionEntry); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csQuestionEntry)); } else if (sOption.Equals(OptionManager.csQuestionModification)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csQuestionModification); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csQuestionModification)); } else if (sOption.Equals(OptionManager.csChangePassword)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csChangePassword); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csChangePassword)); } else if (sOption.Equals(OptionManager.csCandidateSetup) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csCandidateSetup); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csCandidateSetup)); } else if (sOption.Equals(OptionManager.csEvaluateCandidate)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csEvaluateCandidate); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csEvaluateCandidate)); } else if (sOption.Equals(OptionManager.csQuestionSetup)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csQuestionSetup); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csQuestionSetup)); } else if (sOption.Equals(OptionManager.csResultView)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csResultView); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csResultView)); } else if (sOption.Equals(OptionManager.csExamMofication) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csExamMofication); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csExamMofication)); } else if (sOption.Equals(OptionManager.csQuestionSetupRemove)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csQuestionSetupRemove); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csQuestionSetupRemove)); } else if (sOption.Equals(OptionManager.csCandidateModification) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csCandidateModification); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csCandidateModification)); } else if (sOption.Equals(OptionManager.csSystemUserModification) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csSystemUserModification); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csSystemUserModification)); } else if (sOption.Equals(OptionManager.csCategoryModification) && sSystemUserName.ToLower().Equals(LoginManager.csAdministrator)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csCategoryModification); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csCategoryModification)); } else if (sOption.Equals(OptionManager.csExamineProcess)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csExamineProcess); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csExamineProcess)); } else if (sOption.Equals(OptionManager.csCandidateExtend)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csCandidateExtend); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csCandidateExtend)); } else if (sOption.Equals(OptionManager.csLabelEntryAndModification)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csLabelEntryAndModification); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csLabelEntryAndModification)); } else if (sOption.Equals(OptionManager.csQuestionReportForAnExam)) { Utils.SetSession(SessionManager.csLoadedPage, ControlManager.csQuestionReportForAnExam); plh_Control.Controls.Add(LoadControl("Controls/" + ControlManager.csQuestionReportForAnExam)); } } }
private bool AreValidCredentials(SystemUser user, CredentialModel credentials) { return(_hasher.VerifyHashedPassword(user, user.PasswordHash, credentials.Password) == PasswordVerificationResult.Success); }
private static Guid CreateSystemUser(String userName, String firstName, String lastName, String domain, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { CreateADAccount(userName, firstName, lastName, serviceProxy, ref ldapPath); // Retrieve the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = domain + userName, FirstName = firstName, LastName = lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = serviceProxy.Create(user); if (!String.IsNullOrWhiteSpace(roleStr)) { // Retrieve the specified security role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Assign the security role to the newly created Microsoft Dynamics CRM user. AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id), }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } return userId; }
public void UpdateUser(SystemUser user) { _userDAL.UpdateUser(user); }
public void Multiple_Entities_With_Multiple_Users() { var context = new XrmFakedContext(); var contact1 = new Contact { Id = Guid.NewGuid() }; var contact2 = new Contact { Id = Guid.NewGuid() }; var user1 = new SystemUser { Id = Guid.NewGuid() }; var user2 = new SystemUser { Id = Guid.NewGuid() }; var user3 = new SystemUser { Id = Guid.NewGuid() }; context.Initialize(new List <Entity> { contact1, user1, contact2, user2, user3 }); var service = context.GetFakedOrganizationService(); GrantAccessRequest gar1 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = user1.ToEntityReference() }, Target = contact1.ToEntityReference() }; service.Execute(gar1); GrantAccessRequest gar2 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.CreateAccess | AccessRights.DeleteAccess | AccessRights.ShareAccess, Principal = user1.ToEntityReference() }, Target = contact2.ToEntityReference() }; service.Execute(gar2); GrantAccessRequest gar3 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.CreateAccess | AccessRights.DeleteAccess | AccessRights.ShareAccess, Principal = user2.ToEntityReference() }, Target = contact1.ToEntityReference() }; service.Execute(gar3); GrantAccessRequest gar4 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = user2.ToEntityReference() }, Target = contact2.ToEntityReference() }; service.Execute(gar4); RetrievePrincipalAccessRequest rpar = new RetrievePrincipalAccessRequest { Target = contact1.ToEntityReference(), Principal = user1.ToEntityReference() }; RetrievePrincipalAccessResponse rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.NotEqual(AccessRights.None, rpaResp.AccessRights); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess)); rpar = new RetrievePrincipalAccessRequest { Target = contact2.ToEntityReference(), Principal = user1.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.NotEqual(AccessRights.None, rpaResp.AccessRights); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess)); rpar = new RetrievePrincipalAccessRequest { Target = contact1.ToEntityReference(), Principal = user2.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.NotEqual(AccessRights.None, rpaResp.AccessRights); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess)); rpar = new RetrievePrincipalAccessRequest { Target = contact2.ToEntityReference(), Principal = user2.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.NotEqual(AccessRights.None, rpaResp.AccessRights); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess)); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess)); rpar = new RetrievePrincipalAccessRequest { Target = contact1.ToEntityReference(), Principal = user3.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.Equal(AccessRights.None, rpaResp.AccessRights); rpar = new RetrievePrincipalAccessRequest { Target = contact2.ToEntityReference(), Principal = user3.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.Equal(AccessRights.None, rpaResp.AccessRights); }
public SystemUser GetSystemUserByUserName(string userName) { SystemUser systemUser = new SystemUser(); // return Database.SystemUsers.Single(s => s.UserName.Equals(userName) && s.IsRemoved == 0); try { systemUser = Database.SystemUsers.Single(s => s.UserName==userName && s.IsRemoved == 0); return systemUser; } catch (Exception ex) { return null; } //return systemUser; }
private void FillData(SystemUser systemUser) { systemUser.UserName = txtUserName.Text; systemUser.FirstName = txtFisrtName.Text; systemUser.LastName = txtLastName.Text; systemUser.DOB = Convert.ToDateTime(txtDOB.Text); systemUser.Email = txtEmail.Text; systemUser.ContactNo = txtContactNo.Text; systemUser.Address = txtAddress.Text; // su.AspUserID }
// GET: /Create public ActionResult Create(int id) { //Get Item From Database PriceTrackingSetupGroup group = new PriceTrackingSetupGroup(); group = priceTrackingSetupGroupRepository.GetPriceTrackingSetupGroup(id); //Check Exists if (group == null) { ViewData["ActionMethod"] = "EditGet"; return(View("RecordDoesNotExistError")); } //Check Access Rights to Domain if (!hierarchyRepository.AdminHasDomainWriteAccess(groupName)) { ViewData["Message"] = "You do not have access to this item"; return(View("Error")); } //Set Access Rights to Admin ViewData["AdminAccess"] = ""; if (hierarchyRepository.AdminHasDomainWriteAccess(adminGroupName)) { ViewData["AdminAccess"] = "WriteAccess"; } //PriceTrackingSetupGroup ViewData["PriceTrackingSetupGroupId"] = group.PriceTrackingSetupGroupId; ViewData["PriceTrackingSetupGroupName"] = group.PriceTrackingSetupGroupName; //PriceTrackingSetupGroupItemAir PriceTrackingSetupGroupItemAir priceTrackingSetupGroupItemAir = new PriceTrackingSetupGroupItemAir(); priceTrackingSetupGroupItemAir.PriceTrackingSetupGroupId = id; //Default Flags priceTrackingSetupGroupItemAir.SharedSavingsFlag = true; priceTrackingSetupGroupItemAir.TransactionFeeFlag = false; priceTrackingSetupGroupItemAir.RefundableToRefundableWithPenaltyForRefundAllowedFlag = true; priceTrackingSetupGroupItemAir.RefundableToNonRefundableAllowedFlag = true; priceTrackingSetupGroupItemAir.VoidWindowAllowedFlag = true; priceTrackingSetupGroupItemAir.RefundableToRefundableOutsideVoidWindowAllowedFlag = true; priceTrackingSetupGroupItemAir.NonRefundableToNonRefundableOutsideVoidWindowAllowedFlag = true; priceTrackingSetupGroupItemAir.ExchangesAllowedFlag = true; priceTrackingSetupGroupItemAir.VoidExchangeAllowedFlag = true; priceTrackingSetupGroupItemAir.NonRefundableToLowerNonRefundableWithDifferentChangeFeeAllowedFlag = true; priceTrackingSetupGroupItemAir.RefundableToLowerNonRefundableAllowedFlag = true; priceTrackingSetupGroupItemAir.RefundableToLowerRefundableAllowedFlag = true; priceTrackingSetupGroupItemAir.NonPenaltyRefundableToLowerPenaltyRefundableAllowedFlag = true; priceTrackingSetupGroupItemAir.ChargeChangeFeeUpFrontForSpecificCarriersFlag = true; priceTrackingSetupGroupItemAir.ChangeFeeMustBeUsedFromResidualValueFlag = true; priceTrackingSetupGroupItemAir.AutomaticReticketingFlag = true; //Pricing Model Defaults priceTrackingSetupGroupItemAir.SharedSavingsAmount = 30; //Switch Window Defaults priceTrackingSetupGroupItemAir.RefundableToRefundablePreDepartureDayAmount = 5; priceTrackingSetupGroupItemAir.RefundableToNonRefundablePreDepartureDayAmount = 5; //Reason Codes priceTrackingSetupGroupItemAir.RealisedSavingsCode = "XX"; priceTrackingSetupGroupItemAir.MissedSavingsCode = "L"; //Admin Only priceTrackingSetupGroupItemAir.AlphaCodeRemarkField = "Y"; //Currency CurrencyRepository currencyRepository = new CurrencyRepository(); SelectList currencysList = new SelectList(currencyRepository.GetAllCurrencies().ToList(), "CurrencyCode", "Name"); ViewData["Currencies"] = currencysList; //Lists ViewData["ClientHasProvidedWrittenApprovalFlagList"] = new SelectList(commonRepository.GetTrueFalseList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.ClientHasProvidedWrittenApprovalFlag); ViewData["SharedSavingsList"] = new SelectList(commonRepository.GetTrueFalseList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.SharedSavingsFlag); ViewData["TransactionFeeList"] = new SelectList(commonRepository.GetTrueFalseList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.TransactionFeeFlag); ViewData["CentralFulfillmentTimeZoneRuleCodes"] = new SelectList(timeZoneRuleRepository.GetAllTimeZoneRules().ToList(), "TimeZoneRuleCode", "TimeZoneRuleCodeDesc"); ViewData["TimeZoneRules"] = new SelectList(timeZoneRuleRepository.GetAllTimeZoneRules().ToList(), "TimeZoneRuleCode", "TimeZoneRuleCodeDesc"); ViewData["RefundableToRefundableWithPenaltyForRefundAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.RefundableToRefundableWithPenaltyForRefundAllowedFlag); ViewData["RefundableToNonRefundableAllowedFlag"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.RefundableToNonRefundableAllowedFlag); ViewData["VoidWindowAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.VoidWindowAllowedFlag); ViewData["RefundableToRefundableOutsideVoidWindowAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.RefundableToRefundableOutsideVoidWindowAllowedFlag); ViewData["NonRefundableToNonRefundableOutsideVoidWindowAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.NonRefundableToNonRefundableOutsideVoidWindowAllowedFlag); ViewData["ExchangesAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.ExchangesAllowedFlag); ViewData["VoidExchangeAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.VoidExchangeAllowedFlag); ViewData["ExchangePreviousExchangeAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text"); ViewData["NonRefundableToLowerNonRefundableWithDifferentChangeFeeAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.NonRefundableToLowerNonRefundableWithDifferentChangeFeeAllowedFlag); ViewData["RefundableToLowerNonRefundableAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.RefundableToLowerNonRefundableAllowedFlag); ViewData["RefundableToLowerRefundableAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.RefundableToLowerRefundableAllowedFlag); ViewData["NonPenaltyRefundableToLowerPenaltyRefundableAllowedFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.NonPenaltyRefundableToLowerPenaltyRefundableAllowedFlag); ViewData["ChargeChangeFeeUpFrontForSpecificCarriersFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.ChargeChangeFeeUpFrontForSpecificCarriersFlag); ViewData["ChangeFeeMustBeUsedFromResidualValueFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.ChangeFeeMustBeUsedFromResidualValueFlag); ViewData["TrackPrivateNegotiatedFareFlagList"] = new SelectList(commonRepository.GetAllowedNotAllowedList().ToList(), "Value", "Text"); ViewData["AutomaticReticketingFlagList"] = new SelectList(commonRepository.GetTrueFalseList().ToList(), "Value", "Text", priceTrackingSetupGroupItemAir.AutomaticReticketingFlag); //System User ViewData["SystemUser"] = ""; string adminUserGuid = User.Identity.Name.Split(new[] { '|' })[0]; SystemUserRepository systemUserRepository = new SystemUserRepository(); SystemUser systemUser = systemUserRepository.GetUserBySystemUserGuid(adminUserGuid); if (systemUser != null) { string username = systemUser.FirstName + " " + systemUser.LastName; ViewData["SystemUser"] = string.Format("{0} - {1}", username, adminUserGuid); } return(View(priceTrackingSetupGroupItemAir)); }
public bool Update(SystemUser o) { return(sDAL.Update(o)); }
private bool IsVip(SystemUser systemUser) { // TODO return(false); }
private ITaxPolicy GenerateTaxPolicy(SystemUser systemUser) { // TODO determine tax based on user's location return(new DefaultTaxPolicy()); }
/// <summary> /// 新增用户信息 /// </summary> /// <param name="user">The user.</param> /// Author : Napoleon /// Created : 2015-01-19 10:43:24 public int SaveAddUser(SystemUser user) { return(_userDao.SaveAddUser(user)); }
/// <summary> /// 更新用户信息 /// </summary> /// <param name="user">The user.</param> /// Author : Napoleon /// Created : 2015-01-19 16:24:22 public int UpdateUser(SystemUser user) { return(_userDao.UpdateUser(user)); }
public SystemUser getUserByName(string name) { SystemUser systemUser = systemUserCache.getByName(name); if (systemUser != null) { return(systemUser); } Database.Domain.SystemUser DatabaseUser = systemUserRepository.GetByName(name); if (DatabaseUser == null) { return(null); } systemUser = new SystemUser(DatabaseUser.Id, DatabaseUser.UserName, DatabaseUser.Email, DatabaseUser.Image, DatabaseUser.Money, DatabaseUser.Rank, DatabaseUser.GamesPlayed); // Try to get the image from the database. try { // Get the user's profile picture file from memory. var returnedImage = Image.FromFile(systemUser.userImage); // Convert user's profile picture into byte array in order to send over TCP systemUser.userImageByteArray = imageToByteArray(returnedImage); } catch { } systemUserCache.addOrUpdate(systemUser); return(systemUser); //SqlConnection connection = new SqlConnection(connectionString); //SqlCommand cmd = new SqlCommand(); //SqlDataReader reader; //cmd.CommandText = "SELECT Id,email,image,money,rank,gamesPlayed FROM SystemUsers WHERE UserName=@UserName"; //cmd.CommandType = CommandType.Text; //cmd.Connection = connection; //cmd.Parameters.AddWithValue("@UserName", name); //connection.Open(); //reader = cmd.ExecuteReader(); //if (!reader.HasRows || !reader.Read()) // return null; //// string s = reader["email"].ToString(); //SystemUser su = new SystemUser(int.Parse(reader["Id"].ToString()), name, reader["email"].ToString(), reader["image"].ToString(), int.Parse(reader["money"].ToString()), int.Parse(reader["rank"].ToString()), int.Parse(reader["gamesPlayed"].ToString())); //connection.Close(); //// Try to get the image from the database. //try //{ // // Get the user's profile picture file from memory. // var returnedImage = Image.FromFile(su.userImage); // // Convert user's profile picture into byte array in order to send over TCP // su.userImageByteArray = imageToByteArray(returnedImage); //} //catch { } //return su; }
public static bool loginCheck(SystemUser person) { //this is a bool that tells it if you are a vaild login in the eyes of the database //first checks if role is allowed to login. if (!allowedLogin(person.roleId)) { return false; } //next gets session key tied to the account. string sessionKey = getUserSessionKey(person.userId); //next checks to see if keys match if (sessionKey == "" || sessionKey != person.sessionKey) { //this means the keys do not match if (sessionKey != person.sessionKey) { //locks the account SystemUser.lockUser(person.userId); } return false; } //checks to see if user is locked. if (isUserLocked(person.userId)) { return false; } //nothing went wrong they are allowed to see the page. return true; }
public static void ChangeAuthority(SystemUser newUser) { CurrentUser = newUser; }
public void AddNewUser(UserViewModel newUser) { Person person = null; SystemUser systemUser = new SystemUser { UserName = newUser.UserName, Email = newUser.Email, PhoneNumber = newUser.PhoneNumber }; string passHash = userManager.PasswordHasher.HashPassword(systemUser, newUser.Password); systemUser.PasswordHash = passHash; userManager.CreateAsync(systemUser).Wait(); string role = newUser.Role.ToString(); userManager.AddToRoleAsync(systemUser, role).Wait(); switch (newUser.Role) { case UserRoleTypes.Admin: person = new Admin(); SetPersonProperties(person, newUser, systemUser); context.Admins.Add(person as Admin); break; case UserRoleTypes.Patient: person = new Patient(); SetPersonProperties(person, newUser, systemUser); context.Patients.Add(person as Patient); break; case UserRoleTypes.Doctor: person = new Doctor(); SetPersonProperties(person, newUser, systemUser); context.Doctors.Add(person as Doctor); break; case UserRoleTypes.Nurse: person = new Nurse(); SetPersonProperties(person, newUser, systemUser); context.Nurses.Add(person as Nurse); break; case UserRoleTypes.InternalPharmacist: person = new InternalPharmacist(); SetPersonProperties(person, newUser, systemUser); context.InternalPharmacists.Add(person as InternalPharmacist); break; case UserRoleTypes.ExternalPharmacist: person = new ExternalPharmacist(); SetPersonProperties(person, newUser, systemUser); context.ExternalPharmacists.Add(person as ExternalPharmacist); break; case UserRoleTypes.Storekeeper: person = new Storekeeper(); SetPersonProperties(person, newUser, systemUser); context.Storekeepers.Add(person as Storekeeper); break; default: throw new Exception("Unknown user type when creating new user!"); } context.SaveChanges(); }
/// <summary> /// Retrieves the requested SystemUser record. If the record does not exist, a new /// Microsoft Dynamics CRM SystemUser record is created and an associated Active /// Directory account is created, if it doesn't currently exist. /// </summary> /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param> /// <param name="firstName">The first name of the system user to be retrieved</param> /// <param name="lastName">The last name of the system user to be retrieved</param> /// <param name="roleStr">The string representing the Microsoft Dynamics CRM security /// role for the user</param> /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft /// Dynamics CRM environment</param> /// <param name="ldapPath">The LDAP path for your network - you can either call /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param> /// <returns></returns> public static Guid RetrieveSystemUser(String userName, String firstName, String lastName, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { String domain; Guid userId = Guid.Empty; if (serviceProxy == null) { throw new ArgumentNullException("serviceProxy"); } if (String.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException("UserName"); } if (String.IsNullOrWhiteSpace(firstName)) { throw new ArgumentNullException("FirstName"); } if (String.IsNullOrWhiteSpace(lastName)) { throw new ArgumentNullException("LastName"); } // Obtain the current user's information. WhoAmIRequest who = new WhoAmIRequest(); WhoAmIResponse whoResp = (WhoAmIResponse)serviceProxy.Execute(who); Guid currentUserId = whoResp.UserId; SystemUser currentUser = serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity <SystemUser>(); // Extract the domain and create the LDAP object. String[] userPath = currentUser.DomainName.Split(new char[] { '\\' }); if (userPath.Length > 1) { domain = userPath[0] + "\\"; } else { domain = String.Empty; } SystemUser existingUser = GetUserIdIfExist(serviceProxy, domain, userName, firstName, lastName); if (existingUser != null) { userId = existingUser.SystemUserId.Value; if (!String.IsNullOrWhiteSpace(roleStr)) { // Check to make sure the user is assigned the correct role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Associate the user with the role when needed. if (!UserInRole(serviceProxy, userId, role.Id)) { AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id) }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } } } else { // Create the system user in Microsoft Dynamics CRM if the user doesn't // already exist. userId = CreateSystemUser(userName, firstName, lastName, domain, roleStr, serviceProxy, ref ldapPath); } return(userId); }
void refreshTabs() { tabbedView.Visible = true; CKeyNLR selected = null; _currentUser = null; if (userList.GetSelectedCount() > 0) { selected = userList.GetSelectedKeys().GetFirst(); if (WAFContext.Session.NodeExists(selected.NodeId, true, true)) { _currentUser = WAFContext.Session.GetContent<SystemUser>(selected); } else { selected = null; cntFrm.Content = null; userList.ClearFlaggedValues(); } } if (selected == null) { tabbedView.Visible = false; return; } // Details if (cntFrm.Content == null || cntFrm.Content.RootContent.Key.lKey != _currentUser.Key.lKey) { cntFrm.Content = _currentUser; } // Effective memberships AqlQuery qm = WAFContext.Session.CreateQuery(); qm.From<UserGroup>(); qm.Select<UserGroup>(); qm.Select(AqlUserGroup.NodeId); UniqueList<int> allGroupMembersShips; try { allGroupMembersShips = _currentUser.GetAllMembershipsById(); } catch (CircularReferenceException error) { WAFContext.Session.Notify(error); allGroupMembersShips = new UniqueList<int>(-1); } qm.Where(Aql.In(AqlUserGroup.NodeId, allGroupMembersShips)); listMemberships.Query = qm; // Effective permissions AqlQuery qp = WAFContext.Session.CreateQuery(); qp.From<ContentBase>(); qp.Select<ContentBase>(); if (!_currentUser.IsAdmin) { AqlExpressionBuilder ex = new AqlExpressionBuilder(); UniqueList<int> ms = new UniqueList<int>(allGroupMembersShips); ms.Add((int)SystemUserGroupType.AllUsers); ms.Add((int)SystemUserGroupType.Anonymous); AqlPropertyInteger prop = null; switch (rblPermissions.SelectedValue) { case "Read": prop = AqlContent.ReadGroupId; break; case "Edit": prop = AqlContent.EditGroupId; break; case "Publish": prop = AqlContent.PublishGroupId; break; default: break; } qp.Where(Aql.In(prop, ms)); } listPermissions.Query = qp; // Relevant content AqlQuery qr = WAFContext.Session.CreateQuery(); qr.From<ContentBase>(); qr.Select<ContentBase>(); qr.Select(AqlContent.NodeId); qr.IncludeUnpublished = true; qr.Where( (AqlContent.AuthorId == _currentUser.NodeId) | (AqlContent.CreatedById == _currentUser.NodeId) | (AqlContent.PublicationApprovedById == _currentUser.NodeId) | (AqlContent.ChangedById == _currentUser.NodeId )); listRelevant.Query = qr; }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered WebFormFill.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace("WebFormFill.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); ITracingService t = tracingService; IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { // TODO: Implement your custom Workflow business logic. #region 1. Get the Web Form Fill from the workflow context. t.Trace("1. Get the Form Fill from the workflow context."); cldrkt_webformfill webFormFill = (cldrkt_webformfill)service.Retrieve( context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet { AllColumns = true }); #endregion 1. Get the Web Form Fill from the workflow context. #region 2. Get the transaction owner and response email sender. QueryExpression userQuery = new QueryExpression { EntityName = SystemUser.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "domainname", Operator = ConditionOperator.Equal, Values = { "*****@*****.**"}, } } } }; t.Trace("2.1 Get the system user who will send the email."); SystemUser user = (SystemUser)service.RetrieveMultiple(userQuery).Entities.FirstOrDefault(); t.Trace("2.2 The sender is: " + user.FullName.ToString()); #endregion 2. Get the transaction owner and response email sender. #region 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist. t.Trace("3. Find or create the Contact from the email address." + webFormFill.cldrkt_Email); Contact contact = new Contact { EMailAddress1 = webFormFill.cldrkt_Email, FirstName = webFormFill.cldrkt_FirstName, Id = Guid.NewGuid(), LastName = webFormFill.cldrkt_LastName, Telephone1 = webFormFill.cldrkt_BusinessPhone, }; t.Trace("3.1 Look up the Contact using the email address entered: " + webFormFill.cldrkt_Email.ToString()); QueryExpression contactsQuery = new QueryExpression { EntityName = Contact.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "emailaddress1", Operator = ConditionOperator.Equal, Values = { contact.EMailAddress1}, } } } }; Contact c = (Contact)service.RetrieveMultiple(contactsQuery).Entities.FirstOrDefault(); if (c != null) { contact.Id = c.Id; // Will overwrite existing Contact data with entered data. contact.ParentCustomerId = c.ParentCustomerId; // So it will be there for the Account lookup. t.Trace("3.2.1 The existing contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1); } else { t.Trace("3.3.1 Create a new contact."); contact.Id = service.Create(contact); t.Trace("3.3.2 The new contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1); } service.Update(contact); #endregion 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist. #region 4. Look up or create the Account and map this Contact to it. t.Trace("4. Look up or create the Account and map this Contact to it."); //t.Trace("4. Contact is " + contact.FullName); //t.Trace("4. Contact.Id is " + contact.Id); //t.Trace("4. contact.ParentCustomerId is " + contact.ParentCustomerId.ToString()); Account account = new Account { Name = webFormFill.cldrkt_Organization, }; // Look up or create the parent Account. if (contact.ParentCustomerId != null) { t.Trace("4.1 Build the parent account query."); // Look up the parent account. QueryExpression parentAccountQuery = new QueryExpression { EntityName = Account.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "accountid", Operator = ConditionOperator.Equal, Values = { contact.ParentCustomerId.Id,}, } }, }, }; t.Trace("4.2 Look up Account a."); Account a = (Account)service.RetrieveMultiple(parentAccountQuery).Entities.FirstOrDefault(); t.Trace("4.3 If a exists, use it. Otherwise create a new Account."); if (a != null) { t.Trace("4.3.1 The Account exists."); account = a; t.Trace("4.2.2 The existing Account is " + account.Name); } else { t.Trace("4.3.2 Create a new Account."); account.Id = a.Id; t.Trace("4.3.1 The new Account is " + account.Id.ToString()); } } else { t.Trace("4.4 Create a new Account."); account.Id = service.Create(account); }; // Map the contact to the account. account.PrimaryContactId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }; service.Update(account); // Map the account to the contact. contact.ParentCustomerId = new EntityReference { Id = account.Id, LogicalName = Account.EntityLogicalName, }; service.Update(contact); #endregion 4. Look up or create the Account and map this Contact to it. #region 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response. t.Trace("5. Get the Campaign Activity, if any..."); CampaignActivity campaignActivity = new CampaignActivity(); CampaignResponse campaignResponse = new CampaignResponse(); Guid campaignActivityId = Guid.Empty; t.Trace("5.1 webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID); if (String.IsNullOrWhiteSpace(webFormFill.cldrkt_CampaignActivityID)) { campaignActivityId = Guid.Empty; } else { t.Trace("5.2 We have a webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID); Guid.TryParse(webFormFill.cldrkt_CampaignActivityID, out campaignActivityId); t.Trace("5.2.1 CampaignActivityID is " + campaignActivityId.ToString()); if (campaignActivityId != Guid.Empty) { t.Trace("5.2.2 Look up the Campaign Activity..."); campaignActivity = (CampaignActivity)service.Retrieve( CampaignActivity.EntityLogicalName, campaignActivityId, new ColumnSet { AllColumns = true }); t.Trace("5.2.3 campaignActivityId: " + campaignActivityId); t.Trace("5.2.4 campaignActivity.Id: " + campaignActivity.Id.ToString()); if (campaignActivity != null) // Found a Campaign Activity. { // Create a Campaign Response. t.Trace("5.3 Create a Campaign Response..."); campaignResponse.ChannelTypeCode = new OptionSetValue((int)636280001); // 636280001: Web Page Form fill campaignResponse.Customer = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contact.Id) } }; campaignResponse.FirstName = webFormFill.cldrkt_FirstName; campaignResponse.LastName = webFormFill.cldrkt_LastName; campaignResponse.EMailAddress = webFormFill.cldrkt_Email; campaignResponse.Telephone = webFormFill.cldrkt_BusinessPhone; campaignResponse.CompanyName = webFormFill.cldrkt_Organization; campaignResponse.PromotionCodeName = webFormFill.cldrkt_PromotionCode; campaignResponse.cldrkt_CampaignActivityId = new EntityReference { Id = campaignActivity.Id, LogicalName = CampaignActivity.EntityLogicalName, }; campaignResponse.OriginatingActivityId = new EntityReference { Id = webFormFill.Id, LogicalName = cldrkt_webformfill.EntityLogicalName, }; campaignResponse.RegardingObjectId = new EntityReference // Required, must be the parent campaign { Id = campaignActivity.RegardingObjectId.Id, LogicalName = Campaign.EntityLogicalName, }; campaignResponse.ReceivedOn = webFormFill.CreatedOn; campaignResponse.Subject = webFormFill.Subject; //TODO: Change to an available field. t.Trace("5.2.5 Create the Campaign Response."); campaignResponse.ActivityId = service.Create(campaignResponse); t.Trace("5.3.1 campaignResponse.ActivityId: " + campaignResponse.ActivityId); t.Trace("5.3.2 campaignResponse.Id: " + campaignResponse.Id.ToString()); // Update the Campaign Response. t.Trace("5.4 Update the Campaign Response."); if (campaignResponse.Id != Guid.Empty) { service.Update(campaignResponse); t.Trace("5.4.1 campaignResponse.Id = " + campaignResponse.Id.ToString()); } // Add the Campaign Activity to the Web Form Fill. t.Trace("5.5. Add the Campaign Activity to the Web Form fill"); webFormFill.cldrkt_Campaign = new EntityReference { Id = campaignActivity.RegardingObjectId.Id, LogicalName = campaignActivity.RegardingObjectId.LogicalName, }; webFormFill.cldrkt_CampaignActivity = new EntityReference { Id = campaignActivity.Id, LogicalName = campaignActivity.LogicalName, }; webFormFill.cldrkt_CampaignResponse = new EntityReference { Id = campaignResponse.Id, LogicalName = campaignResponse.LogicalName, }; t.Trace("5.6 Update the webFormFill."); service.Update(webFormFill); } } } #endregion 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response. #region 6. Create a new Opportunity and map it to the Contact. t.Trace("6. Create a new Opportunity and map it to the Contact. "); string productNumber = // Defaulting to SMSP. The Product Number has to be valid. String.IsNullOrEmpty(webFormFill.cldrkt_ProductNumber) ? "SMSP-License" : webFormFill.cldrkt_ProductNumber; QueryExpression productQuery = new QueryExpression { EntityName = Product.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "productnumber", Operator = ConditionOperator.Equal, Values = { productNumber}, } } } }; t.Trace("6.1.1 Look up the product. "); Product product = (Product)service.RetrieveMultiple(productQuery).Entities.FirstOrDefault(); t.Trace("6.1.2 product.Id is " + product.Id.ToString() + " product.ProductId is " + product.ProductId); t.Trace("6.1.3 product.ProductId is " + product.Id.ToString() + " "); t.Trace("6.2 Create the Opportunity. "); t.Trace("6.2.0 campaignActivity.Id is " + campaignActivity.Id.ToString()); t.Trace("6.2.1 campaignActivity.RegardingObjectId.Id is " + campaignActivity.RegardingObjectId.Id.ToString()); t.Trace("6.2.2 account.Name and product.ProductNumber are " + account.Name + " " + product.ProductNumber); t.Trace("6.2.3 product.PriceLevelId is " + product.PriceLevelId.Id.ToString()); Opportunity opportunity = new Opportunity { CampaignId = campaignActivity.RegardingObjectId, cldrkt_EstimatedUsers = (int?)webFormFill.cldrkt_ProductQuantity, Name = webFormFill.Subject, // Required. cldrkt_DateofLastContact = webFormFill.CreatedOn, IsRevenueSystemCalculated = true, ParentAccountId = new EntityReference { Id = account.Id, LogicalName = Account.EntityLogicalName, }, ParentContactId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }, PriceLevelId = product.PriceLevelId, // Required StepName = "1-Conversation", TransactionCurrencyId = product.TransactionCurrencyId, // Required. }; t.Trace("6.2.5 opportunity.TransactionCurrencyId is " + opportunity.TransactionCurrencyId.Name.ToString()); t.Trace("6.2.6 TransactionCurrencyId.Id is " + opportunity.TransactionCurrencyId.Id.ToString()); t.Trace("6.2.6.1 opportunity.ParentContactId.Id is " + opportunity.ParentContactId.Id.ToString()); opportunity.Id = service.Create(opportunity); service.Update(opportunity); t.Trace("6.2.7 opportunity.Id is " + opportunity.Id.ToString()); t.Trace("6.2.7.1 ShowMe price is " + Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity)); t.Trace("6.3 Create the OpportunityProduct."); OpportunityProduct opportunityProduct = new OpportunityProduct { OpportunityId = new EntityReference { LogicalName = Opportunity.EntityLogicalName, Id = opportunity.Id, }, ProductId = new EntityReference { LogicalName = Product.EntityLogicalName, Id = product.Id, }, UoMId = new EntityReference { LogicalName = UoM.EntityLogicalName, Id = product.DefaultUoMId.Id, }, Quantity = webFormFill.cldrkt_ProductQuantity, PricePerUnit = new Money { Value = Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity), }, IsPriceOverridden = true, }; t.Trace("6.3.1 Creating the opportunityProduct. "); opportunityProduct.Id = service.Create(opportunityProduct); t.Trace("6.3.2 opportunityProduct.Id is " + opportunityProduct.Id.ToString()); t.Trace("6.3.3 opportunityProductProductId.Id is " + opportunityProduct.ProductId.Id.ToString()); t.Trace("6.3.4 opportunityProduct.Quantity is " + opportunityProduct.Quantity); t.Trace("6.3.5 opportunityProduct.Quantity.Value is " + opportunityProduct.Quantity.Value); t.Trace("6.3.6 opportunityProduct.PricePerUnit is " + opportunityProduct.PricePerUnit); t.Trace("6.3.7 opportunityProduct.PricePerUnit.Value is " + opportunityProduct.PricePerUnit.Value); service.Update(opportunityProduct); service.Update(opportunity); #endregion 6. Create a new Opportunity and map it to the Contact. #region 7. Get the response email template. t.Trace(" 7. Get the email template from the Web Form Fill, otherwise use a default template"); QueryExpression templateQuery = new QueryExpression { EntityName = Template.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "title", Operator = ConditionOperator.Equal, Values = { webFormFill.cldrkt_EmailTemplateTitle}, } } } }; Template emailTemplate = new Template(); Guid defaultEmailTemplateId = Guid.Parse("d4fe12fd-72d2-e311-9e62-6c3be5be5e68"); // Default, SMSP demo request Guid emailTemplateId = new Guid(); if (String.IsNullOrEmpty(webFormFill.cldrkt_EmailTemplateTitle)) { emailTemplateId = defaultEmailTemplateId; t.Trace("7.1 No email template set from the web form."); } else { t.Trace("7.2.1 Looking up Template from webFormFill: " + webFormFill.cldrkt_EmailTemplateTitle); emailTemplate = (Template)service.RetrieveMultiple(templateQuery).Entities.FirstOrDefault(); if (emailTemplate == null) { t.Trace("Template is null"); } else { t.Trace("Template is not null."); t.Trace("Template type is: " + emailTemplate.TemplateTypeCode.ToString()); } t.Trace("7.2.1 Looked up Template using the Title. "); emailTemplateId = emailTemplate == null ? defaultEmailTemplateId : emailTemplate.Id; t.Trace("7.2.2 emailTemplateId: " + emailTemplateId.ToString()); } t.Trace("7.3.1 The email template is " + emailTemplate.Title.ToString() + " type of " + emailTemplate.TemplateTypeCode + " Id: " + emailTemplateId.ToString()); #endregion 7. Get the response email template. #region 8. Create and send the response email. t.Trace("8. Create and send the email message."); t.Trace("8. Send from: " + user.FullName.ToString()); t.Trace("8. Send to: " + contact.Id.ToString() + " using template " + emailTemplate.Title + " with Id " + emailTemplateId.ToString()); // Create an email using an Opportunity template. "To" is a Contact type. SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest { Target = new Email { To = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, opportunity.ParentContactId.Id) } }, From = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, user.Id) } }, Subject = "", Description = "", DirectionCode = true, }, RegardingId = opportunity.Id, // Required, and the type must match the Email Template type. RegardingType = emailTemplate.TemplateTypeCode, TemplateId = emailTemplateId, }; t.Trace("8.1 Send email to: " + opportunity.ParentContactId.Id.ToString() + " from: " + user.DomainName); t.Trace("8.1.1 Contact ID is: " + contact.Id.ToString() + ", email template is " + emailTemplate.Id.ToString() + ", opportunity is " + opportunity.Id.ToString()); t.Trace("8.1.2 email template id is: " + emailUsingTemplateReq.TemplateId.ToString()); SendEmailFromTemplateResponse email = (SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq); t.Trace("8.2 Email sent: " + email.Id.ToString()); #endregion 8. Create and send the response email. #region 9. Add this Contact to the Marketing List, and create the list if it doesn't exist. t.Trace("9. Add this Contact to the Marketing List. " + contact.Id.ToString() + " to List " + webFormFill.cldrkt_AddToMarketingList); List staticContactList = new List { CreatedFromCode = new OptionSetValue((int)2), // Required. Account = 1, Contact = 2, Lead = 4. Id = Guid.NewGuid(), // Required. ListName = webFormFill.cldrkt_AddToMarketingList, // Required. LogicalName = List.EntityLogicalName, OwnerId = new EntityReference { // Required. Id = user.Id, LogicalName = SystemUser.EntityLogicalName, }, StatusCode = new OptionSetValue((int)0), Type = false, // Required. True = dynamic, false = static. }; QueryExpression listQuery = new QueryExpression { EntityName = List.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "listname", Operator = ConditionOperator.Equal, Values = { webFormFill.cldrkt_AddToMarketingList}, } } } }; t.Trace("9.1 Get this list, if it exists: " + webFormFill.cldrkt_AddToMarketingList); Entity list = service.RetrieveMultiple(listQuery).Entities.FirstOrDefault(); t.Trace("9.2 Look up the list."); if (list == null) { t.Trace("9.3.1 Create a new list: " + staticContactList.Id.ToString()); staticContactList.Id = service.Create(staticContactList); } else { t.Trace("9.3.2 Use the list we found: " + list.Id.ToString()); staticContactList.Id = list.Id; } t.Trace("9.4 Add the Contact " + contact.Id.ToString() + " to List " + staticContactList.Id.ToString()); AddMemberListRequest addMemberListRequest = new AddMemberListRequest { EntityId = contact.Id, ListId = staticContactList.Id, }; service.Execute(addMemberListRequest); #endregion 9. Add this Contact to the Marketing List, and create the list if it doesn't exist. #region 10. Update the entities we've worked on. t.Trace("10. Update the entities we've worked on. "); webFormFill.RegardingObjectId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }; service.Update(webFormFill); service.Update(contact); service.Update(opportunityProduct); service.Update(opportunity); service.Update(webFormFill); #endregion 10. Update the entities we've worked on. //throw new InvalidPluginExecutionException("Finished processing the Web Form Fill update."); } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } tracingService.Trace("Exiting WebFormFill.Execute(), Correlation Id: {0}", context.CorrelationId); }
public bool Delete(SystemUser o) //删除用户(该界面可能用不到) { return(u.Delete(o)); }
protected void Page_Load(object sender, EventArgs e) { try { lblUserId.Value = Environment.UserName; if (!string.IsNullOrEmpty(Environment.UserName)) { sda = new SqlDataAccess(); sda.openConnection(Globals.ConnectionString); //string userName = @"NEF\zeynep.bulbul"; // RESEPSIYONIST //string userName = @"NEF\demet.durgut"; //SATIŞ //string userName = @"NEF\KWBornova"; //DIŞ BAYİ string userName = @"NEF\indibox"; SystemUser sInfo = SystemUserHelper.GetSystemUserByDomainName(userName, sda); //SystemUser sInfo = SystemUserHelper.GetSystemUserByDomainName(Environment.UserName, sda); if (sInfo != null && sInfo.SystemUserId != Guid.Empty) { lblUserId.Value = sInfo.SystemUserId.ToString(); lblUserType.Value = ((int)sInfo.UserType).ToString(); } else { bdy.Style.Add("background-color", "white"); bdy.InnerHtml = "<center><br /> <img src='images/warning.png' height='144' /> <br /><h1>Kullanıcı bilgileriniz CRM'de tanımlı değildir.<br> BT ekibi ile irtibata geçebilirsiniz.<h1></center>"; return; //lblUserId.Value = "12979C4A-368C-E411-80C1-005056A62B8A"; //lblUserId.Value = "8B126813-8A8B-E411-80C1-005056A62B8A"; //Nef Test //lblUserId.Value = "246d808b-8774-e411-80e4-005056b0203a"; //ınnthebox test // lblUserId.Value = "8A5D461F-A6A7-E411-80C5-005056A62B8A"; //ınnthebox test Pilot //lblUserId.Value = "19C13874-4FAB-E311-BC40-00155D010409"; // pilot iş gyo //lblUserId.Value = "5A49C200-5A97-E411-80C0-005056A60603"; //ınnthebox test Live //lblUserType.Value = ((int)UserTypes.SatisDanismani).ToString(); //lblUserId.Value = "359BA910-ACC0-E311-B9D9-00155D011C0A"; //lblUserType.Value = ((int)UserTypes.CallCenter).ToString(); //is GYO Satis Test User //lblUserId.Value = "0F3DA178-CDEC-E411-80D0-005056A60603"; //lblUserType.Value = ((int)UserTypes.IsGyoCallCenter).ToString(); //lblUserId.Value = "B0E2D6C9-7D7B-E311-9E00-00155D5A1714"; //Paris //lblUserType.Value = ((int)UserTypes.MusteriIliskileri).ToString(); //lblUserType.Value = ((int)UserTypes.CallCenter).ToString(); //lblUserType.Value = ((int)UserTypes.Resepsiyonist).ToString(); //lblUserType.Value = ((int)UserTypes.CallCenter).ToString(); // return; } } } catch (Exception ex) { } finally { sda.closeConnection(); } }
public void Entity_Revoked_Access_Does_Not_Have_Access() { var context = new XrmFakedContext(); var contact = new Contact { Id = Guid.NewGuid() }; var user = new SystemUser { Id = Guid.NewGuid() }; context.Initialize(new List <Entity> { contact, user }); var service = context.GetFakedOrganizationService(); GrantAccessRequest gar = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess, Principal = user.ToEntityReference() }, Target = contact.ToEntityReference() }; service.Execute(gar); RetrievePrincipalAccessRequest rpar = new RetrievePrincipalAccessRequest { Target = contact.ToEntityReference(), Principal = user.ToEntityReference() }; RetrievePrincipalAccessResponse rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.NotEqual(AccessRights.None, rpaResp.AccessRights); Assert.True(rpaResp.AccessRights.HasFlag(AccessRights.ReadAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AppendToAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.AssignAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.CreateAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.DeleteAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.ShareAccess)); Assert.False(rpaResp.AccessRights.HasFlag(AccessRights.WriteAccess)); RevokeAccessRequest rar = new RevokeAccessRequest { Target = contact.ToEntityReference(), Revokee = user.ToEntityReference() }; service.Execute(rar); rpar = new RetrievePrincipalAccessRequest { Target = contact.ToEntityReference(), Principal = user.ToEntityReference() }; rpaResp = (RetrievePrincipalAccessResponse)service.Execute(rpar); Assert.Equal(AccessRights.None, rpaResp.AccessRights); }
public static bool AddAuthenticatedUser(SystemUser user) { return(LoggedUsersDic.TryAdd(user.AuthToken, user)); }
public void RetrieveSharedPrincipalsAndAccess_Test() { var context = new XrmFakedContext(); var contact1 = new Contact { Id = Guid.NewGuid() }; var contact2 = new Contact { Id = Guid.NewGuid() }; var user1 = new SystemUser { Id = Guid.NewGuid() }; var user2 = new SystemUser { Id = Guid.NewGuid() }; var user3 = new SystemUser { Id = Guid.NewGuid() }; context.Initialize(new List <Entity> { contact1, user1, contact2, user2, user3 }); var service = context.GetFakedOrganizationService(); GrantAccessRequest gar1 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = user1.ToEntityReference() }, Target = contact1.ToEntityReference() }; service.Execute(gar1); GrantAccessRequest gar2 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.CreateAccess | AccessRights.DeleteAccess | AccessRights.ShareAccess, Principal = user1.ToEntityReference() }, Target = contact2.ToEntityReference() }; service.Execute(gar2); GrantAccessRequest gar3 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.CreateAccess | AccessRights.DeleteAccess | AccessRights.ShareAccess, Principal = user2.ToEntityReference() }, Target = contact1.ToEntityReference() }; service.Execute(gar3); GrantAccessRequest gar4 = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = user2.ToEntityReference() }, Target = contact2.ToEntityReference() }; service.Execute(gar4); RetrieveSharedPrincipalsAndAccessRequest req = new RetrieveSharedPrincipalsAndAccessRequest { Target = contact1.ToEntityReference() }; RetrieveSharedPrincipalsAndAccessResponse resp = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(req); foreach (PrincipalAccess pa in resp.PrincipalAccesses) { if (pa.Principal.Id == user1.Id) { Assert.NotEqual(AccessRights.None, pa.AccessMask); Assert.True(pa.AccessMask.HasFlag(AccessRights.ReadAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendToAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AssignAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.CreateAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.DeleteAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.ShareAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.WriteAccess)); } else if (pa.Principal.Id == user2.Id) { Assert.NotEqual(AccessRights.None, pa.AccessMask); Assert.True(pa.AccessMask.HasFlag(AccessRights.ReadAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendToAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AssignAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.CreateAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.DeleteAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.ShareAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.WriteAccess)); } else if (pa.Principal.Id == user3.Id) { Assert.Equal(AccessRights.None, pa.AccessMask); } } req = new RetrieveSharedPrincipalsAndAccessRequest { Target = contact2.ToEntityReference() }; resp = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(req); foreach (PrincipalAccess pa in resp.PrincipalAccesses) { if (pa.Principal.Id == user2.Id) { Assert.NotEqual(AccessRights.None, pa.AccessMask); Assert.True(pa.AccessMask.HasFlag(AccessRights.ReadAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendToAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AssignAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.CreateAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.DeleteAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.ShareAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.WriteAccess)); } else if (pa.Principal.Id == user1.Id) { Assert.NotEqual(AccessRights.None, pa.AccessMask); Assert.True(pa.AccessMask.HasFlag(AccessRights.ReadAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AppendToAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.AssignAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.CreateAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.DeleteAccess)); Assert.True(pa.AccessMask.HasFlag(AccessRights.ShareAccess)); Assert.False(pa.AccessMask.HasFlag(AccessRights.WriteAccess)); } else if (pa.Principal.Id == user3.Id) { Assert.Equal(AccessRights.None, pa.AccessMask); } } }
public static SystemUser GetSystemUserInfoRetailer(Guid systemUserId, SqlDataAccess sda) { SystemUser returnValue = new SystemUser(); #region | SQL DATA ACCCESS | string sqlQuery = @"select S.DomainName ,S.SystemUserId ,S.FullName ,S.EntityImage ,S.EntityImage_URL ,S.EntityImageId ,S.new_jobstatus JobStatus ,S.BusinessUnitId ,T.TeamId from SystemUser as S (NOLOCK) INNER JOIN TeamMembership AS TM (NOLOCK) ON S.SystemUserId = TM.SystemUserId INNER JOIN Team AS T (NOLOCK) ON T.IsDefault = 0 AND T.TeamId = TM.TeamId WHERE S.SystemUserId=@systemuserId ORDER BY S.FullName " ; #endregion SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@systemuserId", systemUserId) }; DataTable dt = sda.getDataTable(sqlQuery, parameters); if (dt.Rows.Count > 0) { returnValue.SystemUserId = (Guid)dt.Rows[0]["SystemUserId"]; returnValue.FullName = dt.Rows[0]["FullName"].ToString(); if (dt.Rows[0]["EntityImage"] != DBNull.Value) { returnValue.Image = (byte[])dt.Rows[0]["EntityImage"]; } if (dt.Rows[0]["JobStatus"] != DBNull.Value) { returnValue.UserType = (UserTypes)((int)dt.Rows[0]["JobStatus"]); } if (dt.Rows[0]["BusinessUnitId"] != DBNull.Value) { returnValue.BusinessUnitId = (Guid)dt.Rows[0]["BusinessUnitId"]; } if (dt.Rows[0]["TeamId"] != DBNull.Value) { returnValue.TeamId = (Guid)dt.Rows[0]["TeamId"]; } } return(returnValue); }
public static bool RemoveAuthenticatedUser(string token) { SystemUser user = null; return(LoggedUsersDic.TryRemove(token, out user)); }
public void When_doing_a_crm_linq_query_with_an_intersect_entity_and_2_levels_of_joins_and_where_clauses_right_result_is_returned() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var parentRole = new Role() { Id = Guid.NewGuid(), Name = "System Administrator" }; var role = new Role() { Id = Guid.NewGuid(), Name = "Sys Admin" }; var user = new SystemUser() { Id = Guid.NewGuid(), FirstName = "Jordi" }; var systemRole = new SystemUserRoles() { Id = Guid.NewGuid() }; role["parentroleid"] = parentRole.ToEntityReference(); systemRole["systemuserid"] = user.ToEntityReference(); systemRole["roleid"] = role.ToEntityReference(); fakedContext.Initialize(new List<Entity>() { user, systemRole, role, parentRole }); var service = fakedContext.GetFakedOrganizationService(); using (XrmServiceContext ctx = new XrmServiceContext(service)) { var matches = (from sr in ctx.CreateQuery<SystemUserRoles>() join r in ctx.CreateQuery<Role>() on sr.RoleId equals r.RoleId join u in ctx.CreateQuery<SystemUser>() on sr.SystemUserId equals u.SystemUserId where u.FirstName == "Jordi" where r.Name == "Sys Admin" select sr).ToList(); Assert.True(matches.Count == 1); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// it creates a system user account with a given active directory account. /// Note: Creating a user is only supported in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetCreateAUser1> // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = _serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = _domain + _userName, FirstName = _firstName, LastName = _lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = _serviceProxy.Create(user); Console.WriteLine("Created a system user {0} for '{1}, {2}'", userId, _lastName, _firstName); } //</snippetCreateAUser1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void LoadSystemUser() { try { oSystemUser = (SystemUser)Utils.GetSession(SessionManager.csLoggedUser); } catch (Exception oEx) { } }
public void When_querying_the_same_entity_records_with_joins_no_collection_modified_exception_is_thrown() { var fakedContext = new XrmFakedContext { }; var service = fakedContext.GetFakedOrganizationService(); var entityAccount = new Account { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!", LogicalName = "account" }; var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference() }; var entityBusinessUnit = new BusinessUnit { Name = "TestBU", BusinessUnitId = Guid.NewGuid() }; var initiatingUser = new SystemUser { Id = Guid.NewGuid(), FirstName = "TestUser", DomainName = "TestDomain", BusinessUnitId = entityBusinessUnit.ToEntityReference() }; fakedContext.Initialize(new List<Entity>() { entityBusinessUnit,entityAccount,entityContact,initiatingUser }); var fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='systemuser'> <attribute name='fullname' /> <attribute name='systemuserid' /> <attribute name='businessunitid' /> <filter type='and'> <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='#userId#' /> </filter> <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='bu' intersect='true' > <attribute name='name' /> </link-entity> </entity> </fetch> "; var UserRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.Replace("#userId#", initiatingUser.Id.ToString())) }; var response = ((RetrieveMultipleResponse)service.Execute(UserRequest)); var entities = response.EntityCollection.Entities; Assert.True(entities.Count == 1); Assert.True(entities[0].Attributes.ContainsKey("bu.name")); Assert.IsType<AliasedValue>(entities[0]["bu.name"]); Assert.Equal("TestBU", (entities[0]["bu.name"] as AliasedValue).Value.ToString()); }
private static async Task <SystemUser> CreateUserWithRole(RecruitmentSystemContext context, UserManager <SystemUser> userManager, SystemUser user, string role) { if (!context.Users.Any(u => u.UserName == user.UserName)) { var result = await userManager.CreateAsync(user, "P@ssw0rd"); if (result.Succeeded) { var systemUser = await userManager.FindByEmailAsync(user.Email); result = await userManager.AddToRoleAsync(systemUser, role); return(systemUser); } } return(null); }
public bool Update(SystemUser o) //更新用户权限 { return(u.Update(o)); }
public static void Should_Only_Find_Correct_Faked_N_To_N_Records() { var fakedContext = new XrmFakedContext(); var fakedService = fakedContext.GetFakedOrganizationService(); var userId = new Guid("11111111-7982-4276-A8FE-7CE05FABEAB4"); var businessId = Guid.NewGuid(); var testUser = new SystemUser { Id = userId }; var testRole = new Role { Id = new Guid("22222222-7982-4276-A8FE-7CE05FABEAB4"), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; var testUser2 = new SystemUser { Id = Guid.NewGuid() }; var testRole2 = new Role { Id = Guid.NewGuid(), Name = "Test Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId) }; fakedContext.Initialize(new Entity[] { testUser, testRole, testUser2, testRole2 }); fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship { IntersectEntity = "systemuserroles", Entity1LogicalName = SystemUser.EntityLogicalName, Entity1Attribute = "systemuserid", Entity2LogicalName = Role.EntityLogicalName, Entity2Attribute = "roleid" }); var request = new AssociateRequest() { Target = testUser.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request); var request2 = new AssociateRequest() { Target = testUser2.ToEntityReference(), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, testRole2.Id), }, Relationship = new Relationship("systemuserroles_association") }; fakedService.Execute(request2); var query = new QueryExpression() { EntityName = "role", ColumnSet = new ColumnSet("name"), LinkEntities = { new LinkEntity { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "systemuserid", Operator = ConditionOperator.Equal, Values = { userId} } } } } } }; var result = fakedService.RetrieveMultiple(query); Assert.NotEmpty(result.Entities); Assert.Equal(1, result.Entities.Count); }
/// <summary> /// The Run() method first connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </summary> /// <param name="connectionString">Provides service connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(String connectionString, bool promptforDelete) { try { // Connect to the CRM web service using a connection string. CrmServiceClient conn = new Xrm.Tooling.Connector.CrmServiceClient(connectionString); // Cast the proxy client to the IOrganizationService interface. _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; //Create any entity records this sample requires. CreateRequiredRecords(); // Obtain information about the logged on user from the web service. Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" })); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)_orgService.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs. // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must // be set for each entity. Account account = new Account { Name = "SiroccoTest2 VB" }; account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer); account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor); // Create an account record named Fourth Coffee. _accountId = _orgService.Create(account); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); // Retrieve the several attributes from the new account. ColumnSet cols = new ColumnSet( new String[] { "name", "address1_postalcode", "lastusedincampaign" }); Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. _orgService.Update(retrievedAccount); Console.WriteLine("and updated."); // Delete any entity records this sample created. DeleteRequiredRecords(promptforDelete); } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
public SystemUser GetUser(string logonName) { SystemUser user = new SystemUser(); if (String.IsNullOrEmpty(logonName)) return user; SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = " + System.Web.HttpContext.Current.Server.MapPath(privilegesDatabase)); conn.Open(); SqlCommand cmd = new SqlCommand("Select * from Users WHERE logonName=@logonNameParam", conn); cmd.Parameters.Add("@logonNameParam", SqlDbType.VarChar, 35); cmd.Parameters["@logonNameParam"].Value = logonName; var reader = cmd.ExecuteReader(); // write each record while (reader.Read()) { string readerRole = reader["userRole"].ToString(); UserRole role = readerRole == "Admin" ? UserRole.Admin : (readerRole == "Viewer" ? UserRole.Viewer : UserRole.Donor); int age = 0, persInfoConsent = 0, eMailConsent, phoneConsent; Int32.TryParse(reader["age"].ToString(), out age); Int32.TryParse(reader["persInfoConsent"].ToString(), out persInfoConsent); Int32.TryParse(reader["eMailConsent"].ToString(), out eMailConsent); Int32.TryParse(reader["phoneConsent"].ToString(), out phoneConsent); string nationalIdentity = reader["nationalIdentity"] != null ? reader["nationalIdentity"].ToString() : String.Empty; string logonNameInput = reader["logonName"] != null ? reader["logonName"].ToString() : String.Empty; string passwordImput = reader["password"] != null ? reader["password"].ToString() : String.Empty; string firstNameInput = reader["firstName"] != null ? reader["firstName"].ToString() : String.Empty; string lastNameInput = reader["lastName"] != null ? reader["lastName"].ToString() : String.Empty; string phoneMobileInput = reader["phoneMobile"] != null ? reader["phoneMobile"].ToString() : String.Empty; string addressInput = reader["address"] != null ? reader["address"].ToString() : String.Empty; string gender = reader["gender"] != null ? reader["gender"].ToString() : String.Empty; string phoneWork = reader["phoneWork"] != null ? reader["phoneWork"].ToString() : String.Empty; string phonePrivate = reader["phonePrivate"] != null ? reader["phonePrivate"].ToString() : String.Empty; string eMail = reader["eMail"] != null ? reader["eMail"].ToString() : String.Empty; user = new SystemUser(logonNameInput, passwordImput, role, firstNameInput, lastNameInput, phoneMobileInput, age, addressInput, persInfoConsent != 0, nationalIdentity, eMailConsent != 0, phoneConsent != 0, gender, phoneWork, phonePrivate, eMail); } cmd.Dispose(); reader.Close(); conn.Dispose(); return user; }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// creates/retrieve a system user, /// retrieve a system user to check if it is associate with the salesperson role. /// Note: Creating a user is only supported /// in on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetDoesUserBelongToRole1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve a user. SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String [] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>(); if (user != null) { Console.WriteLine("{1} {0} user account is retrieved.", user.LastName, user.FirstName); // Find a role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection givenRoles = _serviceProxy.RetrieveMultiple(query); if (givenRoles.Entities.Count > 0) { Role givenRole = givenRoles.Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved.", _givenRole); Console.WriteLine("Checking association between user and role."); // Establish a SystemUser link for a query. LinkEntity systemUserLink = new LinkEntity() { LinkFromEntityName = SystemUserRoles.EntityLogicalName, LinkFromAttributeName = "systemuserid", LinkToEntityName = SystemUser.EntityLogicalName, LinkToAttributeName = "systemuserid", LinkCriteria = { Conditions = { new ConditionExpression( "systemuserid", ConditionOperator.Equal, user.Id) } } }; // Build the query. QueryExpression linkQuery = new QueryExpression() { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), LinkEntities = { new LinkEntity() { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkEntities = { systemUserLink } } }, Criteria = { Conditions = { new ConditionExpression("roleid", ConditionOperator.Equal, givenRole.Id) } } }; // Retrieve matching roles. EntityCollection matchEntities = _serviceProxy.RetrieveMultiple(linkQuery); // if an entity is returned then the user is a member // of the role Boolean isUserInRole = (matchEntities.Entities.Count > 0); if (isUserInRole) { Console.WriteLine("User do not belong to the role."); } else { Console.WriteLine("User belong to this role."); } } } } //</snippetDoesUserBelongToRole1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
public SystemUser GetSystemUserById(long userId) { SystemUser user = new SystemUser(); try { user = Database.SystemUsers.Single(u => u.IID == userId); } catch (Exception ex) { } return user; }
/// <summary> /// This method first connects to the Organization service. Afterwards, it /// creates/retrieves a system user, and /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve a user. SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>(); if (user != null) { Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName); // Find the role. QueryExpression query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); // Disassociate the role. if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved.", _givenRole); _serviceProxy.Disassociate( "systemuser", user.Id, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("role", salesRole.Id) }); Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName); } } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
protected void Page_Load(object sender, EventArgs e) { System.Security.Principal.GenericPrincipal myUser = (System.Security.Principal.GenericPrincipal)HttpContext.Current.Cache.Get("customPrincipal"); if (myUser != null) HttpContext.Current.User = myUser; if ((HttpContext.Current.User != null) && HttpContext.Current.User.Identity.IsAuthenticated) { this.CurrentUser = HttpContext.Current.User.Identity.Name; SystemUser usr = AuthMod.GetUser(CurrentUser); lblHeading.InnerText = "Egenerklæring for " + usr.FirstName != null ? usr.FirstName + " " + usr.LastName : CurrentUser; CurrentUserObject = AuthMod.GetUser(CurrentUser); if (CurrentUserObject.Gender.ToLower() == "female") { radios51a.Disabled = true; radios51b.Disabled = true; } else if(CurrentUserObject.Gender.ToLower() == "male") { radios47a.Disabled = true; radios47b.Disabled = true; radios48a.Disabled = true; radios48b.Disabled = true; radios49a.Disabled = true; radios49b.Disabled = true; radios50a.Disabled = true; radios50b.Disabled = true; } if (!IsPostBack) { List<Schema> userSchemas = FormMod.GetUserSchemaForm(CurrentUser); Schema newestSchema = null; try { newestSchema = userSchemas.Aggregate((i1, i2) => i1.schemaID > i2.schemaID ? i1 : i2); } catch { //We de nothing if this fails } if(newestSchema != null) { radios1a.Checked = newestSchema != null && newestSchema.spm1 == 0 ? false : true; radios2a.Checked = newestSchema != null && newestSchema.spm2 == 0 ? false : true; radios3a.Checked = newestSchema != null && newestSchema.spm3 == 0 ? false : true; radios4a.Checked = newestSchema != null && newestSchema.spm4 == 0 ? false : true; radios5a.Checked = newestSchema != null && newestSchema.spm5 == 0 ? false : true; radios6a.Checked = newestSchema != null && newestSchema.spm6 == 0 ? false : true; radios7a.Checked = newestSchema != null && newestSchema.spm7 == 0 ? false : true; radios8a.Checked = newestSchema != null && newestSchema.spm8 == 0 ? false : true; radios9a.Checked = newestSchema != null && newestSchema.spm9 == 0 ? false : true; radios10a.Checked = newestSchema != null && newestSchema.spm10 == 0 ? false : true; radios11a.Checked = newestSchema != null && newestSchema.spm11 == 0 ? false : true; radios12a.Checked = newestSchema != null && newestSchema.spm12 == 0 ? false : true; radios13a.Checked = newestSchema != null && newestSchema.spm13 == 0 ? false : true; radios14a.Checked = newestSchema != null && newestSchema.spm14 == 0 ? false : true; radios15a.Checked = newestSchema != null && newestSchema.spm15 == 0 ? false : true; radios16a.Checked = newestSchema != null && newestSchema.spm16 == 0 ? false : true; radios17a.Checked = newestSchema != null && newestSchema.spm17 == 0 ? false : true; radios18a.Checked = newestSchema != null && newestSchema.spm18 == 0 ? false : true; radios19a.Checked = newestSchema != null && newestSchema.spm19 == 0 ? false : true; radios20a.Checked = newestSchema != null && newestSchema.spm20 == 0 ? false : true; radios21a.Checked = newestSchema != null && newestSchema.spm21 == 0 ? false : true; radios22a.Checked = newestSchema != null && newestSchema.spm22 == 0 ? false : true; radios23a.Checked = newestSchema != null && newestSchema.spm23 == 0 ? false : true; radios24a.Checked = newestSchema != null && newestSchema.spm24 == 0 ? false : true; radios25a.Checked = newestSchema != null && newestSchema.spm25 == 0 ? false : true; radios26a.Checked = newestSchema != null && newestSchema.spm26 == 0 ? false : true; radios27a.Checked = newestSchema != null && newestSchema.spm27 == 0 ? false : true; radios28a.Checked = newestSchema != null && newestSchema.spm28 == 0 ? false : true; radios29a.Checked = newestSchema != null && newestSchema.spm29 == 0 ? false : true; radios30a.Checked = newestSchema != null && newestSchema.spm30 == 0 ? false : true; radios31a.Checked = newestSchema != null && newestSchema.spm31 == 0 ? false : true; radios32a.Checked = newestSchema != null && newestSchema.spm32 == 0 ? false : true; radios33a.Checked = newestSchema != null && newestSchema.spm33 == 0 ? false : true; radios34a.Checked = newestSchema != null && newestSchema.spm34 == 0 ? false : true; radios35a.Checked = newestSchema != null && newestSchema.spm35 == 0 ? false : true; radios36a.Checked = newestSchema != null && newestSchema.spm36 == 0 ? false : true; radios37a.Checked = newestSchema != null && newestSchema.spm37 == 0 ? false : true; radios38a.Checked = newestSchema != null && newestSchema.spm38 == 0 ? false : true; radios39a.Checked = newestSchema != null && newestSchema.spm39 == 0 ? false : true; radios40a.Checked = newestSchema != null && newestSchema.spm40 == 0 ? false : true; radios41a.Checked = newestSchema != null && newestSchema.spm41 == 0 ? false : true; radios42a.Checked = newestSchema != null && newestSchema.spm42 == 0 ? false : true; radios43a.Checked = newestSchema != null && newestSchema.spm43 == 0 ? false : true; radios44a.Checked = newestSchema != null && newestSchema.spm44 == 0 ? false : true; radios45a.Checked = newestSchema != null && newestSchema.spm45 == 0 ? false : true; radios46a.Checked = newestSchema != null && newestSchema.spm46 == 0 ? false : true; radios47a.Checked = newestSchema != null && newestSchema.spm47 == 0 ? false : true; radios48a.Checked = newestSchema != null && newestSchema.spm48 == 0 ? false : true; radios49a.Checked = newestSchema != null && newestSchema.spm49 == 0 ? false : true; radios50a.Checked = newestSchema != null && newestSchema.spm50 == 0 ? false : true; radios51a.Checked = newestSchema != null && newestSchema.spm51 == 0 ? false : true; radios52a.Checked = newestSchema != null && newestSchema.spm52 == 0 ? false : true; radios53a.Checked = newestSchema != null && newestSchema.spm53 == 0 ? false : true; radios54a.Checked = newestSchema != null && newestSchema.spm54 == 0 ? false : true; radios55a.Checked = newestSchema != null && newestSchema.spm55 == 0 ? false : true; radios56a.Checked = newestSchema != null && newestSchema.spm56 == 0 ? false : true; radios57a.Checked = newestSchema != null && newestSchema.spm57 == 0 ? false : true; radios58a.Checked = newestSchema != null && newestSchema.spm58 == 0 ? false : true; radios59a.Checked = newestSchema != null && newestSchema.spm59 == 0 ? false : true; radios60a.Checked = newestSchema != null && newestSchema.spm60 == 0 ? false : true; radios1b.Checked = newestSchema != null && newestSchema.spm1 == 0 ? true : false; radios2b.Checked = newestSchema != null && newestSchema.spm2 == 0 ? true : false; radios3b.Checked = newestSchema != null && newestSchema.spm3 == 0 ? true : false; radios4b.Checked = newestSchema != null && newestSchema.spm4 == 0 ? true : false; radios5b.Checked = newestSchema != null && newestSchema.spm5 == 0 ? true : false; radios6b.Checked = newestSchema != null && newestSchema.spm6 == 0 ? true : false; radios7b.Checked = newestSchema != null && newestSchema.spm7 == 0 ? true : false; radios8b.Checked = newestSchema != null && newestSchema.spm8 == 0 ? true : false; radios9b.Checked = newestSchema != null && newestSchema.spm9 == 0 ? true : false; radios10b.Checked = newestSchema != null && newestSchema.spm10 == 0 ? true : false; radios11b.Checked = newestSchema != null && newestSchema.spm11 == 0 ? true : false; radios12b.Checked = newestSchema != null && newestSchema.spm12 == 0 ? true : false; radios13b.Checked = newestSchema != null && newestSchema.spm13 == 0 ? true : false; radios14b.Checked = newestSchema != null && newestSchema.spm14 == 0 ? true : false; radios15b.Checked = newestSchema != null && newestSchema.spm15 == 0 ? true : false; radios16b.Checked = newestSchema != null && newestSchema.spm16 == 0 ? true : false; radios17b.Checked = newestSchema != null && newestSchema.spm17 == 0 ? true : false; radios18b.Checked = newestSchema != null && newestSchema.spm18 == 0 ? true : false; radios19b.Checked = newestSchema != null && newestSchema.spm19 == 0 ? true : false; radios20b.Checked = newestSchema != null && newestSchema.spm20 == 0 ? true : false; radios21b.Checked = newestSchema != null && newestSchema.spm21 == 0 ? true : false; radios22b.Checked = newestSchema != null && newestSchema.spm22 == 0 ? true : false; radios23b.Checked = newestSchema != null && newestSchema.spm23 == 0 ? true : false; radios24b.Checked = newestSchema != null && newestSchema.spm24 == 0 ? true : false; radios25b.Checked = newestSchema != null && newestSchema.spm25 == 0 ? true : false; radios26b.Checked = newestSchema != null && newestSchema.spm26 == 0 ? true : false; radios27b.Checked = newestSchema != null && newestSchema.spm27 == 0 ? true : false; radios28b.Checked = newestSchema != null && newestSchema.spm28 == 0 ? true : false; radios29b.Checked = newestSchema != null && newestSchema.spm29 == 0 ? true : false; radios30b.Checked = newestSchema != null && newestSchema.spm30 == 0 ? true : false; radios31b.Checked = newestSchema != null && newestSchema.spm31 == 0 ? true : false; radios32b.Checked = newestSchema != null && newestSchema.spm32 == 0 ? true : false; radios33b.Checked = newestSchema != null && newestSchema.spm33 == 0 ? true : false; radios34b.Checked = newestSchema != null && newestSchema.spm34 == 0 ? true : false; radios35b.Checked = newestSchema != null && newestSchema.spm35 == 0 ? true : false; radios36b.Checked = newestSchema != null && newestSchema.spm36 == 0 ? true : false; radios37b.Checked = newestSchema != null && newestSchema.spm37 == 0 ? true : false; radios38b.Checked = newestSchema != null && newestSchema.spm38 == 0 ? true : false; radios39b.Checked = newestSchema != null && newestSchema.spm39 == 0 ? true : false; radios40b.Checked = newestSchema != null && newestSchema.spm40 == 0 ? true : false; radios41b.Checked = newestSchema != null && newestSchema.spm41 == 0 ? true : false; radios42b.Checked = newestSchema != null && newestSchema.spm42 == 0 ? true : false; radios43b.Checked = newestSchema != null && newestSchema.spm43 == 0 ? true : false; radios44b.Checked = newestSchema != null && newestSchema.spm44 == 0 ? true : false; radios45b.Checked = newestSchema != null && newestSchema.spm45 == 0 ? true : false; radios46b.Checked = newestSchema != null && newestSchema.spm46 == 0 ? true : false; radios47b.Checked = newestSchema != null && newestSchema.spm47 == 0 ? true : false; radios48b.Checked = newestSchema != null && newestSchema.spm48 == 0 ? true : false; radios49b.Checked = newestSchema != null && newestSchema.spm49 == 0 ? true : false; radios50b.Checked = newestSchema != null && newestSchema.spm50 == 0 ? true : false; radios51b.Checked = newestSchema != null && newestSchema.spm51 == 0 ? true : false; radios52b.Checked = newestSchema != null && newestSchema.spm52 == 0 ? true : false; radios53b.Checked = newestSchema != null && newestSchema.spm53 == 0 ? true : false; radios54b.Checked = newestSchema != null && newestSchema.spm54 == 0 ? true : false; radios55b.Checked = newestSchema != null && newestSchema.spm55 == 0 ? true : false; radios56b.Checked = newestSchema != null && newestSchema.spm56 == 0 ? true : false; radios57b.Checked = newestSchema != null && newestSchema.spm57 == 0 ? true : false; radios58b.Checked = newestSchema != null && newestSchema.spm58 == 0 ? true : false; radios59b.Checked = newestSchema != null && newestSchema.spm59 == 0 ? true : false; radios60b.Checked = newestSchema != null && newestSchema.spm60 == 0 ? true : false; } } } BottomNavBar.PrevLink = "/WorkflowItems/PersInfoPage.aspx"; BottomNavBar.NextLink = "/WorkflowItems/BookMedicalExamination.aspx"; }
public void InsertUser(SystemUser user) { user.Pword = SetHashText(user.Pword); // set new user password _userDAL.InsertUser(user); }
public static SystemUser GetAuthenticatedUser(string token) { SystemUser user = null; return(LoggedUsersDic.TryGetValue(token, out user) ? user : null); }
/// <summary> /// 1= Success, 0= Failed, 4= User not Found /// </summary> /// <param name="model"></param> /// <returns></returns> public APIReturnModel SaveUserSettings(UserSettingsModel model) { try { UserSetting usersettings = new UserSetting(); bool isupdate = false; //Check user id is provided if (!string.IsNullOrEmpty(model.Id)) { //Check user id exists in db SystemUser chkexisting = Db.SystemUsers.FirstOrDefault(d => d.Id == model.Id && !d.IsArchived); if (chkexisting != null) { usersettings = Db.UserSettings.FirstOrDefault(d => d.Id == model.Id); if (usersettings == null) { usersettings = new UserSetting { Id = model.Id }; } else { isupdate = true; } usersettings.EmailNewNotification = model.EmailNewNotification; usersettings.EmailNotification = model.EmailNotification; usersettings.NotificationMuteNewAccount = model.NotificationMuteNewAccount; usersettings.NotificationMuteWhoDontFollow = model.NotificationMuteWhoDontFollow; usersettings.NotificationMuteYouDontFollow = model.NotificationMuteYouDontFollow; usersettings.PrivacyPhotoTagging = model.PrivacyPhotoTagging; usersettings.PrivacyTweetLocation = model.PrivacyTweetLocation; usersettings.PrivacyTweetPrivacy = model.PrivacyTweetPrivacy; usersettings.IsArchived = false; if (!isupdate) { Db.UserSettings.Add(usersettings); } Db.SaveChanges(); return(new APIReturnModel { Status = 1, Value = usersettings.Id }); } else { return new APIReturnModel { Status = 4 } }; } else { return new APIReturnModel { Status = 4 } }; } catch { return(new APIReturnModel { Status = 0 }); } }