Beispiel #1
0
 private RoleInfo SetInfo()
 {
     RoleInfo info = new RoleInfo();
     info.RoleName = this.TXT_ROLENAME.Text.Trim();
     info.Remark = this.TXT_REMARK.Text.Trim();
     return info;
 }
Beispiel #2
0
        public static void CreateOrUpdate(RoleInfo model)
        {
            if (model.Id < 0)
            {
                if (SimpleOrmOperator.Create(model))
                {
                    LogInfoOperator.LogSystem("添加角色", "添加角色" + model.RoleName);
                    WebTools.Alert("添加成功!");
                }
                else
                {
                    WebTools.Alert("添加失败!");

                }
            }
            else
            {
                if (SimpleOrmOperator.Update(model))
                {
                    LogInfoOperator.LogSystem("修改角色", "修改角色" + model.RoleName);
                    WebTools.Alert("修改成功!");
                }
                else
                {
                    WebTools.Alert("修改失败!");

                }

            }
        }
Beispiel #3
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="mod">RoleInfo</param>
        /// <returns>受影响行数</returns>
        public int Update(RoleInfo mod)
        {
           using (DbConnection conn = db.CreateConnection())
			{
				conn.Open();
				using (DbTransaction tran = conn.BeginTransaction())
				{ 
					try
					{ 
						using (DbCommand cmd = db.GetStoredProcCommand("SP_Role_Update"))
						{
							db.AddInParameter(cmd, "@RoleID", DbType.Int32, mod.RoleID); 
							db.AddInParameter(cmd, "@RoleName", DbType.String, mod.RoleName); 
							db.AddInParameter(cmd, "@State", DbType.Int32, mod.State); 
							db.AddInParameter(cmd, "@IsDeleted", DbType.Int32, mod.IsDeleted); 
							db.AddInParameter(cmd, "@Sort", DbType.Int32, mod.Sort); 
							tran.Commit();
							return db.ExecuteNonQuery(cmd);
						} 
					}
					catch (Exception e)
					{
						tran.Rollback();
						throw e;
					}
					finally
					{
						conn.Close();
					}
				}
			}
        }  
        public void InitTest()
        {
            // Arrange.
            var role = new RoleInfo(1, "Role 1");
            var businessUnit = new BusinessUnitInfo(2, "BU 2");
            var config1 = new ProcessReportSecurityConfigurationEdit { RoleId = 1, BusinessUnitId = 2 };
            var config2 = new ProcessReportSecurityConfigurationEdit { RoleId = Constants.AllRolesId, BusinessUnitId = Constants.AllBusinessUnitsId };
            var config3 = new ProcessReportSecurityConfigurationEdit { RoleId = 10, BusinessUnitId = 10 };

            var organizationInfo = Mock.Create<IOrganizationInfo>();
            Mock.Arrange(() => organizationInfo.BusinessUnits).Returns(new List<IBusinessUnitInfo> {businessUnit});
            Mock.Arrange(() => organizationInfo.Roles).Returns(new List<IRoleInfo> {role});

            var vm1 = new ReportSecurityConfigurationViewModel { OrganizationInfo = organizationInfo };
            var vm2 = new ReportSecurityConfigurationViewModel { OrganizationInfo = organizationInfo };
            var vm3 = new ReportSecurityConfigurationViewModel { OrganizationInfo = organizationInfo };

            // Act.
            vm1.Init(config1);
            vm2.Init(config2);
            vm3.Init(config3);

            // Assert.
            Assert.AreSame(config1, vm1.Model);
            Assert.AreEqual("Role 1", vm1.RoleName);
            Assert.AreEqual("BU 2", vm1.BusinessUnitName);
            
            Assert.AreSame(config2, vm2.Model);
            Assert.AreEqual(Constants.AllRolesName, vm2.RoleName);
            Assert.AreEqual(Constants.AllBusinessUnitsName, vm2.BusinessUnitName);

            Assert.AreSame(config3, vm3.Model);
            Assert.AreEqual(Constants.Unknown, vm3.RoleName);
            Assert.AreEqual(Constants.Unknown, vm3.BusinessUnitName);
        }
Beispiel #5
0
 private RoleInfo SetInfo()
 {
     RoleInfo info = new RoleInfo();
     info.RoleName = this.TXT_ROLENAME.Text.Trim();
     info.Remark = this.TXT_REMARK.Text.Trim();
     info.RoleId = int.Parse(ViewState["ROLEID"].ToString());
     return info;
 }
 private void SerializeInternal(RoleInfo model, IDictionary<string, object> result)
 { 
     result.Add("roleid", model.RoleID);
     result.Add("rolename", model.RoleName);
     result.Add("state", model.State);
     result.Add("isdeleted", model.IsDeleted);
     result.Add("sort", model.Sort);
 }
Beispiel #7
0
 protected void btnSure_Click(object sender, EventArgs e)
 {
     RoleInfo model = new RoleInfo();
     WebFormHelper.GetDataFromForm(this, model);
     model.MenuStr = this.GetMenuString();
     RoleInfoOperator.CreateOrUpdate(model);
     WebTools.CloseSelf(this);
 }
Beispiel #8
0
        private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType)
        {
            var eventLogController = new EventLogController();
            eventLogController.AddLog(roleInfo,
                                PortalController.GetCurrentPortalSettings(),
                                UserController.GetCurrentUserInfo().UserID,
                                "",
                                logType);

        }
Beispiel #9
0
 public static void SaveRole(HttpContext context)
 {
     var role = new RoleInfo
     {
         Id = context.Request.Get<string>("Id"),
         Name = context.Request.Get<string>("Name"),
         Description = context.Request.Get<string>("Description")
     };
     var result = AppContext.LoadService<IRoleService>().Save(role);
     context.Response.WriteJson(result);
 }
 public int AddRole(RoleInfo objRoleInfo)
 {
     int roleId = -1;
     bool success = provider.CreateRole(objRoleInfo.PortalID, ref objRoleInfo);
     if (success)
     {
         Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
         objEventLog.AddLog(objRoleInfo, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Services.Log.EventLog.EventLogController.EventLogType.ROLE_CREATED);
         AutoAssignUsers(objRoleInfo);
         roleId = objRoleInfo.RoleID;
     }
     return roleId;
 }
Beispiel #11
0
        public static void AreEqualServiceConfiguration(ServiceConfiguration actual, string serviceName, RoleInfo[] roles = null)
        {
            Assert.AreEqual<string>(actual.serviceName, serviceName);

            if (roles != null)
            {
                Assert.AreEqual<int>(actual.Role.Length, roles.Length);
                int length = roles.Length;

                for (int i = 0; i < length; i++)
                {
                    Assert.IsTrue(roles[i].Equals(actual.Role[i]));
                }
            }
        }
 private void AutoAssignUsers(RoleInfo objRoleInfo)
 {
     if (objRoleInfo.AutoAssignment)
     {
         ArrayList arrUsers = UserController.GetUsers(objRoleInfo.PortalID);
         foreach (UserInfo objUser in arrUsers)
         {
             try
             {
                 AddUserRole(objRoleInfo.PortalID, objUser.UserID, objRoleInfo.RoleID, Null.NullDate, Null.NullDate);
             }
             catch (Exception ex)
             {
                 ex.ToString();
             }
         }
     }
 }
Beispiel #13
0
        /// <summary>
        /// 转换datatable为silverlight可以使用的List<RoleInfo>   
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<RoleInfo> GetRoleDataForSl(DataTable dt)
        {
            var result = new List<RoleInfo>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    var roleInfo = new RoleInfo();
                    roleInfo.RoleName = row["RoleName"].ToString();
                    roleInfo.RoleCode = row["RoleCode"].ToString();
                    roleInfo.RoleDescription = row["RoleDesc"].ToString();
                    roleInfo.RoleIsChecked = Convert.ToBoolean(row["IsChecked"]);

                    result.Add(roleInfo);
                }
            }
            return result;
        }
Beispiel #14
0
 public ValidateResult Save(RoleInfo role)
 {
     var command = DbHelper.Default.CreateCommand();
     command.Text = "select count(*) from T_Roles where Id=?Id";
     command.Parameters.Add("Id", role.Id);
     if (command.ToScalar<int>() > 0)
     {
         command.Text = "update T_Roles set Name=?Name,Description=?Description where Id=?Id";
         command.Parameters.Add("Id", role.Id);
     }
     else
     {
         command.Text = "insert into T_Roles(Id,Name,Description) values(?Id,?Name,?Description)";
         command.Parameters.Add("Id", DbHelper.NewId);
     }
     command.Parameters.Add("Name", role.Name);
     command.Parameters.Add("Description", role.Description);
     var message = command.Execute();
     return new ValidateResult(message);
 }
Beispiel #15
0
 private void AutoAssignUsers(RoleInfo role)
 {
     if (role.AutoAssignment)
     {
         //loop through users for portal and add to role
         var arrUsers = UserController.GetUsers(role.PortalID);
         foreach (UserInfo objUser in arrUsers)
         {
             try
             {
                 var legacyRoleController = new RoleController();
                 legacyRoleController.AddUserRole(role.PortalID, objUser.UserID, role.RoleID, Null.NullDate, Null.NullDate);
             }
             catch (Exception exc)
             {
                 //user already belongs to role
                 DnnLog.Error(exc);
             }
         }
     }
 }
        protected override void OnProcessing(RoleInfo roleInfo)
        {
            var interpPath = FindPythonInterpreterPath();
            if (interpPath != null)
            {
                string stdOut, stdErr;

                string originalDir = Directory.GetCurrentDirectory();
                Directory.SetCurrentDirectory(Path.Combine(RootPath, roleInfo.Name));

                try
                {
                    ProcessHelper.StartAndWaitForProcess(
                    new ProcessStartInfo(
                        Path.Combine(interpPath, PythonInterpreterExe),
                        string.Format(DjangoStartProjectCommand, roleInfo.Name)
                    ),
                    out stdOut,
                    out stdErr);
                }
                finally
                {
                    Directory.SetCurrentDirectory(originalDir);
                }

                if (!string.IsNullOrEmpty(stdErr))
                {
                    WriteWarning(string.Format(Resources.UnableToCreateDjangoApp, stdErr));
                    WriteWarning(Resources.UnableToCreateDjangoAppFix);
                }
            }
            else
            {
                WriteWarning(Resources.MissingPythonPreReq);
            }
        }
