Example #1
0
        public IActionResult Index(string member)
        {
            var memberResult = new GetMemberResult();

            if (!string.IsNullOrEmpty(member))
            {
                var memberJson = member.UrlDecode();
                memberResult = JsonConvert.DeserializeObject <GetMemberResult>(memberJson);
            }
            else
            {
                memberResult = AppSessions.GetMember();
                if (memberResult == null)
                {
                    ViewData["Message"] = "人员信息不存在!";
                    return(View());
                }
            }

            if (string.IsNullOrEmpty(memberResult.userid))
            {
                ViewData["Message"] = "人员信息无效!";
                return(View());
            }

            AppSessions.SetMember(memberResult);
            return(View(memberResult));
        }
Example #2
0
 public static MemberResult ToMemberResult(this GetMemberResult result)
 {
     if (result == null)
     {
         throw new ArgumentNullException(nameof(result));
     }
     return(new MemberResult
     {
         ErrorCode = result.ErrorCodeValue,
         ErrorMessage = result.errmsg,
         UserID = result.userid,
         Name = result.name,
         Department = result.department,
         Order = result.order,
         Position = result.position,
         Mobile = result.mobile,
         Gender = result.gender,
         Email = result.email,
         IsLeader = result.isleader,
         Avatar = result.avatar,
         TelePhone = result.telephone,
         EnglishName = result.english_name,
         Extattr = new AdvancedAPIs.AddressList.Extattr
         {
             Attrs = result.extattr.attrs.Select(m => new AdvancedAPIs.AddressList.Attr
             {
                 Name = m.name,
                 Value = m.value
             }).ToList()
         },
         Status = result.status
     });
 }
        /// <summary>
        /// 过滤成员
        /// </summary>
        /// <returns></returns>
        public JsonResult GetListByCondation()
        {
            string          condation = Request["txtSearch"].ToUpper();
            GetMemberResult member    = new GetMemberResult();

            if (WeChatCommonService.lstUser(AccountManageID) != null)
            {
                member = WeChatCommonService.lstUser(AccountManageID).Find(a => a.userid.Equals(condation, StringComparison.InvariantCultureIgnoreCase));
            }

            return(Json(new { data = member }, JsonRequestBehavior.AllowGet));
        }
Example #4
0
        public IActionResult ClockOut(GetMemberResult member)
        {
            var b = CheckClockOut(member, Enum打卡类型.签退, out var errors);

            if (b)
            {
                if (!InsertWeixinClock(Enum打卡类型.签退, member))
                {
                    errors.Add("数据库操作失败");
                }
            }
            return(View(errors));
        }
Example #5
0
        public static GetMemberResult GetMember(string userId, ref string erromsg)
        {
            GetMemberResult result = new GetMemberResult();

            try
            {
                result = MailListApi.GetMember(GetToken(), userId);
            }
            catch (ErrorJsonResultException ex)
            {
                erromsg = WxReturnCodeMessage.GetReturnMessage((int)ex.JsonResult.errcode);
            }
            return(result);
        }
 /// <summary>
 /// 当前用户是否在指定部门
 /// </summary>
 /// <param name="deptName">部门名称,可以是子部门</param>
 /// <returns>true|false</returns>
 public bool IsInDept(string deptName, WorkOption option)
 {
     if(string.IsNullOrEmpty(option.AccessToken))
         option.AccessToken = AccessTokenContainer.TryGetToken(option.CorpId, option.Secret);
     GetDepartmentMemberInfoResult membersinfo = MailListApi.GetDepartmentMemberInfo(option.AccessToken, 1, 1);
     GetMemberResult user = membersinfo.userlist.FirstOrDefault(m => m.name == CurrentUser);
     GetDepartmentListResult depts = MailListApi.GetDepartmentList(option.AccessToken);
     long landDeptId = depts.department.First(d => d.name == deptName).id;
     foreach (var deptId in user.department)
     {
         if (deptId == landDeptId)
             return true;
     }
     return false;
 }
        //public JsonResult GetBatchNotification(RequestMessageEvent_Batch_Job_Result jobResult)
        //{
        //    return Json(doJson(null), JsonRequestBehavior.AllowGet);
        //}

        public override ActionResult Get(string Id)
        {
            string strID = Request["Id"];

            if (!string.IsNullOrEmpty(strID))
            {
                GetMemberResult result = MailListApi.GetMember(GetToken(), Id);

                result.entryDate = !_localservice.Repository.Entities.Where(a => a.LillyID == result.userid).IsEmpty() ?
                                   _localservice.Repository.Entities.Where(a => a.LillyID == result.userid).First().ACTL_HIRE_DT.ToString("yyyy-MM-dd") :
                                   "1900-01-01";

                return(Json(result, JsonRequestBehavior.AllowGet));
            }

            return(Json(null, JsonRequestBehavior.AllowGet));
        }
