Exemplo n.º 1
0
    private void OnSkipClick(PlayableDirector director)
    {
        director.Stop();
        List <RoleData> loadedRoleData = new List <RoleData>();

        foreach (var binding in director.playableAsset.outputs)
        {
            if (binding.sourceObject is MYCinemachineTrack)
            {
                SetCinemachineTrackData(binding, director);
                continue;
            }

            UnityEngine.Object bindingObj = director.GetGenericBinding(binding.sourceObject);
            if (bindingObj != null && bindingObj is RoleData)
            {
                RoleData roledata = bindingObj as RoleData;
                if (!loadedRoleData.Contains(roledata))
                {
                    loadedRoleData.Add(roledata);
                    RoleObject role = roledata.Role as RoleObject;
                    if (role != null && role.gameObject != null && roledata.TargetPosWhenSkip != Vector3.zero)
                    {
                        role.gameObject.transform.position = roledata.TargetPosWhenSkip;
                    }
                }
            }
        }
    }
Exemplo n.º 2
0
    public static string Login(string name, string pwd)
    {
        string sql = "select * from table_users where c_login_name='" + DALSecurityTool.TransferInsertField(name) + "' and c_pwd='" +
                     DALSecurityTool.TransferInsertField(SecurityFactory.GetSecurity().Encrypt(pwd)) + "'";
        ArrayList lists = FT.DAL.Orm.SimpleOrmOperator.QueryList(typeof(UserObject), sql);

        if (lists.Count == 0)
        {
            return("2");
        }
        else
        {
            UserObject   user = lists[0] as UserObject;
            RoleObject   role = FT.DAL.Orm.SimpleOrmOperator.Query <RoleObject>(user.RoleId);
            DepartMent   dept = FT.DAL.Orm.SimpleOrmOperator.Query <DepartMent>(user.DepId);
            OperatorTick ot   = new OperatorTick(user.Id, user.FullName, user.DepId, role.RoleString, pwd);
            ot.Desp1 = user.WorkId;
            ot.Desp2 = dept.ParentCode;
            ot.Desp3 = dept.DepCode;
            ot.Desp4 = dept.DepFullName;
            ot.Desp5 = user.FullName;
            ot.Desp6 = role.RoleName;
            ot.Desp7 = user.Km;
            ot.Desp8 = string.Empty;


            return(FT.Web.OperatorTick.GenerateOpTicket(ot));
        }
        //return "1";
    }
Exemplo n.º 3
0
 private void CreatAniClip(RoleObject roleObj, RoleData roleData)
 {
     if (roleData.AnimClipPath == null)
     {
         return;
     }
     foreach (var path in roleData.AnimClipPath)
     {
         string pathAni = null;
         if (roleData.RoleType == TimelineRoleType.MainPlayer || roleData.RoleType == TimelineRoleType.Player)
         {
             if (AniClipPath.ContainsKey(roleData.RoleOcc))
             {
                 pathAni = string.Format(AniClipPath[roleData.RoleOcc], path);
             }
             else
             {
                 pathAni = string.Format(AniClipPath[TimelineRoleOcc.ZhanShi], path);
             }
         }
         else
         {
             pathAni = path;
         }
         Loader.Instance.CreatAniClips(pathAni, clip =>
         {
             AnimatorOverrideController controller = roleObj.Animator.runtimeAnimatorController as AnimatorOverrideController;
             controller[clip.name] = clip;
         });
     }
 }
Exemplo n.º 4
0
    public void GetRole(RoleObject role, GameObject Manager)
    {
        this.role    = role;
        this.Manager = Manager;

        roleTaken     = false;
        hubCharacters = GameObject.FindGameObjectsWithTag("Character");
        foreach (GameObject character in hubCharacters)
        {
            hubCharacterScript = character.GetComponent <CharacterScript>();
            if (hubCharacterScript.role == role)
            {
                stats = character.GetComponent <Stats>();

                Portrait.GetComponent <CharacterScript>().LoadPlayer(hubCharacterScript);
                Portrait.GetComponent <Stats>().LoadPlayer(stats);

                SetStats();
                hubCharacterScript.isEnlisted = false;
                roleTaken = true;
                break;
            }
        }
        if (!roleTaken)
        {
            //Destroy(Portrait);
            EmptyRole();
        }
    }
Exemplo n.º 5
0
    protected void btnSure_Click(object sender, EventArgs e)
    {
        RoleObject dep = new RoleObject();

        WebFormHelper.GetDataFromForm(this, dep);
        dep.RoleString = this.GetRightString();
        if (dep.Id < 0)
        {
            if (SimpleOrmOperator.Create(dep))
            {
                WebTools.Alert("添加成功!");
            }
            else
            {
                WebTools.Alert("添加失败!");
            }
        }
        else
        {
            if (SimpleOrmOperator.Update(dep))
            {
                WebTools.Alert("修改成功!");
            }
            else
            {
                WebTools.Alert("修改失败!");
            }
        }
        WebTools.CloseSelf(this);
    }