Beispiel #17
0
        private void LoadPower(XmlNode powerNode, RoleInfo role, RoleInfo.PowerType powerType)
        {
            RoleInfo.PowerInfo power = new RoleInfo.PowerInfo();

            string typeString = powerNode.Attributes["type"].Value;

            // Arguments
            foreach(XmlNode arg in powerNode.ChildNodes) {
                power.Args.Add(arg.Name, arg.InnerText);
            }

            power.PowerType = Type.GetType(typeString);
            if (power.PowerType == null) {
                Log.Warn("Invalid power type defined for role " + role.Name);
                return;
            }
            power.Type = powerType;

            if(powerNode.Attributes["duration"] != null) {
                power.Duration = Int32.Parse(powerNode.Attributes["duration"].Value);
            }
            if (powerNode.Attributes["charges"] != null) {
                power.Duration = Int32.Parse(powerNode.Attributes["charges"].Value);
            }

            role.Powers.Add(power);
        }
Beispiel #18
0
 public int AddRole(RoleInfo role, bool addToExistUsers)
 {
     return(RoleController.Instance.AddRole(role, addToExistUsers));
 }
Beispiel #19
0
 public void UpdateRole(RoleInfo role)
 {
     RoleController.Instance.UpdateRole(role);
 }
Beispiel #20
0
 public void UpdateRoleSettings(RoleInfo role, bool clearCache)
 {
     RoleController.Instance.UpdateRoleSettings(role, clearCache);
 }
Beispiel #21
0
        public bool GetRoleInfo(Guid transactionid, AdminInfo admin, Guid roleID, out string strJsonResult)
        {
            bool result = true;

            strJsonResult = string.Empty;
            string        message  = string.Empty;
            ErrorCodeInfo error    = new ErrorCodeInfo();
            string        paramstr = string.Empty;

            paramstr += "useraccount:" + admin.UserAccount;
            paramstr += "||UserID:" + admin.UserID;
            paramstr += "||RoleID:" + roleID;
            string funname = "GetRoleInfo";

            try
            {
                do
                {
                    RoleInfo       info     = new RoleInfo();
                    RoleDBProvider Provider = new RoleDBProvider();
                    if (!Provider.GetRoleInfo(transactionid, admin, roleID, out info, out error))
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }
                    if (info.UserList.Count > 0)
                    {
                        DirectoryEntry entry          = new DirectoryEntry();
                        CommonProvider commonProvider = new CommonProvider();
                        for (int i = 0; i < info.UserList.Count; i++)
                        {
                            if (!commonProvider.GetADEntryByGuid(info.UserList[i].UserID, out entry, out message))
                            {
                                LoggerHelper.Error("GetRoleInfo调用GetADEntryByGuid异常", paramstr, message, transactionid);
                                continue;
                            }

                            info.UserList[i].DisplayName = entry.Properties["displayname"].Value == null ? "" : Convert.ToString(entry.Properties["displayname"].Value);
                            info.UserList[i].UserAccount = entry.Properties["userPrincipalName"].Value == null ? "" : Convert.ToString(entry.Properties["userPrincipalName"].Value);
                        }
                    }

                    error.Code = ErrorCode.None;
                    string json = JsonConvert.SerializeObject(info);
                    LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), true, transactionid);
                    strJsonResult = JsonHelper.ReturnJson(true, Convert.ToInt32(error.Code), error.Info, json);
                    result        = true;
                } while (false);
            }
            catch (Exception ex)
            {
                error.Code = ErrorCode.Exception;
                LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                LoggerHelper.Error("RoleManager调用GetRoleInfo异常", paramstr, ex.ToString(), transactionid);
                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                result        = false;
            }
            return(result);
        }
Beispiel #22
0
        public void DeleteRole(RoleInfo role)
        {
            Requires.NotNull("role", role);

            AddMessage(role, EventLogController.EventLogType.ROLE_DELETED);

            if(role.SecurityMode != SecurityMode.SecurityRole)
            {
                //remove group artifacts
                var portalSettings = PortalController.GetCurrentPortalSettings();

                IFileManager _fileManager = FileManager.Instance;
                IFolderManager _folderManager = FolderManager.Instance;

                IFolderInfo groupFolder = _folderManager.GetFolder(portalSettings.PortalId, "Groups/" + role.RoleID);
                if (groupFolder != null)
                {
                    _fileManager.DeleteFiles(_folderManager.GetFiles(groupFolder));
                    _folderManager.DeleteFolder(groupFolder);
                }
                JournalController.Instance.DeleteJournalItemByGroupId(portalSettings.PortalId, role.RoleID);
            }

            provider.DeleteRole(role);

            ClearRoleCache(role.PortalID);
        }
Beispiel #23
0
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// Gets the Enabled status of the permission
 /// </summary>
 /// <param name="objPerm">The permission being loaded</param>
 /// <param name="role">The role</param>
 /// <param name="column">The column of the Grid</param>
 /// <history>
 ///     [cnurse]    01/13/2006  Created
 /// </history>
 /// -----------------------------------------------------------------------------
 protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column)
 {
     return(role.RoleID != AdministratorRoleId);
 }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                bool blnValid = true;
//                string strTransactionID;
                int intRoleID   = 0;
                int intPortalID = PortalSettings.PortalId;
                int intUserID   = 0;
//                string strDescription;
                double dblAmount = 0;
//                string strEmail;
                bool   blnCancel           = false;
                string strPayPalID         = Null.NullString;
                var    objRoles            = new RoleController();
                var    objPortalController = new PortalController();
                string strPost             = "cmd=_notify-validate";
                foreach (string strName in Request.Form)
                {
                    string strValue = Request.Form[strName];
                    switch (strName)
                    {
                    case "txn_type":     //get the transaction type
                        string strTransactionType = strValue;
                        switch (strTransactionType)
                        {
                        case "subscr_signup":
                        case "subscr_payment":
                        case "web_accept":
                            break;

                        case "subscr_cancel":
                            blnCancel = true;
                            break;

                        default:
                            blnValid = false;
                            break;
                        }
                        break;

                    case "payment_status":     //verify the status
                        if (strValue != "Completed")
                        {
                            blnValid = false;
                        }
                        break;

                    case "txn_id":     //verify the transaction id for duplicates
//                            strTransactionID = strValue;
                        break;

                    case "receiver_email":     //verify the PayPalId
                        strPayPalID = strValue;
                        break;

                    case "mc_gross":     // verify the price
                        dblAmount = double.Parse(strValue);
                        break;

                    case "item_number":     //get the RoleID
                        intRoleID = Int32.Parse(strValue);
                        //RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID);
                        break;

                    case "item_name":     //get the product description
//                            strDescription = strValue;
                        break;

                    case "custom":     //get the UserID
                        intUserID = Int32.Parse(strValue);
                        break;

                    case "email":     //get the email
//                            strEmail = strValue;
                        break;
                    }

                    //reconstruct post for postback validation
                    strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue));
                }

                //postback to verify the source
                if (blnValid)
                {
                    Dictionary <string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
                    string strPayPalURL;

                    // Sandbox mode
                    if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"] == "true")
                    {
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
                    else
                    {
                        strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }
                    var objRequest = Globals.GetExternalRequest(strPayPalURL);
                    objRequest.Method        = "POST";
                    objRequest.ContentLength = strPost.Length;
                    objRequest.ContentType   = "application/x-www-form-urlencoded";
                    using (var objStream = new StreamWriter(objRequest.GetRequestStream()))
                    {
                        objStream.Write(strPost);
                    }

                    string strResponse;
                    using (var objResponse = (HttpWebResponse)objRequest.GetResponse())
                    {
                        using (var sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }
                    }
                    switch (strResponse)
                    {
                    case "VERIFIED":
                        break;

                    default:
                        //possible fraud
                        blnValid = false;
                        break;
                    }
                }
                if (blnValid)
                {
                    int        intAdministratorRoleId = 0;
                    string     strProcessorID         = Null.NullString;
                    PortalInfo objPortalInfo          = objPortalController.GetPortal(intPortalID);
                    if (objPortalInfo != null)
                    {
                        intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
                        strProcessorID         = objPortalInfo.ProcessorUserId.ToLower();
                    }

                    if (intRoleID == intAdministratorRoleId)
                    {
                        //admin portal renewal
                        strProcessorID = Host.ProcessorUserId.ToLower();
                        float portalPrice = objPortalInfo.HostFee;
                        if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objPortalController.UpdatePortalExpiry(intPortalID);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                    else
                    {
                        //user subscription
                        RoleInfo objRoleInfo = TestableRoleController.Instance.GetRole(intPortalID, r => r.RoleID == intRoleID);
                        float    rolePrice   = objRoleInfo.ServiceFee;
                        float    trialPrice  = objRoleInfo.TrialFee;
                        if ((rolePrice.ToString() == dblAmount.ToString() || trialPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objRoles.UpdateUserRole(intPortalID, intUserID, intRoleID, blnCancel);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                }
            }
            catch (Exception exc) //Page failed to load
            {
                Exceptions.ProcessPageLoadException(exc);
            }
        }
    void Start()
    {
        roleInfo     = transform.GetComponent <RoleInfo> ();
        roleMain     = transform.GetComponent <Role_Main> ();
        ani          = transform.GetComponent <Animator> ();
        agent        = GetComponent <NavMeshAgent> ();
        uimanager    = GameObject.Find("UI").GetComponent <UIManager> ();
        skillmanager = transform.GetComponent <SkillManager> ();
        roadLine     = roleMain.roadLine;

        aiOfHeroState = AIOfHeroState.patrol;
        isGet         = false;
        if (uimanager.mapSelect == MapSelect.oneVSone)
        {
            if (roleInfo.roleCamp == Role_Camp.Blue)
            {
                targetOfAI.target01 = GameObject.Find("Tower_Red_01").transform;
                targetOfAI.target02 = GameObject.Find("RebirthPos_Blue").transform;
                targetOfAI.target03 = GameObject.Find("shuiJingRedRoot").transform;
            }
            else
            {
                targetOfAI.target01 = GameObject.Find("Tower_Blue_01").transform;
                targetOfAI.target02 = GameObject.Find("RebirthPos_Red").transform;
                targetOfAI.target03 = GameObject.Find("shuiJingBlueRoot").transform;
            }
        }
        else if (uimanager.mapSelect == MapSelect.threeVSthree)
        {
            if (roleInfo.roleCamp == Role_Camp.Blue)
            {
                if (roadLine == 1)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider/Path (3)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/A_Towers/A_Tower_X02").transform;
                }
                else if (roadLine == 2)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider_z/Path_z (2)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/A_Towers/A_Tower_Z02").transform;
                }
                else if (roadLine == 3)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider_s/Path_s (4)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/A_Towers/A_Tower_S02").transform;
                }
                targetOfAI.target02 = GameObject.Find("RebirthPos_Blue").transform;
                targetOfAI.target03 = GameObject.Find("shuiJingRedRoot").transform;
            }
            else
            {
                if (roadLine == 1)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider_s/Path_s (4)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/B_Towers/B_Tower_X02").transform;
                }
                else if (roadLine == 2)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider_z/Path_z (2)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/B_Towers/B_Tower_Z02").transform;
                }
                else if (roadLine == 3)
                {
                    targetOfAI.target_Roadpoint = GameObject.Find("PathSolider/Path (3)").transform;
                    targetOfAI.target01         = GameObject.Find("Environment/Building/B_Towers/B_Tower_S02").transform;
                }
                targetOfAI.target02 = GameObject.Find("RebirthPos_Red").transform;
                targetOfAI.target03 = GameObject.Find("shuiJingBlueRoot").transform;
            }
        }
    }