Example #8
0
        public ActionResult GetUser(QyUserModel model)
        {
            #region 校验
            var account = GetAccount(model.corpid);
            if (account == null)
            {
                LogWriter.Info(string.Format("corpid为“{0}”的GetUser获取失败,原因:企业号不存在", model.corpid));
                return(Json(new
                {
                    errorcode = "500",
                    errormsg = "企业号不存在",
                }));
            }

            if (!ValidateAccessToken(account, model.accesstoken))
            {
                LogWriter.Info(string.Format("corpid为“{0}”的GetUser获取失败,原因:accesstoken错误", model.corpid));
                return(Json(new
                {
                    errorcode = "500",
                    errormsg = "非法访问",
                }));
            }
            #endregion

            #region 获取用户信息
            var wxFO = Formula.FormulaHelper.CreateFO <WxFO>();

            GetMemberResult userinfo = null;

            try
            {
                userinfo = wxFO.GetUser(model.corpid, model.userid);
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    errorcode = "500",
                    errormsg = ex.Message,
                }));
            }
            #endregion

            return(Json(userinfo));
        }
        public bool BeforeAddOrUpdate(GetMemberResult objModal, string ID)
        {
            //后台校验 Go here..
            bool          validate = true;
            StringBuilder errMsg   = new StringBuilder();
            string        departId = Request["departmentAll"];

            if (string.IsNullOrEmpty(objModal.userid))
            {
                validate = false;
                errMsg.Append(T("Please input UserID.<br/>"));
            }

            if (string.IsNullOrEmpty(objModal.name))
            {
                validate = false;
                errMsg.Append(T("Please input UserName.<br/>"));
            }

            if (string.IsNullOrEmpty(departId))
            {
                validate = false;
                errMsg.Append(T("Please choose Department.<br/>"));
            }

            if (string.IsNullOrEmpty(objModal.email))
            {
                validate = false;
                errMsg.Append(T("Please input Email.<br/>"));
            }

            if (string.IsNullOrEmpty(objModal.entryDate))
            {
                validate = false;
                errMsg.Append(T("Please choose entry date.<br/>"));
            }

            if (!validate)
            {
                ModelState.AddModelError("不正确的输入", errMsg.ToString());
            }

            return(validate);
        }
Example #10
0
File: WxFO.cs Project: Luyingjin/Qy
        /// <summary>
        /// 获取成员
        /// </summary>
        /// <param name="QyID">企业ID</param>
        /// <param name="userId">员工UserID。必须企业内唯一</param>
        /// <returns></returns>
        public GetMemberResult GetUser(string QyID, string userId)
        {
            GetMemberResult result = null;

            try
            {
                result = MailListApi.GetMember(GetAccessToken(QyID), userId);
            }
            catch (Exception ex)
            {
                LogWriter.Error(ex, string.Format("获取QyID为{0}的成员失败", QyID));
                result = MailListApi.GetMember(GetAccessToken(QyID, true), userId);
            }
            if (result.errcode != ReturnCode_QY.请求成功)
            {
                LogWriter.Info(string.Format("获取QyID为{0}的成员失败,原因:{1}", QyID, result.errmsg));
            }
            return(result);
        }