Exemplo n.º 6
0
    public void GetCharacter(GameObject Character, GameObject Manager)
    {
        this.Character = Character;
        this.Manager   = Manager;

        hubCharacterScript = Character.GetComponent <CharacterScript>();
        stats = Character.GetComponent <Stats>();

        Portrait.GetComponent <CharacterScript>().LoadPlayer(hubCharacterScript);
        Portrait.GetComponent <Stats>().LoadPlayer(stats);

        boxCharacterScript = Portrait.GetComponent <CharacterScript>();

        role = boxCharacterScript.role;
        if (role != null)
        {
            txtRole.text = role.roleName;
        }
        else
        {
            txtRole.text = "-No Role-";
        }
        PrepareAppoint();

        txtName.text = boxCharacterScript.title + boxCharacterScript.strName;

        SetStats();
        //boxCharacterScript.isEnlisted = false;
    }
Exemplo n.º 7
0
    public override void DoEvent()
    {
        if (GameTimer.Within(farther.startTime, this.StartTime))
        {
            return;
        }
        Active    = false;
        isDoEvent = true;
        bornTime  = GameTimer.time;
        if (IsDo)
        {
            return;
        }
        IsDo = true;
        GameObject obj  = AssetDatabase.LoadAssetAtPath <GameObject>(string.Format("Assets/res_sourcefile/role/{0}.prefab", config.CallApprid));
        Role       role = obj.GetComponent <Role>();

        xpModel = ModelLoader.CreateRole(role, false);
        for (int i = 0; i < parent.Skins.Count; i++)
        {
            if (parent.Skins[i])
            {
                parent.Skins[i].SetActive(false);
            }
        }
    }
Exemplo n.º 8
0
    protected void btnSure_Click(object sender, EventArgs e)
    {
        RoleObject dep = new RoleObject();
        WebFormHelper.GetDataFromForm(this, dep);
        dep.RoleString=this.GetRightString();
        if(dep.Id<0)
        {
            if (SimpleOrmOperator.Create(dep))
            {
                WebTools.Alert("添加成功!");
            }
            else
            {
                WebTools.Alert("添加失败!");

            }
        }
        else
        {
            if (SimpleOrmOperator.Update(dep))
            {
                WebTools.Alert("修改成功!");
            }
            else
            {
                WebTools.Alert("修改失败!");

            }

        }
        WebTools.CloseSelf(this);
    }
Exemplo n.º 9
0
    protected float MaxDistance = 1000;   //最大追踪距离

    public CActionEffect(ZWActionEvent host, string path)
    {
        this.sourcePath = path;
        this.host       = host;
        this.parent     = host.parent;
        this.Angle      = host.Angle;
        this.Offset     = host.Offset;
    }
Exemplo n.º 10
0
 public override void OnGraphStart(Playable playable)
 {
     if (!EditorApplication.isPlaying)
     {
         return;
     }
     roleObj = World.Instance.GetRoleObj(animationPlayable.Role);
 }
Exemplo n.º 11
0
 public void RoleInfo(RoleObject role)
 {
     txtRoleName.text = role.roleName;
     txtRoleDesc.text = role.desc;
     txtHp.text       = "Hp: +" + role.maxHp;
     txtDef.text      = "Def: +" + role.def;
     txtDex.text      = "Dex: +" + role.dex;
 }
Exemplo n.º 12
0
 public void Show(DialogueUIData data)
 {
     bubbleText.text = data.Dialogue;
     ShowTime        = data.Time;
     showedTime      = 0;
     gameObject.SetActive(true);
     this.roleObj = World.Instance.GetAutoLoadRole(data.Id);
 }
Exemplo n.º 13
0
 public override void OnBehaviourStart(Playable playable)
 {
     roleObj       = World.Instance.GetRoleObj(osBehaviour.role);
     originalScale = roleObj.transform.localScale.x;
     if (!osBehaviour.isSetGradually)
     {
         roleObj.gameObject.transform.localScale = UnityEngine.Vector3.one * osBehaviour.scale;
     }
 }
Exemplo n.º 14
0
 public override void OnGraphStart(Playable playable)
 {
     if (!EditorApplication.isPlaying)
     {
         return;
     }
     roleObj = World.Instance.GetRoleObj(movePlayable.roleData);
     roleNav = roleObj.GetComponent <NavMeshAgent>();
 }
Exemplo n.º 15
0
    public void SetRole(RoleObject role)
    {
        //if (oldCharacter != null) {     //Om det fanns en karaktär på rollen man väljer ändras den till citizenRole
        //    oldCharacter.GetComponent<CharacterScript>().role = citizenRole;
        //}
        CharacterToAlter.GetComponent <RoleScript>().ChangeRole(role); //Ändrar rollen på den man klickade på till den nya rollen

        CreateCharacterList();                                         //Tar tillbaka så att man ser karaktärena igen
    }