Beispiel #26
0
            public async Task <ActionResult <int> > AddRole([FromBody] RoleInfo roleinfo)
            {
                string sql = $"insert into RoleInfo values('{roleinfo.RId}','{roleinfo.RName}','{roleinfo.Level}','{roleinfo.Remark}')";

                return(await db.Database.ExecuteSqlCommandAsync(sql));
            }
Beispiel #27
0
        protected override void OnInit(EventArgs e)
        {
            JavaScript.RequestRegistration(CommonJs.DnnPlugins);
            JavaScript.RequestRegistration(CommonJs.jQueryFileUpload);
            ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
            JavaScript.RequestRegistration(CommonJs.Knockout);

            ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/journal.js");
            ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/journalcomments.js");
            ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js");
            ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/json2.js");

            var isAdmin = this.UserInfo.IsInRole(RoleController.Instance.GetRoleById(this.PortalId, this.PortalSettings.AdministratorRoleId).RoleName);

            if (!this.Request.IsAuthenticated || (!this.UserInfo.IsSuperUser && !isAdmin && this.UserInfo.IsInRole("Unverified Users")))
            {
                this.ShowEditor = false;
            }
            else
            {
                this.ShowEditor = this.EditorEnabled;
            }

            if (this.Settings.ContainsKey(Constants.DefaultPageSize))
            {
                this.PageSize = Convert.ToInt16(this.Settings[Constants.DefaultPageSize]);
            }

            if (this.Settings.ContainsKey(Constants.MaxCharacters))
            {
                this.MaxMessageLength = Convert.ToInt16(this.Settings[Constants.MaxCharacters]);
            }

            if (this.Settings.ContainsKey(Constants.AllowPhotos))
            {
                this.AllowPhotos = Convert.ToBoolean(this.Settings[Constants.AllowPhotos]);
            }

            if (this.Settings.ContainsKey(Constants.AllowFiles))
            {
                this.AllowFiles = Convert.ToBoolean(this.Settings[Constants.AllowFiles]);
            }

            this.ctlJournalList.Enabled   = true;
            this.ctlJournalList.ProfileId = -1;
            this.ctlJournalList.PageSize  = this.PageSize;
            this.ctlJournalList.ModuleId  = this.ModuleId;

            ModuleInfo moduleInfo = this.ModuleContext.Configuration;

            foreach (var module in ModuleController.Instance.GetTabModules(this.TabId).Values)
            {
                if (module.ModuleDefinition.FriendlyName == "Social Groups")
                {
                    if (this.GroupId == -1 && this.FilterMode == JournalMode.Auto)
                    {
                        this.ShowEditor             = false;
                        this.ctlJournalList.Enabled = false;
                    }

                    if (this.GroupId > 0)
                    {
                        RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, this.GroupId);
                        if (roleInfo != null)
                        {
                            if (this.UserInfo.IsInRole(roleInfo.RoleName))
                            {
                                this.ShowEditor = true;
                                this.CanComment = true;
                                this.IsGroup    = true;
                            }
                            else
                            {
                                this.ShowEditor = false;
                                this.CanComment = false;
                            }

                            if (!roleInfo.IsPublic && !this.ShowEditor)
                            {
                                this.ctlJournalList.Enabled = false;
                            }

                            if (roleInfo.IsPublic && !this.ShowEditor)
                            {
                                this.ctlJournalList.Enabled = true;
                            }

                            if (roleInfo.IsPublic && this.ShowEditor)
                            {
                                this.ctlJournalList.Enabled = true;
                            }

                            if (roleInfo.IsPublic)
                            {
                                this.IsPublicGroup = true;
                            }
                        }
                        else
                        {
                            this.ShowEditor             = false;
                            this.ctlJournalList.Enabled = false;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.Request.QueryString["userId"]))
            {
                this.ctlJournalList.ProfileId = Convert.ToInt32(this.Request.QueryString["userId"]);
                if (!this.UserInfo.IsSuperUser && !isAdmin && this.ctlJournalList.ProfileId != this.UserId)
                {
                    this.ShowEditor = this.ShowEditor && Utilities.AreFriends(UserController.GetUserById(this.PortalId, this.ctlJournalList.ProfileId), this.UserInfo);
                }
            }
            else if (this.GroupId > 0)
            {
                this.ctlJournalList.SocialGroupId = Convert.ToInt32(this.Request.QueryString["groupId"]);
            }

            this.InitializeComponent();
            base.OnInit(e);
        }
Beispiel #28
0
        public bool ChangeRole(Guid transactionid, AdminInfo admin, RoleInfo role, out string strJsonResult)
        {
            bool result = true;

            strJsonResult = string.Empty;
            ErrorCodeInfo error = new ErrorCodeInfo();

            string message  = string.Empty;
            string paramstr = string.Empty;

            paramstr += $"AdminID:{admin.UserID}";
            paramstr += $"||AdminAccount:{admin.UserAccount}";
            paramstr += $"||RoleID:{role.RoleID}";
            paramstr += $"||RoleName:{role.RoleName}";
            paramstr += $"||ControlLimit:{role.ControlLimit.ToString()}";
            paramstr += $"||ControlLimitID:{role.ControlLimitID}";
            paramstr += $"||Members:";
            for (int i = 0; i < role.UserList.Count; i++)
            {
                paramstr += role.UserList[i].UserID + ",";
            }

            string funname = "ChangeRole";

            try
            {
                do
                {
                    error = role.ChangeCheckProp();

                    if (error.Code != ErrorCode.None)
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }

                    RoleInfo       oldrole  = new RoleInfo();
                    RoleDBProvider provider = new RoleDBProvider();
                    if (!provider.GetRoleInfo(transactionid, admin, role.RoleID, out oldrole, out error))
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }

                    if (oldrole.IsDefault == 1 && role.UserList.Count == 0)
                    {
                        error.Code    = ErrorCode.MustHaveMember;
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }

                    DirectoryEntry entry          = new DirectoryEntry();
                    CommonProvider commonProvider = new CommonProvider();

                    List <ControlLimitOuInfo> controlLimitOus             = new List <ControlLimitOuInfo>();
                    List <string>             controlOUdistinguishedNames = new List <string>();
                    for (int i = 0; i < role.ControlLimitOuList.Count; i++)
                    {
                        if (!commonProvider.GetADEntryByGuid(role.ControlLimitOuList[i].OuID, out entry, out message))
                        {
                            error.Code    = ErrorCode.SearchADDataError;
                            strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                            LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                            LoggerHelper.Error("AddRole调用GetADEntryByGuid异常", paramstr, message, transactionid);
                            result = false;
                            break;
                        }
                        string OUdistinguishedName = Convert.ToString(entry.Properties["distinguishedName"].Value);

                        if (!controlOUdistinguishedNames.Contains(OUdistinguishedName))
                        {
                            controlOUdistinguishedNames.Add(OUdistinguishedName);
                            ControlLimitOuInfo controlLimitOu = new ControlLimitOuInfo();
                            controlLimitOu.OuID = role.ControlLimitOuList[i].OuID;
                            controlLimitOu.OUdistinguishedName = OUdistinguishedName;
                            controlLimitOus.Add(controlLimitOu);
                        }
                    }
                    if (result)
                    {
                        if (controlOUdistinguishedNames.Count == 0)
                        {
                            error.Code    = ErrorCode.ControlOUPathNotEmpty;
                            strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                            LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                            LoggerHelper.Error("ChangeRole异常", paramstr, error.Info, transactionid);
                            result = false;
                            break;
                        }

                        if (!CheckControlOUdistinguishedNames(transactionid, controlOUdistinguishedNames, out error))
                        {
                            strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                            LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                            LoggerHelper.Error("ChangeRole异常", paramstr, error.Info, transactionid);
                            result = false;
                            break;
                        }

                        string members = string.Empty;
                        for (int i = 0; i < role.UserList.Count; i++)
                        {
                            if (!commonProvider.GetADEntryByGuid(role.UserList[i].UserID, out entry, out message))
                            {
                                LoggerHelper.Error("ChangeRole调用GetADEntryByGuid异常", paramstr, message, transactionid);
                                continue;
                            }

                            string DisplayName = entry.Properties["cn"].Value == null ? "" : Convert.ToString(entry.Properties["cn"].Value);
                            string UserAccount = entry.Properties["userPrincipalName"].Value == null ? "" : Convert.ToString(entry.Properties["userPrincipalName"].Value);

                            AdminInfo userRole = new AdminInfo();
                            if (provider.GetUserRole(transactionid, role.UserList[i].UserID, ref userRole, out error))
                            {
                                if (userRole.RoleID != role.RoleID)
                                {
                                    error.Code = ErrorCode.UserHaveRole;
                                    string errormessage = DisplayName + "(" + UserAccount + ") 已存在角色";
                                    strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), errormessage);
                                    LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                                    LoggerHelper.Error("ChangeRole调用GetADEntryByGuid异常", paramstr, message, transactionid);
                                    result = false;
                                    break;
                                }
                            }

                            members += DisplayName + "(" + UserAccount + "),";
                        }
                        members = string.IsNullOrEmpty(members) ? string.Empty : members.Remove(members.LastIndexOf(','), 1);
                        if (result)
                        {
                            //检查权限
                            List <RoleParam> roleParams = new List <RoleParam>();
                            for (int i = 0; i < role.RoleList.Count; i++)
                            {
                                foreach (RoleParam param in role.RoleList[i].RoleParamList)
                                {
                                    RoleParam roleParam = new RoleParam();
                                    if (provider.GetRoleParam(transactionid, param.ParamID, out roleParam, out error))
                                    {
                                        roleParams.Add(roleParam);
                                    }
                                }
                            }

                            var query = from r in roleParams where r.ParamCode.Equals("SameLevelOu") select r;
                            if (query.Any())
                            {
                                if (role.SameLevelOuList.Count == 0)
                                {
                                    error.Code = ErrorCode.MustHaveSameLevelOuPath;
                                    LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                                    strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                                    result        = false;
                                    break;
                                }
                            }

                            if (!provider.ChangeRole(transactionid, admin, role, out error))
                            {
                                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                                LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                                result = false;
                                break;
                            }

                            for (int i = 0; i < role.RoleList.Count; i++)
                            {
                                foreach (RoleParam param in role.RoleList[i].RoleParamList)
                                {
                                    if (!provider.AddRoleModuleParam(transactionid, role.RoleID, param, out error))
                                    {
                                        continue;
                                    }
                                }
                            }

                            for (int i = 0; i < role.UserList.Count; i++)
                            {
                                if (!provider.AddRoleMembers(transactionid, role.RoleID, role.UserList[i], out error))
                                {
                                    continue;
                                }
                            }

                            for (int i = 0; i < role.SameLevelOuList.Count; i++)
                            {
                                if (!provider.AddSameLevelOu(transactionid, role.RoleID, role.SameLevelOuList[i], out error))
                                {
                                    continue;
                                }
                            }

                            for (int i = 0; i < controlLimitOus.Count; i++)
                            {
                                if (!provider.AddControlLimitOu(transactionid, role.RoleID, controlLimitOus[i], out error))
                                {
                                    continue;
                                }
                            }
                            error.Code = ErrorCode.None;
                            string json = JsonConvert.SerializeObject(role);
                            LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), true, transactionid);
                            strJsonResult = JsonHelper.ReturnJson(true, Convert.ToInt32(error.Code), error.Info, json);

                            #region 操作日志
                            LogInfo operateLog = new LogInfo();
                            operateLog.AdminID       = admin.UserID;
                            operateLog.AdminAccount  = admin.UserAccount;
                            operateLog.RoleID        = admin.RoleID;
                            operateLog.ClientIP      = _clientip;
                            operateLog.OperateResult = true;
                            operateLog.OperateType   = "修改角色";
                            operateLog.OperateLog    = $"{admin.UserAccount}于{DateTime.Now}修改角色。" +
                                                       $"原角色名称:{oldrole.RoleName},现角色名称{role.RoleName};" +
                                                       $"原管理范围:{oldrole.ControlLimitPath},现管理范围:{role.ControlLimitPath};" +
                                                       $"现成员:{members}";
                            LogManager.AddOperateLog(transactionid, operateLog);
                            #endregion

                            result = true;
                        }
                    }
                } while (false);
            }
            catch (Exception ex)
            {
                error.Code = ErrorCode.Exception;
                LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                LoggerHelper.Error("RoleManager调用ChangeRole异常", paramstr, ex.ToString(), transactionid);
                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                result        = false;
            }
            return(result);
        }