Example #11
0
        private bool InsertWeixinClock(Enum打卡类型 type, GetMemberResult member)
        {
            var rtId = "144.1";

            var rcId = pinhuaContext.GetNewRcId();

            var repCase = new EsRepCase
            {
                RcId          = rcId,
                RtId          = rtId,
                LstFiller     = 2,
                LstFillerName = member.name,
                LstFillDate   = DateTime.Now,
                FillDate      = DateTime.Now,
            };

            var record = new WeixinClock
            {
                ExcelServerRtid = rtId,
                ExcelServerRcid = rcId,
                ClockPlanId     = pinhuaContext.GetCurrentClockRange().ExcelServerRcid,
                ClockRangeId    = pinhuaContext.GetCurrentClockRange().RangeId,
                Clocktype       = (int?)type,
                Weixinid        = member.weixinid,
                Userid          = member.userid,
                Name            = member.name,
                Clocktime       = DateTime.Now,
            };

            pinhuaContext.EsRepCase.Add(repCase);
            pinhuaContext.WeixinClock.Add(record);

            var b = pinhuaContext.SaveChanges();

            if (b > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// 经确认,敏感信息需要裁剪调
        /// </summary>
        /// <param name="objModal"></param>
        public void CutPropertyBefaultSync2TX(GetMemberResult objModal)
        {
            var cutConfig = CommonService.GetSysConfig("AddressBookCutInfo", string.Empty);

            if (!string.IsNullOrEmpty(cutConfig))
            {
                var configDic = JsonConvert.DeserializeObject <Dictionary <string, bool> >(cutConfig);
                foreach (var pair in configDic)
                {
                    if (pair.Value == true)
                    {
                        var propertyInfo = typeof(GetMemberResult).GetProperty(pair.Key);
                        if (propertyInfo != null)
                        {
                            propertyInfo.SetValue(objModal, propertyInfo.PropertyType.IsValueType ? (object)0 : (object)string.Empty);
                        }
                    }
                }
            }
        }
Example #13
0
        private bool CheckClockOut(GetMemberResult member, Enum打卡类型 type, out List <string> errors)
        {
            var b = true;

            errors = new List <string>();
            var sType = "签退";

            if (!pinhuaContext.IsInternalNetwork())
            {
                errors.Add($"你的IP地址为 {pinhuaContext.ClientIp()} ,非公司网络");
                b = false;
            }

            var planDetail = pinhuaContext.GetCurrentClockRange();

            if (planDetail == null)
            {
                errors.Add("非工作时段");
                b = false;
            }
            else
            {
                planDetail.今天的签退区间(out var t1, out var t2);
                if (!DateTime.Now.IsBetween(t1, t2))
                {
                    errors.Add($"{planDetail.Name}的{sType}时间是 {t1.ToShortTimeString()}~{t2.ToShortTimeString()}");
                    b = false;
                }
                var r = from p in pinhuaContext.WeixinClock
                        where member.userid == p.Userid && p.Clocktime.Value.IsBetween(t1, t2) && p.Clocktype == (int)Enum打卡类型.签退
                        select p;
                if (r.Count() > 0)
                {
                    errors.Add($"当前班段 {r.FirstOrDefault().Clocktime.Value.ToShortTimeString()} 已经有过{sType}记录,请勿重复打卡!");
                    b = false;
                }
            }

            return(b);
        }
Example #14
0
        /// <summary>
        /// 更新成员(mobile/weixinid/email三者不能同时为空)
        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="userId">员工UserID。必须企业内唯一</param>
        /// <param name="name">成员名称。长度为1~64个字符</param>
        /// <param name="department">成员所属部门id列表。注意,每个部门的直属员工上限为1000个</param>
        /// <param name="position">职位信息。长度为0~64个字符</param>
        /// <param name="mobile">手机号码。必须企业内唯一</param>
        ///// <param name="tel">办公电话。长度为0~64个字符</param>
        /// <param name="email">邮箱。长度为0~64个字符。必须企业内唯一</param>
        /// <param name="weixinId">微信号。必须企业内唯一</param>
        /// <param name="enable">启用/禁用成员。1表示启用成员,0表示禁用成员</param>
        ///// <param name="gender">性别。gender=1表示男,=2表示女。默认gender=0 未选择</param>
        /// <param name="extattr">扩展属性。扩展属性需要在WEB管理端创建后才生效,否则忽略未知属性的赋值</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// accessToken和userId为必须的参数,其余参数不是必须的,可以传入null
        /// <returns></returns>
        public static WxJsonResult UpdateMember(string accessToken, GetMemberResult objEntity, int timeOut = Config.TIME_OUT)
        {
            var url  = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={0}";
            var data = new
            {
                userid     = objEntity.userid,
                name       = objEntity.name,
                department = objEntity.department,
                position   = objEntity.position,
                mobile     = objEntity.mobile,

                //最新的接口中去除了以下两个字段
                gender = objEntity.gender,
                //tel = tel,

                email    = objEntity.email,
                weixinid = objEntity.weixinid,
                extattr  = objEntity.extattr,
            };

            return(CommonJsonSend.Send <WxJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut));
        }
Example #15
0
        /// <summary>
        /// OAuthScope.snsapi_userinfo方式回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="returnUrl">用户最初尝试进入的页面</param>
        /// <returns></returns>
        public async Task <ActionResult> BaseCallback(string code, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            try
            {
                var appKey      = AccessTokenContainer.BuildingKey(_workWeixinSetting);
                var accessToken = await AccessTokenContainer.GetTokenAsync(_corpId, _corpSecret);

                //获取用户信息 测试链接:https://open.work.weixin.qq.com/wwopen/devtool/interface?doc_id=10019
                var oauthResult = await OAuth2Api.GetUserIdAsync(accessToken, code);

                var             userId = oauthResult.UserId;
                GetMemberResult result = await MailListApi.GetMemberAsync(appKey, userId);

                if (result.errcode != ReturnCode_Work.请求成功)
                {
                    return(Content("错误:" + result.errmsg));
                }

                ViewData["returnUrl"] = returnUrl;

                /* 注意:
                 * 实际适用场景,此处应该跳转到 returnUrl,不要停留在 Callback页面上。
                 * 因为当用户刷新此页面 URL 时,实际 code 等参数已失效,用户会受到错误信息。
                 */
                return(View(result));
            }
            catch (Exception ex)
            {
                return(Content("错误:" + ex.Message));
            }
        }
Example #16
0
 static public void SetMember(GetMemberResult value)
 {
     Zky.Utility.HttpContext.Current.Session.SetObjectAsJson(memberInfoKey, value);
 }
Example #17
0
        protected override DynamicMetaObject /*!*/ FallbackInvokeMember(DynamicMetaObject target /*!*/, DynamicMetaObject /*!*/[] /*!*/ args)
        {
            Expression invokeMethodExpr;

            DObject obj = target.Value as DObject;// target.Value can be something else which isn't DObject ?

            WrappedClrDynamicMetaObject wrappedTarget = null;

            bool invokeCallMethod = false;

            // Restrictions
            BindingRestrictions restrictions;
            BindingRestrictions classContextRestrictions = BindingRestrictions.Empty;
            BindingRestrictions defaultRestrictions      = BindingRestrictions.GetTypeRestriction(target.Expression, target.LimitType);

            DTypeDesc classContext = this._classContext;

            if (!ClassContextIsKnown)//ClassContext wasn't supplied during creation of binder => put it into restriction
            {
                Debug.Assert(args.Length > RealMethodArgumentCount, "Not enough arguments!");

                DynamicMetaObject dmoRuntimeClassContext = GetRuntimeClassContext(args);
                Debug.Assert(dmoRuntimeClassContext.Value == null || Types.DTypeDesc[0].IsAssignableFrom(dmoRuntimeClassContext.LimitType), "Wrong class context type!");

                classContext = (DTypeDesc)dmoRuntimeClassContext.Value;
                Debug.Assert(classContext == null || !classContext.IsUnknown, "Class context should be known at run time!");

                classContextRestrictions = BindingRestrictions.GetInstanceRestriction(dmoRuntimeClassContext.Expression, classContext);
                defaultRestrictions      = defaultRestrictions.Merge(classContextRestrictions);
            }

            if (obj == null)
            {
                if (target.Value != null && Configuration.Application.Compiler.ClrSemantics)
                {
                    // TODO: some normalizing conversions (PhpString, PhpBytes -> string):
                    target = new WrappedClrDynamicMetaObject(target);
                    obj    = target.Value as DObject;

                    wrappedTarget = target as WrappedClrDynamicMetaObject;

                    Debug.Assert(obj != null);
                }
                else
                {
                    //defaultRestrictions = defaultRestrictions.Merge(BindingRestrictions.GetTypeRestriction
                    if (target.Value == null)
                    {
                        defaultRestrictions = BindingRestrictions.GetInstanceRestriction(target.Expression, null);
                    }

                    return(DoAndReturnDefault(
                               BinderHelper.ThrowError("method_called_on_non_object", ActualMethodName),
                               defaultRestrictions));
                }
            }



            // obtain the appropriate method table
            DTypeDesc type_desc = obj.TypeDesc;

            // perform method lookup
            DRoutineDesc    method;
            GetMemberResult result = type_desc.GetMethod(new Name(ActualMethodName), classContext, out method);

            //PhpStack stack = context.Stack;

            if (result == GetMemberResult.NotFound)
            {
                if ((result = type_desc.GetMethod(DObject.SpecialMethodNames.Call, classContext, out method)) == GetMemberResult.NotFound)
                {
                    return(DoAndReturnDefault(
                               Expression.Call(Methods.PhpException.UndefinedMethodCalled, Expression.Constant(obj.TypeName), Expression.Constant(ActualMethodName)),
                               defaultRestrictions
                               ));    // TODO: alter restrictions
                }
                else
                {
                    invokeCallMethod = true;
                }
            }

            // throw an error if the method was found but the caller is not allowed to call it due to its visibility
            if (result == GetMemberResult.BadVisibility)
            {
                return(DoAndReturnDefault(
                           BinderHelper.ThrowVisibilityError(method, classContext),
                           defaultRestrictions));
            }

            if (invokeCallMethod)
            {
                InvokeCallMethod(target, args, obj, method, out restrictions, out invokeMethodExpr);

                return(new DynamicMetaObject(invokeMethodExpr, restrictions.Merge(classContextRestrictions)));
            }
            else
            {
                // we are invoking the method

                // PhpRoutine (function or method)
                if (method.Member is PhpRoutine)
                {
                    InvokePhpMethod(target, args, method.PhpRoutine, out restrictions, out invokeMethodExpr);
                    return(new DynamicMetaObject(invokeMethodExpr, restrictions.Merge(classContextRestrictions)));
                }
                // ClrMethod
                else if (method.Member is ClrMethod)
                {
                    var targetwrapper = (target.LimitType == typeof(ClrObject)) ?
                                        (DynamicMetaObject) new ClrDynamicMetaObject(target) :     // ((ClrObject)target).RealType restriction
                                        (DynamicMetaObject) new ClrValueDynamicMetaObject(target); // simple type restriction, IClrValue<T> or any .NET class inheriting PhpObject

                    InvokeClrMethod(targetwrapper, args, method, out restrictions, out invokeMethodExpr);

                    if (wrappedTarget != null)
                    {
                        return(new DynamicMetaObject(Expression.Block(wrappedTarget.WrapIt(),
                                                                      invokeMethodExpr), wrappedTarget.Restrictions.Merge(classContextRestrictions)));
                    }

                    return(new DynamicMetaObject(invokeMethodExpr, restrictions.Merge(classContextRestrictions)));
                }
            }

            throw new NotImplementedException();
        }
Example #18
0
        private DynamicMetaObject /*!*/ FallbackInvokeMember(DynamicMetaObject target /*!*/, DynamicMetaObject /*!*/[] /*!*/ args)
        {
            // determine run time values and additional restrictions:
            DTypeDesc           classContext = this._classContext;
            string              fieldName    = this._fieldName;
            BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction(target.Expression, target.LimitType); //target.Restrictions;

            int currentArg = 0;

            if (!ClassContextIsKnown)
            {
                Debug.Assert(args.Length > currentArg, "Not enough arguments!");
                Debug.Assert(args[currentArg].Value == null || Types.DTypeDesc[0].IsAssignableFrom(args[currentArg].LimitType), "Wrong class context type!");
                classContext = (DTypeDesc)args[currentArg].Value;
                Debug.Assert(classContext == null || !classContext.IsUnknown, "Class context should be known at run time!");

                restrictions = restrictions.Merge(BindingRestrictions.GetInstanceRestriction(args[currentArg].Expression, classContext));

                currentArg++;
            }
            if (IsIndirect)
            {
                Debug.Assert(args.Length > currentArg, "Not enough arguments!");
                Debug.Assert(Types.String[0].IsAssignableFrom(args[currentArg].LimitType), "Wrong field name type!");
                fieldName = (string)args[currentArg].Value;

                restrictions = restrictions.Merge(
                    BindingRestrictions.GetExpressionRestriction(
                        Expression.Equal(
                            args[currentArg].Expression,
                            Expression.Constant(fieldName, Types.String[0]))));

                currentArg++;
            }

            //
            ////Debug.Assert(!(var is PhpReference) && name != null);
            Debug.Assert(target.HasValue && target.LimitType != Types.PhpReference[0], "Target should not be PhpReference!");

            ////if (ReferenceEquals(obj, ScriptContext.SetterChainSingletonObject))
            ////{
            ////    ScriptContext.CurrentContext.AbortSetterChain(false);
            ////    return new PhpReference();
            ////}
            if (WantReference && ReferenceEquals(target.Value, ScriptContext.SetterChainSingletonObject))
            {
                // GetObjectPropertyRef:
                Func <PhpReference> abortSetterChain = () =>
                {
                    ScriptContext.CurrentContext.AbortSetterChain(false);
                    return(new PhpReference());
                };

                return(new DynamicMetaObject(
                           Expression.Call(abortSetterChain.Method),
                           BindingRestrictions.GetInstanceRestriction(target.Expression, ScriptContext.SetterChainSingletonObject)
                           ));
            }

            DObject obj;

            ////// a property of a DObject:
            if ((obj = target.Value as DObject) != null)
            {
                if (obj is ClrObject /*|| obj is IClrValue // IClrValue -> ClrValue<T> -> already in restriction */)
                {
                    // ((DObject)target).RealType == <obj>.RealType
                    restrictions = restrictions.Merge(
                        BindingRestrictions.GetInstanceRestriction(
                            Expression.Property(Expression.Convert(target.Expression, Types.DObject[0]), Properties.DObject_RealType),
                            obj.RealType));
                }

                ////    return GetObjectProperty(obj, name, caller, quiet);
                DPropertyDesc   property;
                GetMemberResult result = obj.TypeDesc.GetInstanceProperty(new VariableName(fieldName), classContext, out property);

                switch (result)
                {
                case GetMemberResult.OK:
                    ////object value = property.Get(this);
                    ////PhpReference reference = value as PhpReference;

                    if (property.Member is PhpField || property.Member is PhpVisibleProperty)
                    {
                        var          realType     = property.DeclaringType.RealType;
                        FieldInfo    realField    = (property.Member is PhpField) ? property.PhpField.RealField : null;
                        PropertyInfo realProperty = (property.Member is PhpVisibleProperty) ? ((PhpVisibleProperty)property.Member).RealProperty : null;

                        Debug.Assert(realField != null ^ realProperty != null);

                        MemberExpression getter = null;

                        if (realField != null)
                        {
                            getter = Expression.Field(Expression.Convert(target.Expression, realType), realField);
                        }
                        else if (realProperty != null)
                        {
                            getter = Expression.Property(Expression.Convert(target.Expression, realType), realProperty);
                        }


                        if (Types.PhpReference[0].IsAssignableFrom(getter.Type))
                        {
                            var reference  = Expression.Variable(Types.PhpReference[0]);
                            var assignment = Expression.Assign(reference, getter);

                            if (WantReference)
                            {
                                ////value = property.Get(this);
                                ////reference = value as PhpReference;

                                var returnLabel = Expression.Label(this._returnType);

                                ////if (reference != null && reference.IsSet)
                                ////{
                                ////    reference.IsAliased = true;
                                ////    return reference;
                                ////}

                                var isset = Expression.IfThen(
                                    Expression.Property(assignment, Properties.PhpReference_IsSet),
                                    Expression.Block(
                                        Expression.Assign(Expression.Property(reference, Properties.PhpReference_IsAliased), Expression.Constant(true)),
                                        Expression.Return(returnLabel, reference)));

                                ////// the CT property has been unset -> try to invoke __get
                                ////PhpReference get_ref = InvokeGetterRef(name, caller, out getter_exists);
                                ////if (getter_exists) return (get_ref == null ? new PhpReference() : get_ref);

                                ////if (reference == null)
                                ////{
                                ////    reference = new PhpReference(value);
                                ////    property.Set(this, reference);
                                ////}
                                ////else
                                ////{
                                ////    reference.IsAliased = true;
                                ////    reference.IsSet = true;
                                ////}
                                Func <DObject, string, DTypeDesc, PhpReference, PhpReference> notsetOperation = (self, name, caller, refrnc) =>
                                {
                                    bool getter_exists;
                                    // the CT property has been unset -> try to invoke __get
                                    PhpReference get_ref = self.InvokeGetterRef(name, caller, out getter_exists);
                                    if (getter_exists)
                                    {
                                        return(get_ref ?? new PhpReference());
                                    }

                                    Debug.Assert(refrnc != null);

                                    refrnc.IsAliased = true;
                                    refrnc.IsSet     = true;

                                    return(refrnc);
                                };

                                ////return reference;

                                return(new DynamicMetaObject(
                                           Expression.Block(this._returnType,
                                                            new[] { reference },
                                                            new Expression[] {
                                    isset,
                                    Expression.Label(returnLabel,
                                                     Expression.Call(null, notsetOperation.Method, Expression.Convert(target.Expression, Types.DObject[0]), Expression.Constant(fieldName), Expression.Constant(classContext, Types.DTypeDesc[0]), reference))
                                }),
                                           restrictions));
                            }
                            else
                            {
                                ////if (reference != null && !reference.IsSet)
                                ////{
                                ////    // the property is CT but has been unset
                                ////    if (issetSemantics)
                                ////    {
                                ////        bool handled;
                                ////        return PropertyIssetHandler(name, caller, out handled);
                                ////    }
                                ////    else return GetRuntimeField(name, caller);
                                ////}
                                ////else return value;


                                Func <DObject, string, DTypeDesc, object> notsetOperation;
                                if (_issetSemantics)
                                {
                                    notsetOperation = (self, name, caller) =>
                                    {
                                        return(PhpVariable.Dereference(self.GetRuntimeField(name, caller)));
                                    }
                                }
                                ;
                                else
                                {
                                    notsetOperation = (self, name, caller) =>
                                    {
                                        bool handled;
                                        return(PhpVariable.Dereference(self.PropertyIssetHandler(name, caller, out handled)));
                                    }
                                };
                                var value =
                                    Expression.Block(this._returnType,
                                                     new[] { reference },
                                                     Expression.Condition(
                                                         Expression.Property(assignment, Properties.PhpReference_IsSet),
                                                         Expression.Field(reference, Fields.PhpReference_Value),
                                                         Expression.Call(null, notsetOperation.Method, Expression.Convert(target.Expression, Types.DObject[0]), Expression.Constant(fieldName), Expression.Constant(classContext, Types.DTypeDesc[0]))
                                                         ));

                                return(new DynamicMetaObject(value, restrictions));
                            }
                        }
                        else
                        {
                            if (WantReference)
                            {
                                return(new DynamicMetaObject(
                                           Expression.New(Constructors.PhpReference_Object, Expression.Convert(getter, Types.Object[0])),
                                           restrictions));
                            }
                            else
                            {
                                return(new DynamicMetaObject(
                                           Expression.Call(Methods.PhpVariable.Dereference, Expression.Convert(getter, Types.Object[0])),
                                           restrictions));
                            }
                        }
                    }
                    else if (property.Member is ClrProperty)
                    {
                        var realType     = property.DeclaringType.RealType;
                        var realProperty = property.ClrProperty.RealProperty;

                        // (target.{RealObject|realValue}).<realProperty>
                        Expression value = Expression.Convert(
                            BinderHelper.ClrObjectWrapDynamic(
                                Expression.Property(
                                    BinderHelper.ClrRealObject(target, realType),
                                    realProperty)),
                            Types.Object[0]);

                        if (WantReference)
                        {
                            value = BinderHelper.MakePhpReference(value);
                        }

                        return(new DynamicMetaObject(value, restrictions));
                    }
                    else if (property.Member is ClrField)
                    {
                        var realType  = property.DeclaringType.RealType;
                        var realField = property.ClrField.FieldInfo;

                        // (target.{RealObject|realValue}).<realField>
                        Expression value = Expression.Convert(
                            BinderHelper.ClrObjectWrapDynamic(
                                Expression.Field(
                                    BinderHelper.ClrRealObject(target, realType),
                                    realField)),
                            Types.Object[0]);

                        if (WantReference)
                        {
                            value = BinderHelper.MakePhpReference(value);
                        }

                        return(new DynamicMetaObject(value, restrictions));
                    }
                    else if (property.Member is ClrEvent)
                    {
                        var clrEvent = (ClrEvent)property.Member;
                        var realType = property.DeclaringType.RealType;

                        // emit stub that Wraps event as [ ClrEventObject<handlerType>.Wrap(<SC>, <event name>, <addMethod>, <removeMethod>) ]
                        var stub = new System.Reflection.Emit.DynamicMethod(
                            string.Format("event<{0}>", fieldName),
                            Types.DObject[0], new[] { realType }, realType);
                        var il = new ILEmitter(stub);
                        clrEvent.EmitGetEventObject(
                            il,
                            new Place(null, Properties.ScriptContext_CurrentContext),
                            new IndexedPlace(PlaceHolder.Argument, 0),
                            false);
                        il.Emit(System.Reflection.Emit.OpCodes.Ret);

                        Expression value = Expression.Call(stub, BinderHelper.ClrRealObject(target, realType));
                        if (WantReference)
                        {
                            value = BinderHelper.MakePhpReference(value);
                        }
                        return(new DynamicMetaObject(value, restrictions));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }

                case GetMemberResult.NotFound:
                    if (WantReference)
                    {
                        Func <DObject, string, DTypeDesc, PhpReference> op = (self, name, caller) =>
                        {
                            PhpReference reference;
                            bool         getter_exists;

                            // search in RT fields
                            if (self.RuntimeFields != null && self.RuntimeFields.ContainsKey(name))
                            {
                                var namekey = new IntStringKey(name);
                                return(self.RuntimeFields.table._ensure_item_ref(ref namekey, self.RuntimeFields));
                            }

                            // property is not present -> try to invoke __get
                            reference = self.InvokeGetterRef(name, caller, out getter_exists);
                            if (getter_exists)
                            {
                                return((reference == null) ? new PhpReference() : reference);
                            }

                            // (no notice/warning/error thrown by PHP)

                            // add the field
                            reference = new PhpReference();
                            if (self.RuntimeFields == null)
                            {
                                self.RuntimeFields = new PhpArray();
                            }
                            self.RuntimeFields[name] = reference;

                            return(reference);
                        };

                        return(new DynamicMetaObject(
                                   Expression.Call(null, op.Method, Expression.Convert(target.Expression, Types.DObject[0]), Expression.Constant(fieldName), Expression.Constant(classContext, Types.DTypeDesc[0])),
                                   restrictions));
                    }
                    else
                    {
                        ////if (issetSemantics)
                        ////{
                        ////    OrderedHashtable<string>.Element element;
                        ////    if (RuntimeFields != null && (element = RuntimeFields.GetElement(name)) != null)
                        ////    {
                        ////        return element.Value;
                        ////    }
                        ////    else
                        ////    {
                        ////        bool handled;
                        ////        return PropertyIssetHandler(name, caller, out handled);
                        ////    }
                        ////}
                        ////else return GetRuntimeField(name, caller);

                        if (_issetSemantics)
                        {
                            Func <DObject, string, DTypeDesc, object> notsetOperation = (self, name, caller) =>
                            {
                                if (self.RuntimeFields != null)
                                {
                                    object value;
                                    if (self.RuntimeFields.TryGetValue(name, out value))
                                    {
                                        return(value);
                                    }
                                }

                                bool handled;
                                return(self.PropertyIssetHandler(name, caller, out handled));
                            };

                            return(new DynamicMetaObject(
                                       Expression.Call(Methods.PhpVariable.Dereference,
                                                       Expression.Call(null, notsetOperation.Method, Expression.Convert(target.Expression, Types.DObject[0]), Expression.Constant(fieldName), Expression.Constant(classContext, Types.DTypeDesc[0]))),
                                       restrictions));
                        }
                        else
                        {
                            return(new DynamicMetaObject(
                                       Expression.Call(
                                           Methods.PhpVariable.Dereference,
                                           Expression.Call(
                                               Expression.Convert(target.Expression, Types.DObject[0]),
                                               Methods.DObject_GetRuntimeField, Expression.Constant(fieldName), Expression.Constant(classContext, Types.DTypeDesc[0]))),
                                       restrictions));
                        };
                    }

                case GetMemberResult.BadVisibility:
                {
                    ////PhpException.PropertyNotAccessible(
                    ////    property.DeclaringType.MakeFullName(),
                    ////    name.ToString(),
                    ////    (caller == null ? String.Empty : caller.MakeFullName()),
                    ////    property.IsProtected);

                    string stringResourceKey = property.IsProtected ? "protected_property_accessed" : "private_property_accessed";

                    return(new DynamicMetaObject(
                               Expression.Block(this._returnType,
                                                Expression.Call(null, Methods.PhpException.Throw,
                                                                Expression.Constant(PhpError.Error, Types.PhpError_String[0]),
                                                                Expression.Constant(CoreResources.GetString(stringResourceKey, property.DeclaringType.MakeFullName(), fieldName, (classContext == null ? String.Empty : classContext.MakeFullName())))),
                                                WantReference ? (Expression)Expression.New(Constructors.PhpReference_Void) : Expression.Constant(null)
                                                ),
                               restrictions));
                }
                }
            }

            ////// warnings:
            ////if (!quiet) // not in isset() operator only
            ////{
            if (!_issetSemantics)
            {
                ////    if (PhpVariable.IsEmpty(var))
                ////        // empty:
                ////        PhpException.Throw(PhpError.Notice, CoreResources.GetString("empty_used_as_object"));
                ////    else
                ////        // PhpArray, string, scalar type:
                ////        PhpException.VariableMisusedAsObject(var, false);

                Action <object> error = (var) =>
                {
                    if (PhpVariable.IsEmpty(var))
                    {
                        // empty:
                        PhpException.Throw(PhpError.Notice, CoreResources.GetString("empty_used_as_object"));
                    }
                    else
                    {
                        // PhpArray, string, scalar type:
                        PhpException.VariableMisusedAsObject(var, false);
                    }
                };

                return(new DynamicMetaObject(
                           Expression.Block(this._returnType,
                                            Expression.Call(error.Method, target.Expression),
                                            WantReference ? (Expression)Expression.New(Constructors.PhpReference_Void) : Expression.Constant(null)),
                           (target.HasValue && target.Value == null) ?
                           BindingRestrictions.GetInstanceRestriction(target.Expression, null) :
                           BindingRestrictions.GetTypeRestriction(target.Expression, target.LimitType)));
            }
            ////}

            ////// property does not exist
            ////return null;
            return(new DynamicMetaObject(
                       Expression.Constant(null),
                       (target.HasValue && target.Value == null) ?
                       BindingRestrictions.GetInstanceRestriction(target.Expression, null) :
                       BindingRestrictions.GetTypeRestriction(target.Expression, target.LimitType)));
        }
        public JsonResult PostUser(GetMemberResult objModal, string Id)
        {
            //验证错误
            if (!BeforeAddOrUpdate(objModal, Id) || !ModelState.IsValid)
            {
                return(Json(GetErrorJson(), JsonRequestBehavior.AllowGet));
            }

            int[] strs = Request["departmentAll"].Split(',').Select(a => int.Parse(a)).ToArray();

            objModal.department = strs;

            objModal.userid   = objModal.userid.Trim();
            objModal.name     = objModal.name.Trim();
            objModal.position = objModal.position != null?objModal.position.Trim() : "";

            objModal.weixinid = objModal.weixinid != null?objModal.weixinid.Trim() : "";

            objModal.mobile = objModal.mobile != null?objModal.mobile.Trim() : "";

            objModal.email     = objModal.email.Trim();
            objModal.entryDate = objModal.entryDate;

            LocalSADEntity employee = new LocalSADEntity();

            employee.ChineseName  = objModal.name;
            employee.LillyID      = objModal.userid;
            employee.ACTL_HIRE_DT = Convert.ToDateTime(objModal.entryDate);
            employee.Tag          = CommonService.GetSysConfig("TagNameNewEmployee", "[]");
            employee.Gender       = Convert.ToString(objModal.gender);
            employee.Email        = objModal.email;

            string[] userList = new string[1];
            userList[0] = objModal.userid;

            //var taglist = MailListApi.GetTagList(GetToken()).taglist.Where(x => x.tagname == employee.Tag);
            var taglist = WeChatCommonService.lstTag.Where(x => x.tagname == employee.Tag);
            int tagid   = taglist.FirstOrDefault() != null?Convert.ToInt32(taglist.FirstOrDefault().tagid) : 0;

            try
            {
                if (!string.IsNullOrEmpty(Id) && Id != "0")
                {
                    MailListApi.UpdateMember(GetToken(), objModal);

                    employee.Id = !_localservice.Repository.Entities.Where(a => a.LillyID == objModal.userid).AsNoTracking().IsEmpty() ?
                                  _localservice.Repository.Entities.Where(a => a.LillyID == objModal.userid).AsNoTracking().First().Id : 0;

                    if (employee.Id == 0)
                    {
                        _localservice.Repository.Insert(employee);
                    }
                    else
                    {
                        List <string> columns = new List <string>();
                        columns.Add("ChineseName");
                        columns.Add("Gender");
                        columns.Add("Email");
                        columns.Add("ACTL_HIRE_DT");

                        _localservice.Repository.Update(employee, columns);
                    }
                }
                else
                {
                    objModal.to_invite = false;
                    MailListApi.CreateMember(GetToken(), objModal);

                    _localservice.Repository.Insert(employee);
                }
            }
            catch (ErrorJsonResultException ex)
            {
                if (ex.JsonResult.errcode == (ReturnCode)60102)
                {
                    return(ErrorNotification(null, "用户已存在"));
                }
            }
            //不超过6个月时,添加标签
            if (tagid != 0 && DateTime.Today <= (employee.ACTL_HIRE_DT.AddMonths(6)))
            {
                MailListApi.AddTagMember(GetToken(), tagid, userList);
            }

            //超过7个月时,移除标签
            if (tagid != 0 && DateTime.Today > (employee.ACTL_HIRE_DT.AddMonths(7)))
            {
                MailListApi.DelTagMember(GetToken(), tagid, userList);
            }

            //添加或更新后会清除掉缓存
            if (WeChatCommonService.lstUser != null)
            {
                cacheManager.Remove("UserItem");
            }

            return(Json(doJson(null), JsonRequestBehavior.AllowGet));
        }