Exemplo n.º 16
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("删除"))
        {
            RoleObject roleObj = target as RoleObject;
            World.Instance.RemoveRole(roleObj);
        }
    }
Exemplo n.º 17
0
 public override void OnGraphStart(Playable playable)
 {
     if (!EditorApplication.isPlaying)
     {
         return;
     }
     Loader.Instance.CreatAction(actionPlayable.ActionName, actionConfig => {
         roleAction = actionConfig;
     });
     roleObj = World.Instance.GetRoleObj(actionPlayable.Role);
 }
 public void ChangeStats(RoleObject role, int modifier)   //Ändrar stats för karaktären
 {
     if (stats == null)
     {
         stats = GetComponent <Stats>();
     }
     stats.maxHp += (role.maxHp * modifier);
     stats.hp    += (role.maxHp * modifier);
     stats.def   += (role.def * modifier);
     stats.dex   += (role.dex * modifier);
 }
Exemplo n.º 19
0
    public override void OnBehaviourStart(Playable playable)
    {
        //return;
        roleEffectBehaviour = behaviour as RoleEffectBehaviour;
        RoleObject obj = World.Instance.GetRoleObj(roleEffectBehaviour.roleData);

        if (obj != null)
        {
            var renders = obj.gameObject.GetComponentsInChildren <SkinnedMeshRenderer>();
            XYCoroutineEngine.Execute(DoDissolveEffect(renders.ToList()));
        }
    }
Exemplo n.º 20
0
 public override void OnPlayableCreate(Playable playable)
 {
     base.OnPlayableCreate(playable);
     vmOperatePlayable = behaviour as VMOperateBehaviour;
     cinemachineCamera = vmOperatePlayable.cinemachineCamera;
     priority          = vmOperatePlayable.priority;
     roleData          = vmOperatePlayable.roleData;
     if (roleData != null)
     {
         roleObj = World.Instance.GetRoleObj(roleData);
     }
 }
Exemplo n.º 21
0
        public RoleObject GetByRoleId(Guid ID)
        {
            var db   = new eTrainingScheduleEntities();
            var list = db.sp_tbl_Role_GetByRoleId(ID);

            foreach (var item in list)
            {
                RoleObject obj = new RoleObject();
                obj.RoleId = item.RoleId; obj.RName = item.RName; obj.Isdeleted = item.Isdeleted;
                return(obj);
            }
            return(null);
        }
Exemplo n.º 22
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         this.InitTree();
         if (Request.Params["id"] != null)
         {
             RoleObject dep = SimpleOrmOperator.Query <RoleObject>(Convert.ToInt32(Request.Params["id"]));
             WebFormHelper.SetDataToForm(this, dep);
             this.InitCheckNode(dep.RoleString);
         }
     }
 }
Exemplo n.º 23
0
 public void ClearRole()
 {
     foreach (RoleData roleData in autoLoadRoles.Keys)
     {
         RoleObject roleObj = autoLoadRoles[roleData];
         //roles.Remove(roleData);
         if (roleObj)
         {
             GameObject.Destroy(roleObj.gameObject);
         }
     }
     autoLoadRoles.Clear();
 }
Exemplo n.º 24
0
 public override void StopEvent()
 {
     base.StopEvent();
     for (int i = 0; i < parent.Skins.Count; i++)
     {
         if (parent.Skins[i])
         {
             parent.Skins[i].SetActive(true);
         }
     }
     GameObject.DestroyImmediate(xpModel.gameObject);
     xpModel = null;
 }
Exemplo n.º 25
0
    public static List <ZWActionEvent> CreateEffect <T>(RoleObject ro, ZWAction farther, Action.ActionEvent aevent, out float Duration, SkillContext context = null, int index = 0, params object[] args) where T : ZWActionEvent
    {
        Duration = 0;
        List <ZWActionEvent> list = new List <ZWActionEvent>();
        T result = null;

        SkillContext.FireBoll fireBoll = null;
        int count = aevent.Child.Length + 1;
        int wave  = 1;

        if (context != null)
        {
            if (aevent.EventType == ActionEventType.FIREBALL)
            {
                if (context.targets.Count > index)
                {
                    fireBoll = context.targets[index];
                }
            }
            wave = context.Wave;
        }

        for (int i = 0; i < wave; i++)
        {
            for (int j = 0; j < count; j++)
            {
                if (args == null)
                {
                    result = Activator.CreateInstance(typeof(T)) as T;
                }
                else
                {
                    result = Activator.CreateInstance(typeof(T), args) as T;
                }

                Action.Childs child = null;

                if (j > 0 && aevent.Child.Length > j - 1)
                {
                    child = aevent.Child[j - 1];
                }

                result.config   = aevent;
                result.fireBoll = fireBoll;
                float time = result.Initialize(ro, farther, child, aevent.Duration * i);
                Duration = Mathf.Max(time, Duration);
                list.Add(result);
            }
        }
        return(list);
    }