Beispiel #29
0
        public bool DeleteRole(Guid transactionid, AdminInfo admin, RoleInfo role, out string strJsonResult)
        {
            bool result = true;

            strJsonResult = string.Empty;
            ErrorCodeInfo error = new ErrorCodeInfo();

            string message  = string.Empty;
            string paramstr = string.Empty;

            paramstr += $"AdminID:{admin.UserID}";
            paramstr += $"||AdminAccount:{admin.UserAccount}";
            paramstr += $"||RoleID:{role.RoleID}";

            string funname = "DeleteRole";

            try
            {
                do
                {
                    RoleDBProvider provider = new RoleDBProvider();
                    if (!provider.GetRoleInfo(transactionid, admin, role.RoleID, out role, out error))
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }

                    if (role.IsDefault == 1)
                    {
                        error.Code    = ErrorCode.IsDefaultRole;
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }

                    if (!provider.DeleteRole(transactionid, admin, role, out error))
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                        result = false;
                        break;
                    }
                    error.Code = ErrorCode.None;
                    LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), true, transactionid);
                    strJsonResult = JsonHelper.ReturnJson(true, Convert.ToInt32(error.Code), error.Info);

                    #region 操作日志
                    LogInfo operateLog = new LogInfo();
                    operateLog.AdminID       = admin.UserID;
                    operateLog.AdminAccount  = admin.UserAccount;
                    operateLog.RoleID        = admin.RoleID;
                    operateLog.ClientIP      = _clientip;
                    operateLog.OperateResult = true;
                    operateLog.OperateType   = "删除角色";
                    operateLog.OperateLog    = $"{admin.UserAccount}于{DateTime.Now}删除角色。" +
                                               $"删除名称:{role.RoleName}";
                    LogManager.AddOperateLog(transactionid, operateLog);
                    #endregion

                    result = true;
                } while (false);
            }
            catch (Exception ex)
            {
                error.Code = ErrorCode.Exception;
                LoggerHelper.Info(admin.UserAccount, funname, paramstr, Convert.ToString(error.Code), false, transactionid);
                LoggerHelper.Error("RoleManager调用DeleteRole异常", paramstr, ex.ToString(), transactionid);
                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                result        = false;
            }
            return(result);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        roleId = QueryHelper.GetInteger("roleid", 0);

        string roleListUrl = "~/CMSModules/Membership/Pages/Roles/Role_List.aspx";

        if (SelectedSiteID != 0)
        {
            urlQuery = "selectedsiteid=" + SelectedSiteID;
            siteID = SelectedSiteID;
        }
        else if (SiteID != 0)
        {
            urlQuery = "siteid=" + SiteID;
            siteID = SiteID;
        }

        if (urlQuery != String.Empty)
        {
            roleListUrl += "?";
        }

        roleListUrl += urlQuery;

        string currentRole = "";
        role = RoleInfoProvider.GetRoleInfo(roleId);
        if (role != null)
        {
            currentRole = role.DisplayName;
        }

        // Initialize PageTitle breadcrumbs
        string[,] pageTitleTabs = new string[2, 3];
        pageTitleTabs[0, 0] = GetString("general.roles");
        pageTitleTabs[0, 1] = roleListUrl;
        pageTitleTabs[0, 2] = "_parent";
        pageTitleTabs[1, 0] = currentRole;
        pageTitleTabs[1, 1] = "";
        pageTitleTabs[1, 2] = "";

        CurrentMaster.Title.Breadcrumbs = pageTitleTabs;
        CurrentMaster.Title.TitleText = GetString("Administration-Role_Edit.Title");
        CurrentMaster.Title.TitleImage = GetImageUrl("Objects/CMS_Role/object.png");
        CurrentMaster.Title.HelpTopicName = "general_tab9";
        CurrentMaster.Title.HelpName = "title";

        // Register script
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ShowContent", ScriptHelper.GetScript("function ShowContent(contentLocation) { parent.frames['content'].location.href= contentLocation; }"));

        // Tabs
        InitalizeTabs();
    }
Beispiel #31
0
    /// <summary>
    /// Gets and bulk updates roles. Called when the "Get and bulk update roles" button is pressed.
    /// Expects the CreateRole method to be run first.
    /// </summary>
    private bool GetAndBulkUpdateRoles()
    {
        // Prepare the parameters
        string where = "RoleName LIKE N'MyNewRole%'";

        // Get the data
        DataSet roles = RoleInfoProvider.GetRoles(where, null);
        if (!DataHelper.DataSourceIsEmpty(roles))
        {
            // Loop through the individual items
            foreach (DataRow roleDr in roles.Tables[0].Rows)
            {
                // Create object from DataRow
                RoleInfo modifyRole = new RoleInfo(roleDr);

                // Update the properties
                modifyRole.DisplayName = modifyRole.DisplayName.ToUpper();

                // Save the changes
                RoleInfoProvider.SetRoleInfo(modifyRole);
            }

            return true;
        }

        return false;
    }