Exemplo n.º 26
0
        public List <RoleObject> GetAll()
        {
            List <RoleObject> lst = new List <RoleObject>();
            var db   = new eTrainingScheduleEntities();
            var list = db.sp_tbl_Role_GetAll();

            foreach (var item in list)
            {
                RoleObject ob = new RoleObject();
                ob.RoleId = item.RoleId; ob.RName = item.RName; ob.Isdeleted = item.Isdeleted;
                lst.Add(ob);
            }
            return(lst);
        }
Exemplo n.º 27
0
        public RoleObject GetAllJoin()
        {
            RoleObject lst  = new RoleObject();
            var        db   = new eTrainingScheduleEntities();
            var        list = db.sp_tbl_Role_GetAll();

            foreach (var item in list)
            {
                RoleObject ob = new RoleObject();
                ob.RoleId = item.RoleId; ob.RName = item.RName; ob.Isdeleted = item.Isdeleted;
                return(lst);
            }
            return(null);
        }
Exemplo n.º 28
0
 private void OnRoleLoadComplete(RoleObject obj)
 {
     if (model != null)
     {
         GameObject.Destroy(model.gameObject);
     }
     obj.gameObject.transform.SetParent(modelParent.transform);
     obj.transform.localPosition = Vector3.zero;
     obj.transform.localScale    = Vector3.one;
     obj.transform.localRotation = Quaternion.Euler(Vector3.zero);
     obj.modelLayer = XYDefines.Layer.TimelineUI;
     TimelineManager.Instance.SetLayerRecursively(obj.gameObject, XYDefines.Layer.TimelineUI);
     model = obj;
 }
Exemplo n.º 29
0
        public ActionResult Edit(System.Guid Id)
        {
            RoleObject objRo = new RoleObject();

            objRo = new RoleBCL().GetByRoleId(Id);
            //objPe.FeaJoin = new FeaIdBCL().GetByFeaId(objPe.FeaId);
            List <RoleObject> LisRo = new RoleBCL().GetAll();

            /*FeaIdObject objFeat = LisFeat.Single(x => x.FeaId.Equals(0));
             * LisFeat.Remove(objFeat);*/
            ViewBag.ListRole = LisRo;

            return(View(objRo));
        }
Exemplo n.º 30
0
 public void SetParentTransform(Transform ts)
 {
     if (ts == null)
     {
         return;
     }
     if (this.gameObject)
     {
         this.gameObject.transform.parent = ts;
     }
     SetPosition(Vector3.zero);
     SetRotation(Vector3.zero);
     SetScale(Vector3.one);
 }
 public void LoadPlayer(CharacterScript data)
 {
     role       = data.role;
     strName    = data.strName;
     id         = data.id;
     rangedId   = data.rangedId;
     healingId  = data.healingId;
     combatId   = data.combatId;
     clothId    = data.clothId;
     headId     = data.headId;
     inventory  = data.inventory;
     inHospital = data.inHospital;
     isEnlisted = data.isEnlisted;
 }
        /// <summary>
        /// Create a new role from detail panel and return the id.
        /// The method needs to create a new entity and set control values to its properties then persist it.
        /// </summary>
        /// <returns>returns the id of new created role.</returns>
        public override string Create()
        {
            this.ValidateInput(Guid.Empty);

            RoleObject roleObject = new RoleObject
            {
                RoleName = this.TextBoxName.Text,
                Description = this.TextBoxDescription.Text,
                Domain = authenticationContext.TempVariables["Domain.Value"] as string,
                Predefined = false
            };

            using (TransactionScope ts = new TransactionScope())
            {
                roleApi.Save(roleObject);
                permissionApi.SetRolePermissions(roleObject.RoleId, this.PermissionTreeView.CheckedValues);
                ts.Complete();
            }

            return roleObject.RoleId.ToString();
        }
        public void GetRolesStory()
        {
            _story = new Story("Get a Role By IRoleApi");

            IDictionary<Guid, RoleObject> _objects;
            _story.AsA("User")
              .IWant("to be able to get a Role")
              .SoThat("I can do something");

            _story.WithScenario("Get a Role By IRoleApi  ")
                .Given("Create several new roles", () =>
                {
                    IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
                    OrganizationTypeObject department = new OrganizationTypeObject { Name = "department", Domain = "Inc", Description = "department-desc" };
                    organizationApi.Save(department);
                    createdOrganizationTypeIds.Add(department.OrganizationTypeId);

                    OrganizationTypeObject customer = new OrganizationTypeObject { Name = "customer", Domain = "Customer", Description = "customer-desc" };
                    organizationApi.Save(customer);
                    createdOrganizationTypeIds.Add(customer.OrganizationTypeId);

                    powerAdministrators = new RoleObject { RoleName = "powerAdministrators", Description = "powerAdministrators-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId }, Predefined = true };
                    business = new RoleObject { RoleName = "business", Description = "business-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId } };
                    customers = new RoleObject { RoleName = "customers", Description = "customers-desc", OrganizationTypeIds = new Collection<Guid> { customer.OrganizationTypeId } };

                })
                .When("I save this member", () =>
                {
                    roleApi.Save(powerAdministrators);
                    roleApi.Save(business);
                    roleApi.Save(customers);

                    createdRoleIds.Add(powerAdministrators.RoleId);
                    createdRoleIds.Add(business.RoleId);
                    createdRoleIds.Add(customers.RoleId);

                })
                .Then("I get these roles", () =>
                {
                    powerAdministrators1 = roleApi.Get(powerAdministrators.RoleId);

                    powerAdministrators1.ShouldEqual(powerAdministrators);

                    business1 = roleApi.Get(business.RoleName);

                    business1.ShouldEqual(business);

                    _objects = roleApi.BulkGet(createdRoleIds);

                    _objects[powerAdministrators.RoleId].ShouldEqual(powerAdministrators1);

                    roleApi.Delete(customers.RoleId);

                    _objects = roleApi.BulkGet(createdRoleIds);

                    _objects.ContainsKey(customers.RoleId).ShouldBeFalse();

                    createdRoleIds.Add(new Guid());

                    _objects = roleApi.BulkGet(createdRoleIds);

                    createdRoleIds.Count.ShouldEqual(_objects.Count + 2);

                });

            this.CleanUp();
        }
 /// <summary>
 /// Save role business object. 
 /// It does create/update based on roleObject.Id. If id is empty, the method will create a new role object.
 /// If the specified id is invalid, the method will throw an exception.       
 /// </summary>
 /// <param name="roleObject">role object</param>
 /// <returns>returns id of the accessing role.</returns>
 public string SaveJson(RoleObject roleObject)
 {
     if (roleObject == null)
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidRoleID + "{0}", "Role Object cannot be null"));
     try
     {
         roleApi.Save(roleObject);
         return roleObject.RoleId.ToString();
     }
     catch (ArgumentException ex)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message));
     }
     catch (BadRequestException bad)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message));
     }
     catch (FormatException formatEx)
     {
         throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message));
     }
     catch (Exception exp)
     {
         Logger.Instance(this).Error(exp);
         throw new InternalServerErrorException();
     }
 }
        /// <summary>
        /// Save role business object. 
        /// It does create/update based on roleObject.Id. If id is empty, the method will create a new role object.
        /// If the specified id is invalid, the method will throw an exception.
        /// </summary>
        /// <param name="roleObject">role object</param>
        /// <exception cref="ValidationException">Role name existed in system</exception>
        /// <exception cref="ArgumentException">Role id is invalid</exception>
        public void Save(RoleObject roleObject)
        {
            Kit.NotNull(roleObject, "roleObject");

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                try
                {
                    Role role = null;
                    using (ValidationScope validationScope = new ValidationScope(true))
                    {
                        var duplicateRoleNameCount = (from r in ctx.Roles
                                                      where r.ApplicationId == this.authenticationContext.ApplicationId
                                                         && r.RoleName == roleObject.RoleName
                                                         && r.Domain == roleObject.Domain
                                                         && r.RoleId != roleObject.RoleId
                                                      select r).Count();
                        if (duplicateRoleNameCount > 0)
                            validationScope.Error(Resources.ExistedRoleName, roleObject.RoleName);

                        if (roleObject.RoleId == Guid.Empty)
                        {
                            role = new Role()
                            {
                                ApplicationId = this.authenticationContext.ApplicationId,
                            };

                            ctx.Roles.InsertOnSubmit(role);
                        }
                        else
                        {
                            role = ctx.Roles.FirstOrDefault(r => r.RoleId == roleObject.RoleId);
                            if (role == null)
                                validationScope.Error(Resources.InvalidRoleID, "roleObject");

                            base.RemoveCache(FormatRoleNameCacheKey(role.RoleName));
                            base.RemoveCache(roleObject.RoleId);
                        }
                    }

                    role.Domain = roleObject.Domain;
                    role.RoleName = roleObject.RoleName;
                    role.LoweredRoleName = roleObject.RoleName.ToLowerInvariant();
                    role.Description = roleObject.Description;
                    role.LastUpdatedDate = DateTime.UtcNow;
                    role.Predefined = roleObject.Predefined;

                    ctx.SubmitChanges();
                    roleObject.RoleId = role.RoleId;
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (ValidationException)
                {
                    throw;
                }
                catch (Exception exp)
                {
                    Logger.Instance(this).Error(exp);
                    throw;
                }
            }
        }
        /// <summary>
        /// Get role id by role id.
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public RoleObject Get(Guid roleId)
        {
            RoleObject roleObject = base.GetCacheObject<RoleObject>(roleId);
            if (roleObject != null) return roleObject;

            try
            {
                using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
                {
                    Role role = ctx.Roles.FirstOrDefault(r => r.RoleId == roleId);
                    if (role == null) return null;

                    roleObject = new RoleObject()
                    {
                        RoleId = role.RoleId,
                        RoleName = role.RoleName,
                        Description = role.Description,
                        Predefined = role.Predefined,
                        Domain = role.Domain
                    };

                    base.AddCache(roleId, roleObject);
                    return roleObject;
                }
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                throw;
            }
        }
 /// <summary>
 /// Save role business object. 
 /// It does create/update based on roleObject.Id. If id is empty, the method will create a new role object.
 /// If the specified id is invalid, the method will throw an exception.
 /// </summary>
 /// <param name="roleObject">role object</param>
 /// <returns>returns id of the accessing role.</returns>
 public string SaveXml(RoleObject roleObject)
 {
     return SaveJson(roleObject);
 }
        public void Setup()
        {
            string serviceUri1 = @"/OrganizationService.svc/json/SaveOrganizationType";
            string serviceUriorganization = @"/OrganizationService.svc/json/SaveOrganization";

            organizationTypeObject = new OrganizationTypeObject() { Name = "Manager" + Guid.NewGuid().ToString().Substring(0, 5), Domain = "Department", Description = "department-desc", LastUpdatedDate = System.DateTime.Now };
            string organizationTypeId = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUri1, userName, password, TestServicesHelper.PostDataByJsonWithContent, TestServicesHelper.GenerateJsonByType(organizationTypeObject), null).Replace("\"", "");

            organizationTypeObject.OrganizationTypeId = new Guid(organizationTypeId);
            organizationObject = new OrganizationObject()
            {
                OrganizationCode = "sh021" + Guid.NewGuid().ToString().Substring(0, 5),
                OrganizationName = "sh-department" + Guid.NewGuid().ToString().Substring(0, 5),
                OrganizationTypeId = organizationTypeObject.OrganizationTypeId,
                Status = OrganizationStatus.Enabled,
                Description = "sh-desc",
                CreatedDate = System.DateTime.Now,
                LastUpdatedDate = System.DateTime.Now

            };

            string organizationId = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUriorganization, userName, password, TestServicesHelper.PostDataByJsonWithContent, TestServicesHelper.GenerateJsonByType(organizationObject), null).Replace("\"", "");
            organizationObject.OrganizationId = new Guid(organizationId);

            common = new UserObject
            {
                UserName = "******" + Guid.NewGuid().ToString().Substring(0, 5),
                DisplayName = "CommonUser" + Guid.NewGuid().ToString().Substring(0, 5),
                LastActivityDate = DateTime.Now,
                LastLockoutDate = DateTime.Now,
                LastLoginDate = DateTime.Now,
                LastPasswordChangedDate = DateTime.Now,
                CreationDate = System.DateTime.Now,
                OrganizationId = organizationObject.OrganizationId,
                LastUpdatedDate = DateTime.Now,
                PasswordQuestion = pwdAns
            };
            string serviceUri = string.Format("/MembershipService.svc/json/Save");

            string content = TestServicesHelper.GenerateJsonByType(common);
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("password", pwd);
            parameters.Add("passwordAnswer", pwdAns);

            string id = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUri, userName, password, TestServicesHelper.PostDataByJsonWithContent, content, parameters).Replace("\"", "");
            common.UserId = new Guid(id);

            super = new RoleObject { RoleName = "super", Domain = "Department", Description = "super role" };
            string serviceUriRole = @"/RoleService.svc/json/Save";

            string contentRole = TestServicesHelper.GenerateJsonByType(super);
            string idRole = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUriRole, userName, password, TestServicesHelper.PostDataByJsonWithContent, contentRole, null).Replace("\"", "");
            super.RoleId = new Guid(idRole);
        }
        public void SetUserToRoleAndUpdateStory()
        {
            _story = new Story("Create a Role By IRoleApi");
            IPlatformConfiguration platformConfiguration = SpringContext.Current.GetObject<IPlatformConfiguration>();
            IMembershipApi membershipApi = SpringContext.Current.GetObject<IMembershipApi>();
            IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
            UserObject eunge = null;
            //IDictionary<Guid, RoleObject> _objects;
            _story.AsA("User")
              .IWant("to be able to set User to  Role")
              .SoThat("I can do something");

            _story.WithScenario("Set existing User to  an Existing Role By IRoleApi  ")
                .Given("Create several new role", () =>
                                                      {
                                                          OrganizationTypeObject department =
                                                              new OrganizationTypeObject
                                                                  {
                                                                      Name = "department",
                                                                      Domain = "Inc",
                                                                      Description = "department-desc"
                                                                  };
                                                          organizationApi.Save(department);
                                                          createdOrganizationTypeIds.Add(department.OrganizationTypeId);
                                                          powerAdministrators = new RoleObject
                                                                                    {
                                                                                        RoleName = "powerAdministrators",
                                                                                        Description =
                                                                                            "powerAdministrators-desc",
                                                                                        OrganizationTypeIds =
                                                                                            new Collection<Guid>
                                                                                                {
                                                                                                    department.
                                                                                                        OrganizationTypeId
                                                                                                }
                                                                                    };
                                                          business = new RoleObject
                                                                         {
                                                                             RoleName = "business",
                                                                             Description = "business-desc",
                                                                             OrganizationTypeIds =
                                                                                 new Collection<Guid> { department.OrganizationTypeId }
                                                                         };
                                                          roleApi.Save(powerAdministrators);
                                                          roleApi.Save(business);
                                                          createdRoleIds.AddRange(new Guid[]
                                                                                      {
                                                                                          powerAdministrators.RoleId,
                                                                                          business.RoleId
                                                                                      });

                                                      })
                .And("Create User", () =>
                                        {
                                            eunge = new UserObject
                                           {
                                               OrganizationId = platformConfiguration.Organization.OrganizationId,
                                               UserName = "******",
                                               DisplayName = "Eunge",
                                               Email = "*****@*****.**",
                                               Comment = "The author of BaoJianSoft.",
                                               IsApproved = true
                                           };

                                            membershipApi.Save(eunge, "password1", null);
                                            createdUserIds.Add(eunge.UserId);
                                        })
                .When("Set User to the Roles", () =>
                                                   {
                                                       roleApi.SetUserToRoles(eunge.UserId, new Guid[] { powerAdministrators.RoleId });
                                                       roleApi.SetUserToRoles(eunge.UserId, new Guid[] { powerAdministrators.RoleId, business.RoleId });
                                                       typeof(ArgumentException).ShouldBeThrownBy(() => roleApi.SetUserToRoles(new Guid(), new Guid[] { powerAdministrators.RoleId }));
                                                   })
                .Then("I get the relationship among these roles and User", () =>
                             {
                                 roleApi.FindByUserId(eunge.UserId).Count().ShouldEqual(2);
                                 roleApi.IsUserInRole(eunge.UserId, powerAdministrators.RoleId).ShouldBeTrue();
                                 roleApi.IsUserInRole(eunge.UserId, business.RoleId).ShouldBeTrue();
                             });

            _story.WithScenario("Update an Existing Role By IRoleApi  ")
                .Given("an existing Role", () => { })
                .When("Update the Role's Role Name", () => { powerAdministrators.RoleName = "NotAdmin"; roleApi.Save(powerAdministrators); })
                .Then("I still can get the Role by UserId",()=>
                                                               {
                                                                   var temp = roleApi.FindByUserId(eunge.UserId).Where(x => x.RoleName == powerAdministrators.RoleName);
                                                                   if(temp is RoleObject)
                                                                       ((RoleObject)temp).RoleName.ShouldEqual("NotAdmin");
                                                               });
            _story.WithScenario("Delete an Existing Role which assoicate with an existing User By IRoleApi  ")
                .Given("an existing Role", () => { })
                .When("Delete the Role", () => { roleApi.Delete(powerAdministrators.RoleId); })
                .Then("I  can get noting by userId", () =>
                {
                    powerAdministrators1 = roleApi.FindByUserId(eunge.UserId).Where(x => x.RoleName == powerAdministrators1.RoleName) as RoleObject;
                    powerAdministrators1.ShouldBeNull();
                });

            this.CleanUp();
        }
        /// <summary>
        /// Create a role into specified application.
        /// </summary>
        /// <param name="applicationId"></param>
        /// <param name="roleObject"></param>
        protected static void CreateRole(Guid applicationId, RoleObject roleObject)
        {
            Kit.NotNull(roleObject, "roleObject");

            try
            {
                using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
                {
                    Role role = new Role()
                    {
                        ApplicationId = applicationId,
                        RoleName = roleObject.RoleName,
                        LoweredRoleName = roleObject.RoleName.ToLowerInvariant(),
                        Domain = roleObject.Domain,
                        Description = roleObject.Description,
                        LastUpdatedDate = DateTime.UtcNow,
                        Predefined = true
                    };

                    ctx.Roles.InsertOnSubmit(role);
                    ctx.SubmitChanges();

                    roleObject.RoleId = role.RoleId;
                }
            }
            catch (ValidationException)
            {
                throw;
            }
            catch (Exception exp)
            {
                Logger.Instance(typeof(CredentialInstaller)).Error(exp);
                throw;
            }
        }
        public void SaveRolesStory()
        {
            _story = new Story("Create a Role By IRoleApi");

            //IDictionary<Guid, RoleObject> _objects;
            _story.AsA("User")
              .IWant("to be able to create a Role")
              .SoThat("I can do something");

            _story.WithScenario("create a Role By IRoleApi including Create the Same Name;Same Domain; Same Description; Empty Name; ")
                .Given("Create several new roles", () =>
                {
                    IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
                    OrganizationTypeObject department = new OrganizationTypeObject { Name = "department", Domain = "Inc", Description = "department-desc" };
                    organizationApi.Save(department);
                    createdOrganizationTypeIds.Add(department.OrganizationTypeId);

                    OrganizationTypeObject customer = new OrganizationTypeObject { Name = "customer", Domain = "Customer", Description = "customer-desc" };
                    organizationApi.Save(customer);
                    createdOrganizationTypeIds.Add(customer.OrganizationTypeId);

                    powerAdministrators = new RoleObject { RoleName = "", Description = "powerAdministrators-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId }, Predefined = true };
                    business = new RoleObject { RoleName = "business", Description = "business-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId } };
                    customers = new RoleObject { RoleName = "customers", Description = "customers-desc", OrganizationTypeIds = new Collection<Guid> { customer.OrganizationTypeId } };

                })
                .When("I save this member", () =>
                {
                    //roleApi.Save(powerAdministrators);
                    roleApi.Save(business);
                    roleApi.Save(customers);

                    //createdRoleIds.Add(powerAdministrators.RoleId);
                    createdRoleIds.Add(business.RoleId);
                    createdRoleIds.Add(customers.RoleId);

                })
                .Then("I get these roles", () =>
                {
                   typeof(ArgumentNullException).ShouldBeThrownBy(()=>roleApi.Save(powerAdministrators));

                });

            this.CleanUp();
        }
        public void DeleteRolesStory()
        {
            _story = new Story("Delete a Role By IRoleApi");

            _story.AsA("User")
              .IWant("to be able to delete a Role")
              .SoThat("I can re-create");

            _story.WithScenario("Delete a Role By IRoleApi with correct Role Id ")
                .Given("Create several new roles", () =>
                                                {
                                                    IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
                                                    OrganizationTypeObject department = new OrganizationTypeObject { Name = "department", Domain = "Inc", Description = "department-desc" };
                                                    organizationApi.Save(department);
                                                    createdOrganizationTypeIds.Add(department.OrganizationTypeId);

                                                    OrganizationTypeObject customer = new OrganizationTypeObject { Name = "customer", Domain = "Customer", Description = "customer-desc" };
                                                    organizationApi.Save(customer);
                                                    createdOrganizationTypeIds.Add(customer.OrganizationTypeId);

                                                    powerAdministrators = new RoleObject { RoleName = "powerAdministrators", Description = "powerAdministrators-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId }, Predefined = true };
                                                    business = new RoleObject { RoleName = "business", Description = "business-desc", OrganizationTypeIds = new Collection<Guid> { department.OrganizationTypeId } };
                                                    customers = new RoleObject { RoleName = "customers", Description = "customers-desc", OrganizationTypeIds = new Collection<Guid> { customer.OrganizationTypeId } };

                                                })
                .When("I save this member", () =>
                                                {
                                                    roleApi.Save(powerAdministrators);
                                                    roleApi.Save(business);
                                                    roleApi.Save(customers);

                                                    createdRoleIds.Add(powerAdministrators.RoleId);
                                                    createdRoleIds.Add(business.RoleId);
                                                    createdRoleIds.Add(customers.RoleId);

                                                })
                .Then("I Delete these roles, I cannot get it any more", () =>
                                                  {
                                                      roleApi.Delete(powerAdministrators.RoleId);

                                                      roleApi.Get(powerAdministrators.RoleId).ShouldBeNull();

                                                      roleApi.Delete(new Guid());

                                                  });

            this.CleanUp();
        }
        /// <summary>
        /// Update an existed organization type from detail panel.
        /// The method needs to load an existed entity by specified id and set control values to overwrite its original properties then persist it.
        /// </summary>
        /// <param name="entityId"></param>
        public override void Update(string entityId)
        {
            Guid roleId = new Guid(entityId);
            this.ValidateInput(roleId);

            RoleObject roleObject = new RoleObject { RoleId = roleId };
            roleObject.RoleName = this.TextBoxName.Text;
            roleObject.Description = this.TextBoxDescription.Text;
            roleObject.Domain = authenticationContext.TempVariables["Domain.Value"] as string;

            using (TransactionScope ts = new TransactionScope())
            {
                roleApi.Save(roleObject);
                permissionApi.SetRolePermissions(roleObject.RoleId, this.PermissionTreeView.CheckedValues);
                ts.Complete();
            }
        }