Beispiel #32
0
        private void Create_Click(object sender, EventArgs e)
        {
            var ps = Security.PortalSecurity.Instance;

            txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoScripting);
            txtGroupName.Text = ps.InputFilter(txtGroupName.Text, Security.PortalSecurity.FilterFlag.NoMarkup);

            txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoScripting);
            txtDescription.Text = ps.InputFilter(txtDescription.Text, Security.PortalSecurity.FilterFlag.NoMarkup);
            if (RoleController.Instance.GetRoleByName(PortalId, txtGroupName.Text) != null)
            {
                lblInvalidGroupName.Visible = true;
                return;
            }


            var modRoles = new List <RoleInfo>();
            var modUsers = new List <UserInfo>();

            foreach (ModulePermissionInfo modulePermissionInfo in ModulePermissionController.GetModulePermissions(ModuleId, TabId))
            {
                if (modulePermissionInfo.PermissionKey == "MODGROUP" && modulePermissionInfo.AllowAccess)
                {
                    if (modulePermissionInfo.RoleID > int.Parse(Globals.glbRoleNothing))
                    {
                        modRoles.Add(RoleController.Instance.GetRoleById(PortalId, modulePermissionInfo.RoleID));
                    }
                    else if (modulePermissionInfo.UserID > Null.NullInteger)
                    {
                        modUsers.Add(UserController.GetUserById(PortalId, modulePermissionInfo.UserID));
                    }
                }
            }

            var roleInfo = new RoleInfo()
            {
                PortalID     = PortalId,
                RoleName     = txtGroupName.Text,
                Description  = txtDescription.Text,
                SecurityMode = SecurityMode.SocialGroup,
                Status       = RoleStatus.Approved,
                IsPublic     = rdAccessTypePublic.Checked
            };
            var userRoleStatus = RoleStatus.Pending;

            if (GroupModerationEnabled)
            {
                roleInfo.Status = RoleStatus.Pending;
                userRoleStatus  = RoleStatus.Pending;
            }
            else
            {
                userRoleStatus = RoleStatus.Approved;
            }

            var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(ModuleId, -1), typeof(ModulePermissionInfo)));

            if (ModulePermissionController.HasModulePermission(objModulePermissions, "MODGROUP"))
            {
                roleInfo.Status = RoleStatus.Approved;
                userRoleStatus  = RoleStatus.Approved;
            }

            var roleGroupId = DefaultRoleGroupId;

            if (roleGroupId < Null.NullInteger)
            {
                roleGroupId = Null.NullInteger;
            }
            roleInfo.RoleGroupID = roleGroupId;

            roleInfo.RoleID = RoleController.Instance.AddRole(roleInfo);
            roleInfo        = RoleController.Instance.GetRoleById(PortalId, roleInfo.RoleID);

            var groupUrl = Globals.NavigateURL(GroupViewTabId, "", new String[] { "groupid=" + roleInfo.RoleID.ToString() });

            if (groupUrl.StartsWith("http://") || groupUrl.StartsWith("https://"))
            {
                const int startIndex = 8;                 // length of https://
                groupUrl = groupUrl.Substring(groupUrl.IndexOf("/", startIndex, StringComparison.InvariantCultureIgnoreCase));
            }
            roleInfo.Settings.Add("URL", groupUrl);

            roleInfo.Settings.Add("GroupCreatorName", UserInfo.DisplayName);
            roleInfo.Settings.Add("ReviewMembers", chkMemberApproved.Checked.ToString());

            RoleController.Instance.UpdateRoleSettings(roleInfo, true);
            if (inpFile.PostedFile != null && inpFile.PostedFile.ContentLength > 0)
            {
                IFileManager   _fileManager   = FileManager.Instance;
                IFolderManager _folderManager = FolderManager.Instance;
                var            rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory);

                IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID);
                if (groupFolder == null)
                {
                    groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID);
                }
                if (groupFolder != null)
                {
                    var fileName = Path.GetFileName(inpFile.PostedFile.FileName);
                    var fileInfo = _fileManager.AddFile(groupFolder, fileName, inpFile.PostedFile.InputStream, true);
                    roleInfo.IconFile = "FileID=" + fileInfo.FileId;
                    RoleController.Instance.UpdateRole(roleInfo);
                }
            }

            var notifications = new Notifications();


            RoleController.Instance.AddUserRole(PortalId, UserId, roleInfo.RoleID, userRoleStatus, true, Null.NullDate, Null.NullDate);
            if (roleInfo.Status == RoleStatus.Pending)
            {
                //Send notification to Group Moderators to approve/reject group.
                notifications.AddGroupNotification(Constants.GroupPendingNotification, GroupViewTabId, ModuleId, roleInfo, UserInfo, modRoles, modUsers);
            }
            else
            {
                //Send notification to Group Moderators informing of new group.
                notifications.AddGroupNotification(Constants.GroupCreatedNotification, GroupViewTabId, ModuleId, roleInfo, UserInfo, modRoles, modUsers);

                //Add entry to journal.
                GroupUtilities.CreateJournalEntry(roleInfo, UserInfo);
            }

            Response.Redirect(Globals.NavigateURL(GroupViewTabId, "", new String[] { "groupid=" + roleInfo.RoleID.ToString() }));
        }
Beispiel #33
0
        public void UpdateRoleSettings(RoleInfo role, bool clearCache)
        {
            provider.UpdateRoleSettings(role);

            if (clearCache)
            {
                ClearRoleCache(role.PortalID);
            }
        }
Beispiel #34
0
        public void UpdateJournalItem(JournalItem journalItem, int tabId)
        {
            if (journalItem.UserId < 1)
            {
                throw new ArgumentException("journalItem.UserId must be for a real user");
            }
            UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId);

            if (currentUser == null)
            {
                throw new Exception("Unable to locate the current user");
            }
            string xml            = null;
            var    portalSecurity = new PortalSecurity();

            if (!String.IsNullOrEmpty(journalItem.Title))
            {
                journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup);
            }
            if (!String.IsNullOrEmpty(journalItem.Summary))
            {
                journalItem.Summary = HttpUtility.HtmlDecode(portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting));
            }
            if (!String.IsNullOrEmpty(journalItem.Body))
            {
                journalItem.Body = HttpUtility.HtmlDecode(portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting));
            }
            if (!String.IsNullOrEmpty(journalItem.Body))
            {
                var        xDoc   = new XmlDocument();
                XmlElement xnode  = xDoc.CreateElement("items");
                XmlElement xnode2 = xDoc.CreateElement("item");
                xnode2.AppendChild(CreateElement(xDoc, "id", "-1"));
                xnode2.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body));
                xnode.AppendChild(xnode2);
                xDoc.AppendChild(xnode);
                XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null);
                xDec.Encoding   = "UTF-16";
                xDec.Standalone = "yes";
                XmlElement root = xDoc.DocumentElement;
                xDoc.InsertBefore(xDec, root);
                journalItem.JournalXML = xDoc;
                xml = journalItem.JournalXML.OuterXml;
            }
            if (journalItem.ItemData != null)
            {
                if (!String.IsNullOrEmpty(journalItem.ItemData.Title))
                {
                    journalItem.ItemData.Title = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup);
                }
                if (!String.IsNullOrEmpty(journalItem.ItemData.Description))
                {
                    journalItem.ItemData.Description = HttpUtility.HtmlDecode(portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting));
                }
                if (!String.IsNullOrEmpty(journalItem.ItemData.Url))
                {
                    journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting);
                }
                if (!String.IsNullOrEmpty(journalItem.ItemData.ImageUrl))
                {
                    journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting);
                }
            }
            string journalData = journalItem.ItemData.ToJson();

            if (journalData == "null")
            {
                journalData = null;
            }
            if (String.IsNullOrEmpty(journalItem.SecuritySet))
            {
                journalItem.SecuritySet = "E,";
            }
            else if (!journalItem.SecuritySet.EndsWith(","))
            {
                journalItem.SecuritySet += ",";
            }
            if (journalItem.SecuritySet == "F,")
            {
                journalItem.SecuritySet  = "F" + journalItem.UserId.ToString(CultureInfo.InvariantCulture) + ",";
                journalItem.SecuritySet += "P" + journalItem.ProfileId.ToString(CultureInfo.InvariantCulture) + ",";
            }
            if (journalItem.SecuritySet == "U,")
            {
                journalItem.SecuritySet += "U" + journalItem.UserId.ToString(CultureInfo.InvariantCulture) + ",";
            }
            if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId)
            {
                journalItem.SecuritySet += "P" + journalItem.ProfileId.ToString(CultureInfo.InvariantCulture) + ",";
                journalItem.SecuritySet += "U" + journalItem.UserId.ToString(CultureInfo.InvariantCulture) + ",";
            }
            if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId.ToString(CultureInfo.InvariantCulture)))
            {
                journalItem.SecuritySet += "U" + journalItem.UserId.ToString(CultureInfo.InvariantCulture) + ",";
            }
            if (journalItem.SocialGroupId > 0)
            {
                JournalItem item = journalItem;
                RoleInfo    role = TestableRoleController.Instance.GetRole(journalItem.PortalId, r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId);
                if (role != null)
                {
                    if (currentUser.IsInRole(role.RoleName))
                    {
                        journalItem.SecuritySet += "R" + journalItem.SocialGroupId.ToString(CultureInfo.InvariantCulture) + ",";
                        if (!role.IsPublic)
                        {
                            journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", String.Empty);
                        }
                    }
                }
            }
            journalItem.JournalId = _dataService.Journal_Save(journalItem.PortalId,
                                                              journalItem.UserId,
                                                              journalItem.ProfileId,
                                                              journalItem.SocialGroupId,
                                                              journalItem.JournalId,
                                                              journalItem.JournalTypeId,
                                                              journalItem.Title,
                                                              journalItem.Summary,
                                                              journalItem.Body,
                                                              journalData,
                                                              xml,
                                                              journalItem.ObjectKey,
                                                              journalItem.AccessKey,
                                                              journalItem.SecuritySet,
                                                              journalItem.CommentsDisabled,
                                                              journalItem.CommentsHidden);

            var updatedJournalItem = GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId);

            journalItem.DateCreated = updatedJournalItem.DateCreated;
            journalItem.DateUpdated = updatedJournalItem.DateUpdated;

            var cnt = new Content();

            if (journalItem.ContentItemId > 0)
            {
                cnt.UpdateContentItem(journalItem, tabId);
                _dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId);
            }
            else
            {
                ContentItem ci = cnt.CreateContentItem(journalItem, tabId);
                _dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId);
                journalItem.ContentItemId = ci.ContentItemId;
            }
            if (journalItem.SocialGroupId > 0)
            {
                try
                {
                    UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId);
                }
                catch (Exception exc)
                {
                    Exceptions.Exceptions.LogException(exc);
                }
            }
        }
Beispiel #35
0
    /// <summary>
    /// Roles control items changed event.
    /// </summary>
    protected void RolesSelector_OnItemsSelected(object sender, EventArgs e)
    {
        // Check permissions
        CheckAuthorization();

        int roleID = 0;

        string[]   newItems = null;
        Subscriber sb       = null;
        int        siteId   = CMSContext.CurrentSiteID;

        // Get new items from selector
        string newValues = ValidationHelper.GetString(selectRole.Value, null);

        // Get added items
        newItems = newValues.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        if (newItems != null)
        {
            foreach (string item in newItems)
            {
                roleID = ValidationHelper.GetInteger(item, 0);

                // Get subscriber
                sb = SubscriberProvider.GetSubscriber(SiteObjectType.ROLE, roleID, siteId);
                if (sb == null)
                {
                    // Get role info and copy display name to new subscriber
                    RoleInfo ri = RoleInfoProvider.GetRoleInfo(roleID);
                    if (ri == null)
                    {
                        break;
                    }

                    // Check limited number of subscribers
                    if (!SubscriberProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Subscribers, VersionActionEnum.Insert))
                    {
                        lblError.Text    = GetString("licenselimitations.subscribers.errormultiple");
                        lblError.Visible = true;
                        break;
                    }

                    // Create new subscriber of role type
                    sb = new Subscriber();
                    sb.SubscriberFirstName = ri.DisplayName;
                    // Full name consists of "role " and role display name
                    sb.SubscriberFullName  = string.Concat("Role '", ri.DisplayName, "'");
                    sb.SubscriberSiteID    = siteId;
                    sb.SubscriberType      = SiteObjectType.ROLE;
                    sb.SubscriberRelatedID = roleID;
                    SubscriberProvider.SetSubscriber(sb);
                }

                // If subscriber exists and is not subscribed, subscribe him
                if ((sb != null) && (!SubscriberProvider.IsSubscribed(sb.SubscriberID, newsletterId)))
                {
                    try
                    {
                        SubscriberProvider.Subscribe(sb.SubscriberID, newsletterId, DateTime.Now, chkSendConfirmation.Checked, false);
                    }
                    catch
                    {
                    }
                }
            }
        }

        selectRole.Value = null;
        UniGridSubscribers.ReloadData();
        pnlUpdate.Update();
    }
    /// <summary>
    /// After node created, solver role permissions.
    /// </summary>
    private void AddRoles(object sender, EventArgs e)
    {
        string roleIds = ";" + usRoles.Value + ";";

        // Check if ACL should inherit from parent
        if (InheritParentPermissions)
        {
            AclInfoProvider.EnsureOwnAcl(EditedNode);
        }
        else
        {
            // If node has already own ACL don't leave permissions, otherwise break inheritance
            if (!EditedNode.NodeIsACLOwner)
            {
                AclInfoProvider.BreakInheritance(EditedNode, false);
            }
        }

        // Get original ACLItems
        DataSet ds = AclItemInfoProvider.GetACLItemsAndOperators(EditedNode.NodeID)
                     .WhereStartsWith("Operator", "R")
                     .WhereEquals("ACLID", EditedNode.NodeACLID)
                     .Columns("Operator", "Allowed", "Denied");

        // Change original values
        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string op        = DataHelper.GetNotEmpty(dr["Operator"], "R");
                int    allowed   = ValidationHelper.GetInteger(dr["Allowed"], 0);
                int    denied    = ValidationHelper.GetInteger(dr["Denied"], 0);
                int    aclRoleId = ValidationHelper.GetInteger(op.Substring(1), 0);

                if (aclRoleId != 0)
                {
                    // Check if read permission should be set or removed
                    if (roleIds.Contains(";" + aclRoleId + ";"))
                    {
                        // Remove role from processed role and adjust permissions in database
                        roleIds  = roleIds.Replace(";" + aclRoleId + ";", ";");
                        allowed |= 1;
                    }
                    else
                    {
                        allowed &= 126;
                    }

                    RoleInfo ri = RoleInfoProvider.GetRoleInfo(aclRoleId);
                    AclItemInfoProvider.SetRolePermissions(EditedNode, allowed, denied, ri);
                }
            }
        }


        if (roleIds.Trim(';') == "")
        {
            return;
        }

        // Create ACL items for new roles
        string[] roles = roleIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string role in roles)
        {
            RoleInfo ri = RoleInfoProvider.GetRoleInfo(int.Parse(role));
            AclItemInfoProvider.SetRolePermissions(EditedNode, 1, 0, ri);
        }
    }
Beispiel #37
0
 public void UpdateRole(RoleInfo role, bool addToExistUsers)
 {
     RoleController.Instance.UpdateRole(role, addToExistUsers);
 }
Beispiel #38
0
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// Gets the Enabled status of the permission.
 /// </summary>
 /// <param name="objPerm">The permission being loaded.</param>
 /// <param name="role">The role.</param>
 /// <param name="column">The column of the Grid.</param>
 /// <returns></returns>
 /// -----------------------------------------------------------------------------
 protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column)
 {
     return(!this.IsImplicitRole(role.PortalID, role.RoleID));
 }
Beispiel #39
0
 public void DeleteRole(RoleInfo role)
 {
     RoleController.Instance.DeleteRole(role);
 }
 /// <summary>
 /// Loads data of edited role from DB into TextBoxes.
 /// </summary>
 protected void LoadData(RoleInfo ri)
 {
     txtRoleCodeName.Text = ri.RoleName;
     txtRoleDisplayName.Text = ri.DisplayName;
     txtDescription.Text = ri.Description;
     chkIsAdmin.Checked = ri.RoleIsGroupAdministrator;
     chkIsDomain.Checked = ri.RoleIsDomain;
 }
Beispiel #41
0
 public int AddRole(RoleInfo role)
 {
     return(RoleController.Instance.AddRole(role));
 }
Beispiel #42
0
 public DumpableDict(Dictionary<string, Role> Roles)
 {
     foreach (KeyValuePair<string,Role> role in Roles)
     {
         RoleInfo i = new RoleInfo(role.Value);
         i.Name = role.Key;
         this.Roles.Add(i);
     }
 }
Beispiel #43
0
 public GuiMianJunZiRole(RoleInfo roleInfo)
     : base(roleInfo)
 {
 }
Beispiel #44
0
 public abstract void CreateRole(RoleInfo role, out RoleCreationStatus status);
Beispiel #45
0
 private void LoadRole(XmlNode roleNode)
 {
     try {
         RoleInfo role = new RoleInfo();
         role.Name = roleNode.SelectSingleNode("Name").InnerText;
         if(roleNode.SelectSingleNode("InheritsFrom") != null) {
             role.Inherits = roleNode.SelectSingleNode("InheritsFrom").InnerText;
         }
         if(roleNode.SelectSingleNode("ShowsAs") != null) {
             role.ShowsAs = roleNode.SelectSingleNode("ShowsAs").InnerText;
         }
         foreach(XmlNode powerNode in roleNode.SelectNodes("Powers/Power")) {
             LoadPower(powerNode, role, RoleInfo.PowerType.Power);
         }
         foreach (XmlNode powerNode in roleNode.SelectNodes("Effects/Effect")) {
             LoadPower(powerNode, role, RoleInfo.PowerType.Effect);
         }
         roles.Add(role.Name, role);
     }
     catch(Exception ex) {
         Log.Warn("Failed to load a role: " + ex.Message);
     }
 }
Beispiel #46
0
 public bool EditTo(RoleInfo entity)
 {
     return(efCore.EditTo(entity));
 }
Beispiel #47
0
    /// <summary>
    /// Creates role. Called when the "Create role" button is pressed.
    /// </summary>
    private bool CreateRole()
    {
        // Create new role object
        RoleInfo newRole = new RoleInfo();

        // Set the properties
        newRole.DisplayName = "My new role";
        newRole.RoleName = "MyNewRole";
        newRole.SiteID = CMSContext.CurrentSiteID;

        // Save the role
        RoleInfoProvider.SetRoleInfo(newRole);

        return true;
    }
Beispiel #48
0
 /// <summary>
 /// Update a role
 /// </summary>
 /// <param name="role">The role to update</param>
 /// <history>
 ///     [cnurse]	03/28/2006	created
 /// </history>
 public override void UpdateRole(RoleInfo role)
 {
     dataProvider.UpdateRole(role.RoleID, role.RoleGroupID, role.Description, role.ServiceFee, role.BillingPeriod.ToString(), role.BillingFrequency, role.TrialFee, role.TrialPeriod, role.TrialFrequency, role.IsPublic, role.AutoAssignment, role.RSVPCode, role.IconFile);
 }
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        // Validate form entries
        string errorMessage = ValidateForm();
        if (errorMessage == string.Empty)
        {
            try
            {
                codeName = GetSafeCodeName();
                codeName = GetUniqueCodeName(codeName);

                GroupInfo group = new GroupInfo();
                group.GroupDisplayName = txtDisplayName.Text;
                group.GroupName = codeName;
                group.GroupDescription = txtDescription.Text;
                group.GroupAccess = GetGroupAccess();
                group.GroupSiteID = mSiteId;
                group.GroupApproveMembers = GetGroupApproveMembers();

                // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
                var user = MembershipContext.AuthenticatedUser;

                if (user != null)
                {
                    group.GroupCreatedByUserID = user.UserID;

                    if ((!RequireApproval) || (CurrentUserIsAdmin()))
                    {
                        group.GroupApprovedByUserID = user.UserID;
                        group.GroupApproved = true;
                    }
                }

                // Save Group in the database
                GroupInfoProvider.SetGroupInfo(group);

                // Create group admin role
                RoleInfo roleInfo = new RoleInfo();
                roleInfo.DisplayName = "Group admin";
                roleInfo.RoleName = group.GroupName + "_groupadmin";
                roleInfo.RoleGroupID = group.GroupID;
                roleInfo.RoleIsGroupAdministrator = true;
                roleInfo.SiteID = mSiteId;
                // Save group admin role
                RoleInfoProvider.SetRoleInfo(roleInfo);

                if (user != null)
                {
                    // Set user as member of group
                    GroupMemberInfo gmi = new GroupMemberInfo();
                    gmi.MemberUserID = user.UserID;
                    gmi.MemberGroupID = group.GroupID;
                    gmi.MemberJoined = DateTime.Now;
                    gmi.MemberStatus = GroupMemberStatus.Approved;
                    gmi.MemberApprovedWhen = DateTime.Now;
                    gmi.MemberApprovedByUserID = user.UserID;

                    // Save user as member of group
                    GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                    // Set user as member of admin group role
                    UserRoleInfo userRole = new UserRoleInfo();
                    userRole.UserID = user.UserID;
                    userRole.RoleID = roleInfo.RoleID;

                    // Save user as member of admin group role
                    UserRoleInfoProvider.SetUserRoleInfo(userRole);
                }

                // Clear user session a request
                MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);
                MembershipContext.AuthenticatedUser = null;

                string culture = CultureHelper.EnglishCulture.ToString();
                if (DocumentContext.CurrentDocument != null)
                {
                    culture = DocumentContext.CurrentDocument.DocumentCulture;
                }

                // Copy document
                errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo);

                if (!String.IsNullOrEmpty(errorMessage))
                {
                    // Display error message
                    ShowError(errorMessage);
                    return;
                }

                // Create group forum
                if (CreateForum)
                {
                    CreateGroupForum(group);

                    // Create group forum search index
                    if (CreateSearchIndexes)
                    {
                        CreateGroupForumSearchIndex(group);
                    }
                }

                // Create group media library
                if (CreateMediaLibrary)
                {
                    CreateGroupMediaLibrary(group);
                }

                // Create search index for group documents
                if (CreateSearchIndexes)
                {
                    CreateGroupContentSearchIndex(group);
                }

                // Display information on success
                ShowConfirmation(GetString("group.group.createdinfo"));

                // If URL is set, redirect user to specified page
                if (!String.IsNullOrEmpty(RedirectToURL))
                {
                    URLHelper.Redirect(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL)));
                }

                // After registration message
                if ((RequireApproval) && (!CurrentUserIsAdmin()))
                {
                    ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText);

                    // Send approval email to admin
                    if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                    {
                        // Create the message
                        EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", SiteContext.CurrentSiteName);
                        if (eti != null)
                        {
                            EmailMessage message = new EmailMessage();
                            if (String.IsNullOrEmpty(eti.TemplateFrom))
                            {
                                message.From = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom");
                            }
                            else
                            {
                                message.From = eti.TemplateFrom;
                            }

                            MacroResolver resolver = MacroContext.CurrentResolver;
                            resolver.SetAnonymousSourceData(group);
                            resolver.SetNamedSourceData("Group", group);

                            message.Recipients = SendWaitingForApprovalEmailTo;
                            message.Subject = resolver.ResolveMacros(eti.TemplateSubject);
                            message.Body = resolver.ResolveMacros(eti.TemplateText);

                            resolver.Settings.EncodeResolvedValues = false;
                            message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText);

                            // Send the message using email engine
                            EmailSender.SendEmail(message);
                        }
                    }
                }
                else
                {
                    string groupPath = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                    string url = String.Empty;

                    if (!String.IsNullOrEmpty(groupPath))
                    {
                        url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                    }
                    ShowConfirmation(String.Format(SuccessfullRegistrationText, url));
                }

                // Hide form
                if (HideFormAfterRegistration)
                {
                    plcForm.Visible = false;
                }
                else
                {
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                // Display error message
                ShowError(GetString("general.saveerror"), ex.Message, null);
            }
        }
        else
        {
            // Display error message
            ShowError(errorMessage);
        }
    }
Beispiel #50
0
 /// <summary>
 /// DeleteRole deletes a Role from the Data Store
 /// </summary>
 /// <param name="portalId">Id of the portal</param>
 /// <param name="role">The role to delete from the Data Store.</param>
 /// <history>
 ///     [cnurse]	03/28/2006	created
 /// </history>
 public override void DeleteRole(int portalId, ref RoleInfo role)
 {
     dataProvider.DeleteRole(role.RoleID);
 }
Beispiel #51
0
        public void UpdateRole(RoleInfo role)
        {
            Requires.NotNull("role", role);

            provider.UpdateRole(role);
            AddMessage(role, EventLogController.EventLogType.ROLE_UPDATED);
            AutoAssignUsers(role);

            ClearRoleCache(role.PortalID);
        }
Beispiel #52
0
 public static RoleInfo UpdateRole(RoleInfo role)
 {
     RoleController.Instance.UpdateRole(role);
     return(GetRoleById(role.RoleID, role.PortalID));
 }
Beispiel #53
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                UserInfo objUserInfo = null;
                int      intUserID   = -1;
                if (Request.IsAuthenticated)
                {
                    objUserInfo = UserController.Instance.GetCurrentUserInfo();
                    if (objUserInfo != null)
                    {
                        intUserID = objUserInfo.UserID;
                    }
                }
                int intRoleId = -1;
                if (Request.QueryString["roleid"] != null)
                {
                    intRoleId = int.Parse(Request.QueryString["roleid"]);
                }
                string     strProcessorUserId = "";
                PortalInfo objPortalInfo      = PortalController.Instance.GetPortal(PortalSettings.PortalId);
                if (objPortalInfo != null)
                {
                    strProcessorUserId = objPortalInfo.ProcessorUserId;
                }
                Dictionary <string, string> settings = PortalController.Instance.GetPortalSettings(PortalSettings.PortalId);
                string strPayPalURL;
                if (intUserID != -1 && intRoleId != -1 && !String.IsNullOrEmpty(strProcessorUserId))
                {
                    // Sandbox mode
                    if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].ToLowerInvariant() == "true")
                    {
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
                    else
                    {
                        strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }

                    if (Request.QueryString["cancel"] != null)
                    {
                        //build the cancellation PayPal URL
                        strPayPalURL += "cmd=_subscr-find&alias=" + Globals.HTTPPOSTEncode(strProcessorUserId);
                    }
                    else
                    {
                        strPayPalURL += "cmd=_ext-enter";
                        RoleInfo objRole = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == intRoleId);
                        if (objRole.RoleID != -1)
                        {
                            int intTrialPeriod = 1;
                            if (objRole.TrialPeriod != 0)
                            {
                                intTrialPeriod = objRole.TrialPeriod;
                            }
                            int intBillingPeriod = 1;
                            if (objRole.BillingPeriod != 0)
                            {
                                intBillingPeriod = objRole.BillingPeriod;
                            }

                            //explicitely format numbers using en-US so numbers are correctly built
                            var    enFormat   = new CultureInfo("en-US");
                            string strService = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.ServiceFee);
                            string strTrial   = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.TrialFee);
                            if (objRole.BillingFrequency == "O" || objRole.TrialFrequency == "O")
                            {
                                //build the payment PayPal URL
                                strPayPalURL += "&redirect_cmd=_xclick&business=" + Globals.HTTPPOSTEncode(strProcessorUserId);
                                strPayPalURL += "&item_name=" +
                                                Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " +
                                                                       PortalSettings.Currency + " )");
                                strPayPalURL += "&item_number=" + Globals.HTTPPOSTEncode(intRoleId.ToString());
                                strPayPalURL += "&no_shipping=1&no_note=1";
                                strPayPalURL += "&quantity=1";
                                strPayPalURL += "&amount=" + Globals.HTTPPOSTEncode(strService);
                                strPayPalURL += "&currency_code=" + Globals.HTTPPOSTEncode(PortalSettings.Currency);
                            }
                            else //recurring payments
                            {
                                //build the subscription PayPal URL
                                strPayPalURL += "&redirect_cmd=_xclick-subscriptions&business=" + Globals.HTTPPOSTEncode(strProcessorUserId);
                                strPayPalURL += "&item_name=" +
                                                Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " +
                                                                       PortalSettings.Currency + " every " + intBillingPeriod + " " + GetBillingFrequencyText(objRole.BillingFrequency) + " )");
                                strPayPalURL += "&item_number=" + Globals.HTTPPOSTEncode(intRoleId.ToString());
                                strPayPalURL += "&no_shipping=1&no_note=1";
                                if (objRole.TrialFrequency != "N")
                                {
                                    strPayPalURL += "&a1=" + Globals.HTTPPOSTEncode(strTrial);
                                    strPayPalURL += "&p1=" + Globals.HTTPPOSTEncode(intTrialPeriod.ToString());
                                    strPayPalURL += "&t1=" + Globals.HTTPPOSTEncode(objRole.TrialFrequency);
                                }
                                strPayPalURL += "&a3=" + Globals.HTTPPOSTEncode(strService);
                                strPayPalURL += "&p3=" + Globals.HTTPPOSTEncode(intBillingPeriod.ToString());
                                strPayPalURL += "&t3=" + Globals.HTTPPOSTEncode(objRole.BillingFrequency);
                                strPayPalURL += "&src=1";
                                strPayPalURL += "&currency_code=" + Globals.HTTPPOSTEncode(PortalSettings.Currency);
                            }
                        }
                        var ctlList = new ListController();

                        strPayPalURL += "&custom=" + Globals.HTTPPOSTEncode(intUserID.ToString());
                        strPayPalURL += "&first_name=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.FirstName);
                        strPayPalURL += "&last_name=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.LastName);
                        try
                        {
                            if (objUserInfo.Profile.Country == "United States")
                            {
                                ListEntryInfo colList = ctlList.GetListEntryInfo("Region", objUserInfo.Profile.Region);
                                strPayPalURL += "&address1=" +
                                                Globals.HTTPPOSTEncode(Convert.ToString(!String.IsNullOrEmpty(objUserInfo.Profile.Unit) ? objUserInfo.Profile.Unit + " " : "") +
                                                                       objUserInfo.Profile.Street);
                                strPayPalURL += "&city=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.City);
                                strPayPalURL += "&state=" + Globals.HTTPPOSTEncode(colList.Value);
                                strPayPalURL += "&zip=" + Globals.HTTPPOSTEncode(objUserInfo.Profile.PostalCode);
                            }
                        }
                        catch (Exception ex)
                        {
                            //issue getting user address
                            Logger.Error(ex);
                        }

                        //Return URL
                        if (settings.ContainsKey("paypalsubscriptionreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptionreturn"]))
                        {
                            strPayPalURL += "&return=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptionreturn"]);
                        }
                        else
                        {
                            strPayPalURL += "&return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request)));
                        }

                        //Cancellation URL
                        if (settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"]))
                        {
                            strPayPalURL += "&cancel_return=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptioncancelreturn"]);
                        }
                        else
                        {
                            strPayPalURL += "&cancel_return=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request)));
                        }

                        //Instant Payment Notification URL
                        if (settings.ContainsKey("paypalsubscriptionnotifyurl") && !string.IsNullOrEmpty(settings["paypalsubscriptionnotifyurl"]))
                        {
                            strPayPalURL += "&notify_url=" + Globals.HTTPPOSTEncode(settings["paypalsubscriptionnotifyurl"]);
                        }
                        else
                        {
                            strPayPalURL += "&notify_url=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(Request)) + "/admin/Sales/PayPalIPN.aspx");
                        }
                        strPayPalURL += "&sra=1"; //reattempt on failure
                    }

                    //redirect to PayPal
                    Response.Redirect(strPayPalURL, true);
                }
                else
                {
                    if ((settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"])))
                    {
                        strPayPalURL = settings["paypalsubscriptioncancelreturn"];
                    }
                    else
                    {
                        strPayPalURL = Globals.AddHTTP(Globals.GetDomainName(Request));
                    }

                    //redirect to PayPal
                    Response.Redirect(strPayPalURL, true);
                }
            }
            catch (Exception exc) //Page failed to load
            {
                Exceptions.ProcessPageLoadException(exc);
            }
        }
Beispiel #54
0
 public abstract void UpdateRole(RoleInfo role);
Beispiel #55
0
        public int AddRole(RoleInfo role)
        {
            Requires.NotNull("role", role);

            var roleId = -1;
            if (provider.CreateRole(role))
            {
                AddMessage(role, EventLogController.EventLogType.ROLE_CREATED);
                AutoAssignUsers(role);
                roleId = role.RoleID;

                ClearRoleCache(role.PortalID);
            }

            return roleId;
        }
Beispiel #56
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        // Validate form entries
        string errorMessage = ValidateForm();

        if (errorMessage == string.Empty)
        {
            try
            {
                codeName = GetSafeCodeName();
                codeName = GetUniqueCodeName(codeName);

                GroupInfo group = new GroupInfo();
                group.GroupDisplayName    = txtDisplayName.Text;
                group.GroupName           = codeName;
                group.GroupDescription    = txtDescription.Text;
                group.GroupAccess         = GetGroupAccess();
                group.GroupSiteID         = mSiteId;
                group.GroupApproveMembers = GetGroupApproveMembers();

                // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
                var user = MembershipContext.AuthenticatedUser;

                if (user != null)
                {
                    group.GroupCreatedByUserID = user.UserID;

                    if ((!RequireApproval) || (CurrentUserIsAdmin()))
                    {
                        group.GroupApprovedByUserID = user.UserID;
                        group.GroupApproved         = true;
                    }
                }

                // Save Group in the database
                GroupInfoProvider.SetGroupInfo(group);

                // Create group admin role
                RoleInfo roleInfo = new RoleInfo();
                roleInfo.DisplayName = "Group admin";
                roleInfo.RoleName    = group.GroupName + "_groupadmin";
                roleInfo.RoleGroupID = group.GroupID;
                roleInfo.RoleIsGroupAdministrator = true;
                roleInfo.SiteID = mSiteId;
                // Save group admin role
                RoleInfoProvider.SetRoleInfo(roleInfo);

                if (user != null)
                {
                    // Set user as member of group
                    GroupMemberInfo gmi = new GroupMemberInfo();
                    gmi.MemberUserID           = user.UserID;
                    gmi.MemberGroupID          = group.GroupID;
                    gmi.MemberJoined           = DateTime.Now;
                    gmi.MemberStatus           = GroupMemberStatus.Approved;
                    gmi.MemberApprovedWhen     = DateTime.Now;
                    gmi.MemberApprovedByUserID = user.UserID;

                    // Save user as member of group
                    GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                    // Set user as member of admin group role
                    UserRoleInfo userRole = new UserRoleInfo();
                    userRole.UserID = user.UserID;
                    userRole.RoleID = roleInfo.RoleID;

                    // Save user as member of admin group role
                    UserRoleInfoProvider.SetUserRoleInfo(userRole);
                }

                // Clear user session a request
                MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);
                MembershipContext.AuthenticatedUser = null;

                string culture = CultureHelper.EnglishCulture.ToString();
                if (DocumentContext.CurrentDocument != null)
                {
                    culture = DocumentContext.CurrentDocument.DocumentCulture;
                }

                // Copy document
                errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo);

                if (!String.IsNullOrEmpty(errorMessage))
                {
                    // Display error message
                    ShowError(errorMessage);
                    return;
                }

                // Create group forum
                if (CreateForum)
                {
                    CreateGroupForum(group);

                    // Create group forum search index
                    if (CreateSearchIndexes)
                    {
                        CreateGroupForumSearchIndex(group);
                    }
                }

                // Create group media library
                if (CreateMediaLibrary)
                {
                    CreateGroupMediaLibrary(group);
                }

                // Create search index for group documents
                if (CreateSearchIndexes)
                {
                    CreateGroupContentSearchIndex(group);
                }

                // Display information on success
                ShowConfirmation(GetString("group.group.createdinfo"));

                // If URL is set, redirect user to specified page
                if (!String.IsNullOrEmpty(RedirectToURL))
                {
                    URLHelper.Redirect(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL)));
                }

                // After registration message
                if ((RequireApproval) && (!CurrentUserIsAdmin()))
                {
                    ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText);

                    // Send approval email to admin
                    if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                    {
                        // Create the message
                        EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", SiteContext.CurrentSiteName);
                        if (eti != null)
                        {
                            EmailMessage message = new EmailMessage();
                            if (String.IsNullOrEmpty(eti.TemplateFrom))
                            {
                                message.From = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom");
                            }
                            else
                            {
                                message.From = eti.TemplateFrom;
                            }

                            MacroResolver resolver = MacroContext.CurrentResolver;
                            resolver.SetAnonymousSourceData(group);
                            resolver.SetNamedSourceData("Group", group);

                            message.Recipients = SendWaitingForApprovalEmailTo;
                            message.Subject    = resolver.ResolveMacros(eti.TemplateSubject);
                            message.Body       = resolver.ResolveMacros(eti.TemplateText);

                            resolver.Settings.EncodeResolvedValues = false;
                            message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText);

                            // Send the message using email engine
                            EmailSender.SendEmail(message);
                        }
                    }
                }
                else
                {
                    string groupPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                    string url       = String.Empty;

                    if (!String.IsNullOrEmpty(groupPath))
                    {
                        url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                    }
                    ShowConfirmation(String.Format(SuccessfullRegistrationText, url));
                }

                // Hide form
                if (HideFormAfterRegistration)
                {
                    plcForm.Visible = false;
                }
                else
                {
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                // Display error message
                ShowError(GetString("general.saveerror"), ex.Message, null);
            }
        }
        else
        {
            // Display error message
            ShowError(errorMessage);
        }
    }
    private void SaveRole(RoleInfo ri, string codeName, string displayName)
    {
        bool newRole = false;
        // Get object
        if (ri == null)
        {
            ri = RoleInfoProvider.GetRoleInfo(ItemID);
            if (ri == null)
            {
                ri = new RoleInfo();
                // indicate this is new role and should be redirected after safe
                newRole = true;
            }
        }

        if (ri.DisplayName != displayName)
        {
            // Refresh a breadcrumb if used in the tabs layout
            ScriptHelper.RefreshTabHeader(Page, displayName);
        }

        // Set the fields
        ri.DisplayName = displayName;
        ri.RoleName = codeName;
        ri.RoleID = ItemID;
        ri.Description = txtDescription.Text;
        ri.SiteID = mSiteId;
        ri.RoleIsDomain = chkIsDomain.Checked;

        // If group id is present then it's group role
        if (GroupID > 0)
        {
            ri.RoleGroupID = mGroupId;
            ri.RoleIsGroupAdministrator = chkIsAdmin.Checked;
        }

        RoleInfoProvider.SetRoleInfo(ri);
        ItemID = ri.RoleID;

        ShowChangesSaved();

        // if new group was created redirect to edit page
        if (newRole)
        {
            RoleID = ri.RoleID;
            RaiseOnSaved();
        }
    }
Beispiel #58
0
    /// <summary>
    /// Sends the email.
    /// </summary>
    protected void Send()
    {
        // Check "modify" permission
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Users", "Modify"))
        {
            RedirectToAccessDenied("CMS.Users", "Modify");
        }

        var sender = emailSender.Text;

        // Validate first
        if (!emailSender.IsValid() || string.IsNullOrEmpty(sender))
        {
            ShowError(GetString("general.correctemailformat"));
            return;
        }

        // Get recipients
        string groupIds = null;

        if (groupsControl != null)
        {
            groupIds = Convert.ToString(groupsControl.Value);
        }
        string userIDs = Convert.ToString(users.Value);
        string roleIDs = Convert.ToString(roles.Value);

        if (string.IsNullOrEmpty(groupIds) && string.IsNullOrEmpty(userIDs) && string.IsNullOrEmpty(roleIDs))
        {
            ShowError(GetString("massemail.norecipients"));
            return;
        }

        // Get resolver to resolve context macros
        MacroResolver resolver = MacroResolver.GetInstance();

        // Create the message
        EmailMessage message = new EmailMessage();

        message.Subject = resolver.ResolveMacros(txtSubject.Text);
        message.From    = sender;
        if (plcText.Visible)
        {
            message.Body = resolver.ResolveMacros(htmlText.ResolvedValue);
        }
        if (plcPlainText.Visible)
        {
            message.PlainTextBody = resolver.ResolveMacros(txtPlainText.Text);
        }

        // Get the attachments
        HttpPostedFile[] attachments = uploader.PostedFiles;
        foreach (HttpPostedFile att in attachments)
        {
            message.Attachments.Add(new EmailAttachment(StreamWrapper.New(att.InputStream), Path.GetFileName(att.FileName), Guid.NewGuid(), DateTime.Now, siteId));
        }

        // Check if list of roleIds contains generic role 'Everyone'
        bool containsEveryone = false;

        if (!String.IsNullOrEmpty(roleIDs))
        {
            RoleInfo roleEveryone = RoleInfoProvider.GetRoleInfo(RoleName.EVERYONE, siteId);
            if ((roleEveryone != null) && (";" + roleIDs + ";").Contains(";" + roleEveryone.RoleID + ";"))
            {
                containsEveryone = true;
            }
        }

        // Send messages using email engine
        EmailSender.SendMassEmails(message, userIDs, roleIDs, groupIds, siteId, containsEveryone);

        // Clear the form if email was sent successfully
        Clear();
        ShowConfirmation(GetString("system_email.emailsent"));
    }
Beispiel #59
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            lblError.Visible = false;
            CoreLibrary.Security.RoleController roleController = new CoreLibrary.Security.RoleController();
            int IdRole = int.Parse(Request.Params["IdRole"]);

            if (IdRole > 0)
            {
                EntRole = roleController.GetRoleByID(IdRole);
                SetDataToForm();
            }
            else
            {
                EntRole = new RoleInfo();

            }
            EntRole.EntListSiteMap = new List<ServicesLibrary.Entities.SiteMap>();

            BuidlRolesTree();
            tbxName.Focus();
        }
        tvSiteMap.Attributes.Add("onclick", "client_OnTreeNodeChecked();");
        Page.ClientScript.RegisterClientScriptInclude("role", Page.ResolveUrl("~/js/Roles.js"));

        //TreeNode tnItem = new TreeNode();
        //tnItem.

        //TreeView2.Nodes.Add(
    }
Beispiel #60
0
 public bool SaveAs(RoleInfo entity)
 {
     return(efCore.SaveAs(entity));
 }