/// <summary>
        /// 获取Api行为的特性过滤器     
        /// </summary>
        /// <param name="action">Api行为</param>
        /// <returns></returns>
        private static IEnumerable<IFilter> GetActionFiltersNoCached(ApiAction action)
        {
            var methodAttributes = action.GetMethodFilterAttributes();

            var classAttributes = action.GetClassFilterAttributes()
                .Where(filter => filter.AllowMultiple || methodAttributes.Any(mFilter => mFilter.TypeId == filter.TypeId) == false);

            var methodFilters = methodAttributes.Select(fiter => new
            {
                Filter = fiter,
                Level = (fiter is IAuthorizationFilter) ? FilterLevels.Authorization : FilterLevels.Method
            });

            var classFilters = classAttributes.Select(fiter => new
            {
                Filter = fiter,
                Level = (fiter is IAuthorizationFilter) ? FilterLevels.Authorization : FilterLevels.Class
            });

            var filters = classFilters.Concat(methodFilters)
                .OrderBy(filter => filter.Level)
                .ThenBy(filter => filter.Filter.Order)
                .Select(filter => filter.Filter);

            return filters;
        }
        /// <summary>
        /// 获取服务行为的特性过滤器   
        /// 并进行属性注入
        /// </summary>
        /// <param name="fastAction">服务行为</param>
        /// <returns></returns>
        public override IEnumerable<IFilter> GetActionFilters(ApiAction fastAction)
        {
            var filters = base.GetActionFilters(fastAction);
            var lifetimeScope = this.dependencyResolver.CurrentLifetimeScope;

            if (lifetimeScope == null)
            {
                return filters;
            }
            return filters.Select(filter => lifetimeScope.InjectProperties(filter));
        }
Ejemplo n.º 3
0
        dynamic DoAction(ApiAction action)
        {
            if (action == ApiAction.READ)
            {
                return(ReadData());
            }

            if (action == ApiAction.WRITE)
            {
                return(Write());
            }

            if (action == ApiAction.DELETE)
            {
                return(Delete());
            }

            if (action == ApiAction.HUGEINSERT)
            {
                return(HugeInsert());
            }

            return(null);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取和更新Api行为的参数值
        /// </summary>
        /// <param name="action">api行为</param>
        /// <param name="package">数据包</param>
        /// <exception cref="ArgumentException"></exception>
        private void UpdateParameterValues(ApiAction action, JsonPacket package)
        {
            var body = package.body as IList;

            if (body == null)
            {
                throw new ArgumentException("body参数必须为数组");
            }

            if (body.Count != action.ParameterTypes.Length)
            {
                throw new ArgumentException("body参数数量不正确");
            }

            var parameters = new object[body.Count];

            for (var i = 0; i < body.Count; i++)
            {
                var bodyParameter = body[i];
                var parameterType = action.ParameterTypes[i];
                parameters[i] = this.JsonSerializer.Convert(bodyParameter, parameterType);
            }
            action.ParameterValues = parameters;
        }
        private Object Execute(Type type, ApiAction action, Dictionary<string, Object> objectMap = null, Authentication authentication = null)
        {
            if (authentication == null)
            {
                authentication = GetDefaultAuthentication();
            }

            string url = null;
            string requestBody = null;
            string signature = null;
            string privateKey = authentication.PrivateApiKey;
            string publicKey = authentication.PublicApiKey;

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;

            switch (action)
            {
                case ApiAction.List:
                    Dictionary<string, string> queryParams = new Dictionary<string, string>();
                    queryParams["max"] = (string)objectMap["max"];
                    queryParams["offset"] = (string)objectMap["offset"];

                    if (objectMap["sorting"] != null)
                    {
                        Dictionary<string, string> sorting = (Dictionary<string, string>)objectMap["sorting"];
                        foreach (var key in sorting.Keys)
                        {
                            queryParams["sorting[" + key + "]"] = sorting[key];
                        }
                    }

                    if (objectMap["filter"] != null)
                    {
                        Dictionary<string, string> filter = (Dictionary<string, string>)objectMap["filter"];
                        foreach (var key in filter.Keys)
                        {
                            queryParams["filter[" + key + "]"] = filter[key];
                        }
                    }

                    url = GetUrl(type, action, publicKey, null, queryParams);

                    signature = JwsEncode(url, null, authentication);
                    break;

                case ApiAction.Find:
                    url = GetUrl(type, action, publicKey, (string)objectMap["id"]);
                    signature = JwsEncode(url, null, authentication);
                    break;
                case ApiAction.Delete:
                    url = GetUrl(type, action, publicKey, (string)objectMap["id"]);
                    signature = JwsEncode(url, null, authentication);
                    break;
                case ApiAction.Create:
                    url = GetUrl(type, action, publicKey, null);

                    requestBody = JsonConvert.SerializeObject(objectMap["object"], settings);
                    requestBody = JwsEncode(url, requestBody, authentication);
                    break;
                case ApiAction.Update:
                    url = GetUrl(type, action, publicKey, (string)objectMap["id"]);
                    requestBody = JsonConvert.SerializeObject(objectMap["object"], settings);
                    requestBody = JwsEncode(url, requestBody, authentication);
                    break;
            }

            HttpWebRequest request = CreateWebRequest(url, requestBody, ActionToMethodMap[action], privateKey, publicKey);

            string result = ExecuteRequest(request, requestBody, signature);
            return ConvertResponse(result, type, action);
        }
        private Object ConvertResponse(string response, Type type, ApiAction action)
        {
            Object result = null;

            switch (action)
            {
                case ApiAction.List:

                    Type listType = typeof(ResourceList<>);
                    result = JsonConvert.DeserializeObject(response, listType.MakeGenericType(type));
                    break;
                case ApiAction.Find:
                case ApiAction.Delete:
                case ApiAction.Create:
                case ApiAction.Update:
                    result = JsonConvert.DeserializeObject(response, type);
                    break;

            }
            return result;
        }
Ejemplo n.º 7
0
 private static void onCreateSuccessAction(ApiAction context)
 {
     MakerWOWApi.InventoryRepository.Read(onReadSuccessAction, OnCrudFailed);
 }
Ejemplo n.º 8
0
 public Request(string function, ApiAction action)
     : base("api3/"+function, action.ApiMethod())
 {
 }
Ejemplo n.º 9
0
 internal HttpPostDataCollection AppendApiActionToPostDataCollection(HttpPostDataCollection postDataCollection, ApiAction action)
 {
     postDataCollection.Add("a", EnumerationUtility.GetStringValue(action));
     return(postDataCollection);
 }
Ejemplo n.º 10
0
        public void Create(ApiAction apiAction)
        {
            var action = ConvertToDomain(apiAction);

            _actionService.Create(action);
        }
Ejemplo n.º 11
0
        private async Task <object> ActionInvoker()
        {
            var action = ApiActionFactory.Get(this, ActionName, ActionVersion);

            if (action == null)
            {
                return(ErrorResult(new ApiException(ExceptionCode.ApiNotFound)));
            }
            if (action.Obsolete != null && action.Obsolete.IsError)
            {
                return(ErrorResult(new ApiException(ExceptionCode.ApiObsolete, action.Obsolete.Message)));
            }
            ActionName = action.Name;
            ApiAction  = action;
            //验证签名
            if (action.HasFilter <SignAttribute>())
            {
                var signer = new Signer();
                if (_NoSign == false)
                {
                    var ex = signer.CheckAsync(this); //验证签名返回错误消息
                    if (ex != null)                   //如果必须签名,则抛出异常
                    {
                        return(ErrorResult(ex));
                    }
                }
            }


            //是否启动Session
            var sessionState = SessionState;

            if (sessionState == ApiSessionState.Auto)
            {
                sessionState = IsBrowser ? ApiSessionState.Enable : ApiSessionState.Disable;
            }
            switch (sessionState)
            {
            case ApiSessionState.Enable:
                Properties["SessionState"] = 1;
                var err = await OnInitSession();

                if (err != null)
                {
                    return(ErrorResult(err));
                }
                break;

            case ApiSessionState.Disable:
            case ApiSessionState.Auto:
            default:
                Properties["SessionState"] = 0;
                Trace.WriteLine("本次请求禁用Session");
                Session = new DictionarySession();
                break;
            }
            //用户
            if (!action.HasFilter <NoLoginAttribute>())
            {
                //初始化用户
                var task = OnInitUser();
                var ex   = task.IsNull() ? null : await task;
                if (ex != null)
                {
                    return(ErrorResult(ex));
                }
            }
            //解析Url参数
            Exception parseError;
            var       args = action.GetArguments(RequestValues, out parseError);

            if (parseError != null)
            {
                return(ErrorResult(parseError));
            }
            //验证参数

            //执行前
            {
                var task = OnExecuting(action.Name);
                var r    = await task;
                if (r != null)
                {
                    Trace.WriteLine("Api.OnExecuting截断");
                    return(ProcessResult(r));
                }
            }
            //前Filter
            {
                var r = await action.OnActionExecuting(this);

                if (r != null)
                {
                    Trace.WriteLine("Filter.OnExecuting截断");
                    return(ProcessResult(r));
                }
            }
            //执行Action
            var result = await ApiAction.TryRunTask(action.Execute(this, args));

            {//后Filter
                var r = await action.OnActionExecuted(this, result);

                if (r != null)
                {
                    Trace.WriteLine("Filter.OnExecuted截断");
                    return(ProcessResult(r));
                }
            }

            {//执行后
                var task = OnExecuted(action.Name, result);
                var r    = await task;
                if (r == null)
                {
                    return(ProcessResult(result));
                }
                Trace.WriteLine("Api.OnExecuted截断");
                return(ProcessResult(r));
            }
        }
Ejemplo n.º 12
0
        // ------------------------------------------------------------

        public AppConfig(string fname)
        {
            // initialize
            HashSet <int> deviceIds     = new HashSet <int>();
            HashSet <int> deviceNumbers = new HashSet <int>();

            mSettings      = new ApiSettings();
            mDevices       = new ApiDevice[0];
            mDeviceConfigs = new ApiDeviceConfig[0];
            mAppProfiles   = new ApiAppProfile[0];
            mEvents        = new ApiEvent[0];
            mActions       = new ApiAction[0];

            // load the AppConfig
            if (!File.Exists(fname))
            {
                return;  // FIXME! can't do this - we have to notify the DLL
            }
            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();

            xmlReaderSettings.IgnoreComments = true;
            xmlReaderSettings.IgnoreProcessingInstructions = true;
            xmlReaderSettings.IgnoreWhitespace             = true;
            XmlDocument xmlDoc = new XmlDocument();

            using (XmlReader xmlReader = XmlReader.Create(fname, xmlReaderSettings))
                xmlDoc.Load(xmlReader);

            // parse the app config
            XmlNode configXmlNode = xmlDoc.SelectSingleNode("/config");

            // parse the devices
            List <ApiDevice> devices = new List <ApiDevice>();

            foreach (XmlNode xn in configXmlNode.SelectNodes("device"))
            {
                ApiDevice device = new ApiDevice();
                device.mDeviceId = Int32.Parse(xn.Attributes["id"].Value);
                if (deviceIds.Contains(device.mDeviceId))
                {
                    throw new Exception(String.Format("Duplicate device ID: {0}", device.mDeviceId));
                }
                deviceIds.Add(device.mDeviceId);
                device.mHID          = xn.SelectSingleNode("hid").InnerText.Trim();
                device.mDeviceNumber = Int32.Parse(xn.SelectSingleNode("deviceNumber").InnerText);
                if (deviceNumbers.Contains(device.mDeviceNumber))
                {
                    throw new Exception(String.Format("Duplicate device number: {0}", device.mDeviceNumber));
                }
                deviceNumbers.Add(device.mDeviceNumber);
                if (deviceNumbers.Contains(device.mDeviceNumber))
                {
                    device.mDisplayName = Utils.getXmlChildVal(xn, "displayName");
                }
                device.mIsEnabled = Utils.getXmlChildVal(xn, "enabled", false);
                devices.Add(device);
            }
            mDevices = devices.ToArray();

            // parse the device configs
            List <ApiDeviceConfig> deviceConfigs = new List <ApiDeviceConfig>();
            List <ApiAppProfile>   appProfiles   = new List <ApiAppProfile>();
            List <ApiEvent>        events        = new List <ApiEvent>();
            List <ApiAction>       actions       = new List <ApiAction>();

            foreach (XmlNode deviceConfigXmlNode in configXmlNode.SelectNodes("deviceConfig"))
            {
                ApiDeviceConfig deviceConfig = new ApiDeviceConfig();
                deviceConfig.mDeviceId = Int32.Parse(deviceConfigXmlNode.Attributes["id"].Value);
                deviceConfig.mStrokeHistoryResetInterval = Utils.getXmlChildVal(deviceConfigXmlNode, "strokeHistoryResetInterval", -1);
                deviceConfig.mAppProfileStartIndex       = appProfiles.Count;
                deviceConfig.mAppProfileCount            = 0;
                // parse the app profiles
                foreach (XmlNode appProfileXmlNode in deviceConfigXmlNode.SelectNodes("appProfile"))
                {
                    ApiAppProfile appProfile = new ApiAppProfile();
                    appProfile.mApp = Utils.getXmlAttr(appProfileXmlNode, "app", "");
                    XmlNode xn = appProfileXmlNode.SelectSingleNode("sensitivity");
                    if (xn != null)
                    {
                        appProfile.mSensitivityX = Utils.getXmlAttr(xn, "x", 0);
                        appProfile.mSensitivityY = Utils.getXmlAttr(xn, "y", 0);
                    }
                    appProfile.mFallbackToDefaultAppProfile = Utils.getXmlChildVal(appProfileXmlNode, "fallbackToDefaultAppProfile", false);
                    appProfile.mEventStartIndex             = events.Count;
                    appProfile.mEventCount = 0;
                    // parse the events
                    foreach (XmlNode eventXmlNode in appProfileXmlNode.SelectNodes("event"))
                    {
                        ApiEvent evt = new ApiEvent();
                        evt.mEventType    = (int)Enum.Parse(typeof(ApiEvent.EventType), eventXmlNode.Attributes["type"].Value, true);
                        evt.mKeyModifiers = getKeyModifiers(eventXmlNode);
                        // parse the actions
                        evt.mActionStartIndex = actions.Count;
                        evt.mActionCount      = 0;
                        foreach (XmlNode actionXmlNode in eventXmlNode.SelectNodes("action"))
                        {
                            ApiAction action = new ApiAction();
                            action.mActionType = (int)Enum.Parse(typeof(ApiAction.ActionType), actionXmlNode.Attributes["type"].Value, true);
                            if (action.mActionType == (int)ApiAction.ActionType.keyPress)
                            {
                                action.mActionParam = Utils.getXmlAttr(actionXmlNode, "vKey", 0);
                                if (action.mActionParam <= 0)
                                {
                                    throw new Exception("Missing vKey.");
                                }
                            }
                            else
                            {
                                action.mActionParam = Utils.getXmlAttr(actionXmlNode, "speed", 0);
                            }
                            action.mKeyModifiers = getKeyModifiers(actionXmlNode);
                            actions.Add(action);
                            evt.mActionCount++;
                        }
                        events.Add(evt);
                        appProfile.mEventCount++;
                    }
                    // add the app profile to the table
                    appProfiles.Add(appProfile);
                    deviceConfig.mAppProfileCount++;
                }
                // add the device config to the table
                deviceConfigs.Add(deviceConfig);
            }
            mDeviceConfigs = deviceConfigs.ToArray();
            mAppProfiles   = appProfiles.ToArray();
            mEvents        = events.ToArray();
            mActions       = actions.ToArray();
        }
Ejemplo n.º 13
0
        bool isParamValid(ApiAction action)
        {
            try {
                int nTempValue;

                // check fam no
                if (Request.Form[Param.FamNo] == null)
                {
                    return(false);
                }

                string szFamNo = Request.Form[Param.FamNo].ToString();
                int.Parse(szFamNo);

                m_paramExpDList.Add($"{TableName.CoExpD}.fam_no={szFamNo}");
                m_paramExpMList.Add($"{TableName.CoExpM}.fam_no={szFamNo}");

                if (action == ApiAction.READ)
                {
                    // check date
                    if (Request.Form[Param.Year] != null && Request.Form[Param.Month] != null)
                    {
                        string szYear  = Request.Form[Param.Year].ToString();
                        string szMonth = Request.Form[Param.Month].ToString();

                        if (
                            int.TryParse(szYear, out nTempValue) == false ||
                            int.TryParse(szMonth, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoExpD}.ie_year={szYear} AND {TableName.CoExpD}.ie_mon={szMonth}");
                        m_paramExpMList.Add($"{TableName.CoExpM}.ie_year={szYear} AND {TableName.CoExpM}.ie_mon={szMonth}");
                    }

                    if (Request.Form[Param.Day] != null)
                    {
                        string szDay = Request.Form[Param.Day].ToString();
                        if (int.TryParse(szDay, out nTempValue) == false)
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoExpD}.ie_day={szDay}");
                        m_paramExpMList.Add($"{TableName.CoExpM}.ie_day={szDay}");
                    }

                    // check duration
                    if (Request.Form[Param.DurationStart] != null && Request.Form[Param.DurationEnd] != null)
                    {
                        string szDurationStart = Request.Form[Param.DurationStart].ToString();
                        string szDurationEnd   = Request.Form[Param.DurationEnd].ToString();

                        if (
                            int.TryParse(szDurationStart, out nTempValue) == false ||
                            int.TryParse(szDurationEnd, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoExpD}.ie_day BETWEEN {szDurationStart} AND {szDurationEnd}");
                        m_paramExpMList.Add($"{TableName.CoExpM}.ie_day BETWEEN {szDurationStart} AND {szDurationEnd}");
                    }

                    // check no
                    if (Request.Form[Param.CodeNo] != null)
                    {
                        string szCodeNo = Request.Form[Param.CodeNo].ToString();
                        int    nCode    = int.Parse(szCodeNo);
                        m_paramExpDList.Add($"{TableName.CoExpD}.code_no LIKE '{nCode}%'");
                    }

                    // check no
                    if (Request.Form[Param.CodeName] != null)
                    {
                        string szCodeName = Request.Form[Param.CodeName].ToString();
                        m_paramExpDList.Add($"{TableName.CoExpD}.code_name LIKE '%{szCodeName}%'");
                    }

                    if (m_paramExpDList.Count == 0)
                    {
                        return(false);
                    }
                    return(true);
                }
                if (action == ApiAction.WRITE)
                {
                    // get item array
                    string szUpdateItems = Request.Form[Param.UpdateItems].ToString();
                    JArray.Parse(szUpdateItems);
                    string szInsertItems = Request.Form[Param.InsertItems].ToString();
                    JArray.Parse(szInsertItems);

                    // get date
                    string szYear = Request.Form[Param.Year].ToString();
                    int.Parse(szYear);
                    string szMonth = Request.Form[Param.Month].ToString();
                    int.Parse(szMonth);
                    string szDay = Request.Form[Param.Day].ToString();
                    int.Parse(szDay);

                    m_paramExpDList.Add($"{TableName.CoExpD}.ie_year={szYear} AND {TableName.CoExpD}.ie_mon={szMonth} AND {TableName.CoExpD}.ie_day={szDay}");
                    m_paramExpMList.Add($"{TableName.CoExpM}.ie_year={szYear} AND {TableName.CoExpM}.ie_mon={szMonth} AND {TableName.CoExpM}.ie_day={szDay}");

                    // check total cosst
                    string szTotalCost = Request.Form[Param.TotalCost].ToString();
                    int.Parse(szTotalCost);

                    // check remark
                    string szRemark = Request.Form[Param.DayRemark].ToString();
                    return(true);
                }
                if (action == ApiAction.DELETE)
                {
                    string szItemArray = Request.Form[Param.ItemArray].ToString();
                    JArray.Parse(szItemArray);
                    return(true);
                }

                if (action == ApiAction.HUGEINSERT)
                {
                    string szInsertItems = Request.Form[Param.InsertItems].ToString();
                    JArray.Parse(szInsertItems);

                    // get date
                    string szYear = Request.Form[Param.Year].ToString();
                    int.Parse(szYear);
                    string szMonth = Request.Form[Param.Month].ToString();
                    int.Parse(szMonth);
                    string szDay = Request.Form[Param.Day].ToString();
                    int.Parse(szDay);

                    m_paramExpDList.Add($"{TableName.CoExpD}.ie_year={szYear} AND {TableName.CoExpD}.ie_mon={szMonth} AND {TableName.CoExpD}.ie_day={szDay}");
                    m_paramExpMList.Add($"{TableName.CoExpM}.ie_year={szYear} AND {TableName.CoExpM}.ie_mon={szMonth} AND {TableName.CoExpM}.ie_day={szDay}");
                    return(true);
                }
                return(false);
            }
            catch {
                return(false);
            }
        }
Ejemplo n.º 14
0
        public AzureListener(string collectionUri, string project, string accessToken, string buildId, ApiAction send, int batchSize)
        {
            this.collectionUri = collectionUri;
            this.project       = project;
            this.buildId       = buildId;
            this.send          = send;
            this.batchSize     = batchSize;

            batch = new List <Result>(batchSize);

            client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }
Ejemplo n.º 15
0
 public Task <IActionResult> Get(Id <ForNameSelection> id)
 {
     return(ApiAction.GetAsync(processor.SendAsync <Id <ForNameSelection>, NameSelectionView>(id)));
 }
Ejemplo n.º 16
0
 public virtual void Init(ApiAction action)
 {
 }
        private String GetUrl(Type type, ApiAction action, String publicKey, String id = null, Dictionary<string, string> queryParams = null)
        {
            string url = ApiBaseSandboxUrl;
            if (IsLivePublicKey(publicKey))
            {
                url = ApiBaseLiveUrl;
            }

            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            string name = type.Name.Substring(0, 1).ToLower() + type.Name.Substring(1);
            url += name;

            switch (action)
            {
                case ApiAction.Find:
                case ApiAction.Delete:
                case ApiAction.Update:
                    url += "/" + id;
                    break;

            }

            if (queryParams != null)
            {
                url += BuildParamString(queryParams);
            }

            return url;
        }
        bool isParamValid(ApiAction action)
        {
            try {
                int nTempValue;

                switch (action)
                {
                case ApiAction.READ: {
                    // check data
                    if (Request.Form[Param.Year] != null && Request.Form[Param.Month] != null)
                    {
                        string szYear  = Request.Form[Param.Year].ToString();
                        string szMonth = Request.Form[Param.Month].ToString();

                        if (
                            int.TryParse(szYear, out nTempValue) == false ||
                            int.TryParse(szMonth, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramList.Add($"{TableName.CoFam}.ie_year={szYear} AND {TableName.CoFam}.ie_mon={szMonth}");
                    }

                    // check family no
                    if (Request.Form[Param.FamNoStart] != null && Request.Form[Param.FamNoEnd] != null)
                    {
                        string szFamNoStart = Request.Form[Param.FamNoStart].ToString();
                        string szFamNoEnd   = Request.Form[Param.FamNoEnd].ToString();

                        if (
                            int.TryParse(szFamNoStart, out nTempValue) == false ||
                            int.TryParse(szFamNoEnd, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramList.Add($"{TableName.CoFam}.fam_no BETWEEN {szFamNoStart} AND {szFamNoEnd}");
                    }

                    // check record no
                    if (Request.Form[Param.RecUser] != null)
                    {
                        string szRecUser = Request.Form[Param.RecUser].ToString();
                        m_paramList.Add($"{TableName.CoFam}.rec_user LIKE '%{szRecUser}%'");
                    }

                    // check record no
                    if (Request.Form[Param.AdiUser] != null)
                    {
                        string szAdiUser = Request.Form[Param.AdiUser].ToString();
                        m_paramList.Add($"{TableName.CoFam}.adi_user LIKE '%{szAdiUser}%'");
                    }

                    // no param
                    if (m_paramList.Count == 0)
                    {
                        return(false);
                    }

                    return(true);
                }

                case ApiAction.DELETE: {
                    // check data
                    if (Request.Form[Param.Year] != null && Request.Form[Param.Month] != null)
                    {
                        string szYear  = Request.Form[Param.Year].ToString();
                        string szMonth = Request.Form[Param.Month].ToString();

                        if (
                            int.TryParse(szYear, out nTempValue) == false ||
                            int.TryParse(szMonth, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramList.Add($"{TableName.CoFam}.ie_year={szYear} AND {TableName.CoFam}.ie_mon={szMonth}");
                    }

                    if (Request.Form[Param.FamilyDataList] != null)
                    {
                        JArray jData = JArray.Parse(Request.Form[Param.FamilyDataList].ToString());
                    }

                    if (Request.Form[Param.FamMemData] != null)
                    {
                        JArray jDataAry = JArray.Parse(Request.Form[Param.FamMemData].ToString());
                    }
                    return(true);
                }

                case ApiAction.UPDATE: {
                    if (Request.Form[Param.FamData] != null)
                    {
                        JArray jDataAry = JArray.Parse(Request.Form[Param.FamData].ToString());
                    }
                    else if (Request.Form[Param.FamMemData] != null)
                    {
                        JArray jDataAry = JArray.Parse(Request.Form[Param.FamMemData].ToString());
                    }
                    else
                    {
                        return(false);
                    }

                    return(true);
                }

                default:
                    return(false);
                }
            }
            catch {
                return(false);
            }
        }
 /// <summary>
 /// 获取Api行为的特性过滤器
 /// </summary>
 /// <param name="apiAction">Api行为</param>
 /// <returns></returns>
 public IEnumerable <IFilter> GetActionFilters(ApiAction apiAction)
 {
     return(this.GetActionFilters(apiAction, cached: true));
 }
Ejemplo n.º 20
0
        bool isParamValid(ApiAction action)
        {
            try {
                if (action == ApiAction.READ)
                {
                    int nTempValue;

                    // check data
                    if (Request.Form[Param.Year] != null && Request.Form[Param.Month] != null)
                    {
                        string szYear  = Request.Form[Param.Year].ToString();
                        string szMonth = Request.Form[Param.Month].ToString();

                        if (
                            int.TryParse(szYear, out nTempValue) == false ||
                            int.TryParse(szMonth, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoFam}.ie_year={szYear} AND {TableName.CoFam}.ie_mon={szMonth}");
                    }

                    // check family no
                    if (Request.Form[Param.FamNoStart] != null && Request.Form[Param.FamNoEnd] != null)
                    {
                        string szFamNoStart = Request.Form[Param.FamNoStart].ToString();
                        string szFamNoEnd   = Request.Form[Param.FamNoEnd].ToString();

                        if (
                            int.TryParse(szFamNoStart, out nTempValue) == false ||
                            int.TryParse(szFamNoEnd, out nTempValue) == false
                            )
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoFam}.fam_no BETWEEN {szFamNoStart} AND {szFamNoEnd}");
                    }

                    // check record no
                    if (Request.Form[Param.RecNo] != null)
                    {
                        string szRecNo = Request.Form[Param.RecNo].ToString();

                        if (int.TryParse(szRecNo, out nTempValue) == false)
                        {
                            return(false);
                        }

                        m_paramExpDList.Add($"{TableName.CoFam}.rec_user LIKE '%{szRecNo}%'");
                    }

                    // check record no
                    if (Request.Form[Param.AdiUser] != null)
                    {
                        string szAdiUser = Request.Form[Param.AdiUser].ToString();
                        m_paramExpDList.Add($"{TableName.CoFam}.adi_user LIKE '%{szAdiUser}%'");
                    }

                    // check record no
                    if (Request.Form[Param.State] != null)
                    {
                        string szState = Request.Form[Param.State].ToString();
                        if (szState != "0")
                        {
                            m_paramExpDList.Add($"{TableName.CoFam}.state = {szState}");
                        }
                    }

                    // no param
                    if (m_paramExpDList.Count == 0)
                    {
                        return(false);
                    }

                    return(true);
                }
                if (action == ApiAction.CONFIRM)
                {
                    string szConfirmList = Request.Form[Param.ConfirmList].ToString();
                    string szConfirmType = Request.Form[Param.ConfirmType].ToString();
                    int.Parse(szConfirmType);
                    JArray.Parse(szConfirmList);
                    return(true);
                }

                return(false);
            }
            catch {
                return(false);
            }
        }
 /// <summary>
 /// 获取Api行为的特性过滤器     
 /// </summary>
 /// <param name="apiAction">Api行为</param>
 /// <returns></returns>
 public virtual IEnumerable<IFilter> GetActionFilters(ApiAction apiAction)
 {
     return this.filterCached.GetOrAdd(apiAction, action => GetActionFiltersNoCached(action));
 }
Ejemplo n.º 22
0
 public BasicRequest(string action)
 {
     Action = new ApiAction(action);
     Meta   = new Meta();
     Params = new Params();
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Api行为上下文
 /// </summary>
 /// <param name="context">请求上下文</param>
 /// <param name="action">Api行为</param>
 public ActionContext(RequestContext context, ApiAction action)
     : base(context.Session, context.Packet)
 {
     this.Action = action;
 }
Ejemplo n.º 24
0
        public AzureListener(string collectionUri, string project, string accessToken, string buildId, ApiAction postAction)
        {
            this.collectionUri = collectionUri;
            this.project       = project;
            this.buildId       = buildId;
            this.postAction    = postAction;

            client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Api行为上下文
 /// </summary>
 /// <param name="context">请求上下文</param>
 /// <param name="action">Api行为</param>
 public ActionContext(RequestContext context, ApiAction action)
     : base(context.Session, context.Packet, context.AllSessions)
 {
     this.Action = action;
 }
Ejemplo n.º 26
0
        //保存
        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                if (tbConPwd.Text.Trim().Equals(tbNewPwd.Text.Trim()))
                {
                    if (!string.IsNullOrEmpty(WorkNum_T.Text) && !bll.CheckWorkNumIsOnly(WorkNum_T.Text, Convert.ToInt32(HdnUserID.Value)))
                    {
                        function.WriteErrMsg("工号重复请重新输入!!");
                    }
                    DataTable dt         = bub.Select_All();//获取你额外添加的字段。
                    Call      commonCall = new Call();
                    DataTable table      = commonCall.GetDTFromPage(dt, this.Page, ViewState);

                    int        UserID = DataConverter.CLng(this.HdnUserID.Value);
                    M_UserInfo info   = bll.SeachByID(UserID);
                    if (!string.IsNullOrEmpty(this.tbNewPwd.Text.Trim()))
                    {
                        info.UserPwd = this.tbNewPwd.Text.Trim();
                    }
                    info.Email              = this.tbEmail.Text.Trim();
                    info.GroupID            = DataConverter.CLng(this.DDLGroup.SelectedValue);
                    info.UserExp            = DataConverter.CLng(this.txtPoint.Text);
                    info.SilverCoin         = DataConverter.CLng(this.txtSilverCoin.Text);
                    info.Purse              = DataConverter.CDouble(this.txtMoney.Text);
                    info.UserPoint          = DataConverter.CLng(this.txtUserPoint.Text);  //点券
                    info.boffExp            = DataConverter.CLng(this.txtboffExp.Text);    //卖家积分
                    info.ConsumeExp         = DataConverter.CLng(this.txtConsumeExp.Text); //消费积分
                    info.DeadLine           = DataConverter.CDate(this.txtDeadLine.Text);  //有效期截止时间
                    info.CerificateDeadLine = DataConverter.CDate(this.txtCerificateDeadLine.Text);
                    info.UserCreit          = DataConverter.CLng(txtUserCrite.Text);
                    info.DummyPurse         = DataConverter.CDouble(txtPurm.Text);
                    info.ParentUserID       = this.tbParentUserID.Text;
                    info.CompanyName        = this.CompanyNameT.Text;
                    info.CompanyDescribe    = this.CompanyDescribeT.Text;
                    info.WorkNum            = WorkNum_T.Text.Trim().ToString();
                    info.UserFace           = this.tbUserFace.Text.Trim();
                    info.HoneyName          = txtHoneyName.Text.Trim();
                    info.UserRole           = GetUserRole();
                    info.Question           = tbQuestion.Text;
                    info.Answer             = tbAnswer.Text.Trim();
                    M_Uinfo binfo = bll.GetUserBaseByuserid(UserID);
                    info.TrueName     = this.tbTrueName.Text.Trim();
                    binfo.UserSex     = DataConverter.CBool(this.tbUserSex.SelectedValue);
                    binfo.BirthDay    = this.tbBirthday.Text.Trim();
                    binfo.OfficePhone = this.tbOfficePhone.Text.Trim();
                    binfo.HomePhone   = this.tbHomePhone.Text.Trim();
                    binfo.Mobile      = this.tbMobile.Text.Trim();
                    binfo.PHS         = this.tbPHS.Text.Trim();
                    binfo.Fax         = this.tbFax.Text.Trim();
                    binfo.Address     = this.tbAddress.Text.Trim();
                    binfo.ZipCode     = this.tbZipCode.Text.Trim();
                    binfo.IDCard      = this.tbIDCard.Text.Trim();
                    binfo.HomePage    = this.tbHomepage.Text.Trim();
                    binfo.QQ          = this.tbQQ.Text.Trim();
                    binfo.ICQ         = this.tbICQ.Text.Trim();
                    binfo.MSN         = this.tbMSN.Text.Trim();
                    binfo.Yahoo       = this.tbYahoo.Text.Trim();
                    //binfo.HoneyName = txtHoneyName.Text.Trim();
                    binfo.UC         = this.tbUC.Text.Trim();
                    binfo.UserFace   = info.UserFace;
                    binfo.FaceHeight = DataConverter.CLng(this.tbFaceHeight.Text.Trim());
                    binfo.FaceWidth  = DataConverter.CLng(this.tbFaceWidth.Text.Trim());
                    binfo.Sign       = this.tbSign.Text.Trim();
                    binfo.Province   = Request.Form["selprovince"];
                    binfo.City       = Request.Form["selcity"];
                    binfo.County     = Request.Form["selcoutry"];

                    binfo.Privating = this.tbPrivacy.SelectedIndex;
                    binfo.VIPUser   = DataConverter.CLng(this.VIPUser.SelectedValue);

                    ApiAction api = new ApiAction();
                    if (!string.IsNullOrEmpty(this.tbNewPwd.Text.Trim()))
                    {
                        if (DataConverter.CBool(api.data.config.Discuz))              //启用DZ整合
                        {
                            int regstr = ucApi.Func.uc_user_checkname(info.UserName); // Func.uc_user_register(username, this.tbPwd.Text.Trim(), this.tbEmail.Text.Trim()).ToString();
                            if (regstr == -3)                                         //已存在
                            {
                                ucApi.Func.uc_user_edit(info.UserName, "", this.tbNewPwd.Text.Trim(), this.tbEmail.Text.Trim(), true);
                            }
                        }
                    }

                    #region
                    DataTable dtModelUser = bm.GetListUser();
                    for (int i = 0; i < dtModelUser.Rows.Count; i++)
                    {
                        string    tablename = dtModelUser.Rows[i]["TableName"].ToString();
                        DataTable modelinfo = bmf.SelectTableName(tablename, "userid=" + UserID);
                        if (modelinfo != null && modelinfo.Rows.Count > 0)
                        {
                            int       modelid  = Convert.ToInt32(dtModelUser.Rows[i]["ModelId"].ToString());
                            DataTable groupset = bmf.GetModelFieldListall(modelid).Tables[0];
                            DataTable tablereg = new DataTable();
                            tablereg.Columns.Add(new DataColumn("FieldName", typeof(string)));
                            tablereg.Columns.Add(new DataColumn("FieldType", typeof(string)));
                            tablereg.Columns.Add(new DataColumn("FieldValue", typeof(string)));
                            if (groupset != null && groupset.Rows.Count > 0)
                            {
                                foreach (DataRow dr in groupset.Rows)
                                {
                                    if (DataConverter.CBool(dr["IsNotNull"].ToString()))
                                    {
                                        if (string.IsNullOrEmpty(this.Page.Request.Form["txt_" + dr["FieldName"].ToString()]))
                                        {
                                            function.WriteErrMsg(dr["FieldAlias"].ToString() + "不能为空!");
                                        }
                                    }

                                    if (dr["FieldType"].ToString() == "FileType")
                                    {
                                        string[] Sett      = dr["Content"].ToString().Split(new char[] { ',' });
                                        bool     chksize   = DataConverter.CBool(Sett[0].Split(new char[] { '=' })[1]);
                                        string   sizefield = Sett[1].Split(new char[] { '=' })[1];
                                        if (chksize && sizefield != "")
                                        {
                                            DataRow row2 = tablereg.NewRow();
                                            row2[0] = sizefield;
                                            row2[1] = "FileSize";
                                            row2[2] = this.Page.Request.Form["txt_" + sizefield];
                                            tablereg.Rows.Add(row2);
                                        }
                                    }

                                    if (dr["FieldType"].ToString() == "MultiPicType")
                                    {
                                        string[] Sett      = dr["Content"].ToString().Split(new char[] { ',' });
                                        bool     chksize   = DataConverter.CBool(Sett[0].Split(new char[] { '=' })[1]);
                                        string   sizefield = Sett[1].Split(new char[] { '=' })[1];
                                        if (chksize && sizefield != "")
                                        {
                                            if (string.IsNullOrEmpty(this.Page.Request.Form["txt_" + sizefield]))
                                            {
                                                function.WriteErrMsg(dr["FieldAlias"].ToString() + "的缩略图不能为空!");
                                            }
                                            DataRow row1 = tablereg.NewRow();
                                            row1[0] = sizefield;
                                            row1[1] = "ThumbField";
                                            row1[2] = this.Page.Request.Form["txt_" + sizefield];
                                            tablereg.Rows.Add(row1);
                                        }
                                    }

                                    DataRow row = tablereg.NewRow();
                                    row[0] = dr["FieldName"].ToString();
                                    string ftype = dr["FieldType"].ToString();
                                    row[1] = ftype;
                                    string fvalue = this.Page.Request.Form["txt_" + dr["FieldName"].ToString()];
                                    if (ftype == "TextType" || ftype == "MultipleTextType" || ftype == "MultipleHtmlType")
                                    {
                                        fvalue = sll.ProcessSen(fvalue);
                                    }
                                    row[2] = fvalue;
                                    tablereg.Rows.Add(row);
                                }
                            }
                            bll.UpdateModelInfo(tablereg, tablename, DataConverter.CLng(modelinfo.Rows[0]["id"]));
                        }
                    }

                    #endregion

                    if (!string.IsNullOrEmpty(this.tbNewPwd.Text.Trim()))
                    {
                        info.UserPwd = StringHelper.MD5(this.tbNewPwd.Text.Trim());
                    }
                    bll.UpDateUser(info);
                    bll.UpdateBase(binfo);
                    if (table.Rows.Count > 0)
                    {
                        bll.UpdateUserFile(binfo.UserId, table);
                    }
                    EditPlatInfo(UserID);
                    function.WriteSuccessMsg("修改成功!", ViewState["PageUrl"].ToString());
                }
            }
        }
Ejemplo n.º 27
0
        internal HttpWebRequest CreatePostHttpWebRequest(CloudFlareCredentials credentials, ApiAction action, HttpPostDataCollection postDataCollection)
        {
            var request = (HttpWebRequest)HttpWebRequest.Create(cloudFlareApiUrl);

            request.ContentType = formUrlEndodedContentType;
            request.Method      = WebRequestMethods.Http.Post;

            if (postDataCollection != null && postDataCollection.Count > 0)
            {
                postDataCollection = AppendApiActionToPostDataCollection(postDataCollection, action);
                postDataCollection = AppendCredentialsToPostDataCollection(postDataCollection, credentials);

                var postData       = postDataCollection.ToString();
                var postDataStream = Encoding.UTF8.GetBytes(postData);

                request.ContentLength = postData.Length;

                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(postDataStream, 0, postDataStream.Length);
                }
            }

            return(request);
        }
        bool isParamValid(ApiAction action)
        {
            int nTempValue;

            switch (action)
            {
            case ApiAction.READ: {
                // check data
                if (Request.Form[Param.Year] != null && Request.Form[Param.Month] != null)
                {
                    string szYear  = Request.Form[Param.Year].ToString();
                    string szMonth = Request.Form[Param.Month].ToString();

                    if (
                        int.TryParse(szYear, out nTempValue) == false ||
                        int.TryParse(szMonth, out nTempValue) == false
                        )
                    {
                        return(false);
                    }

                    m_param.Add($"{TableName.CoExpAudit}.ie_year={szYear} AND {TableName.CoExpAudit}.ie_mon={ParseTwoDigital(szMonth)}");
                }

                // check family no
                if (Request.Form[Param.FamNoStart] != null && Request.Form[Param.FamNoEnd] != null)
                {
                    string szFamNoStart = Request.Form[Param.FamNoStart].ToString();
                    string szFamNoEnd   = Request.Form[Param.FamNoEnd].ToString();

                    if (
                        int.TryParse(szFamNoStart, out nTempValue) == false ||
                        int.TryParse(szFamNoEnd, out nTempValue) == false
                        )
                    {
                        return(false);
                    }

                    m_param.Add($"{TableName.CoExpAudit}.fam_no BETWEEN {szFamNoStart} AND {szFamNoEnd}");
                }

                if (Request.Form[Param.CheckType] != null)
                {
                    string szCheckType = Request.Form[Param.CheckType].ToString();
                    if (szCheckType != "0")
                    {
                        m_param.Add($"{TableName.CoExpAudit}.chk_no='{szCheckType}'");
                    }
                }

                if (Request.Form[Param.CheckTime] != null)
                {
                    string szCheckTime = Request.Form[Param.CheckTime].ToString();
                    m_param.Add($"CAST({TableName.CoExpAudit}.chk_date AS smalldatetime)='{szCheckTime}'");
                }

                return(true);
            }

            case ApiAction.CHECK: {
                if (Request.Form[Param.Year] == null || Request.Form[Param.Month] == null)
                {
                    return(false);
                }

                return(true);
            }

            case ApiAction.GetCheckTime:
                return(true);

            default:
                return(false);
            }
        }
Ejemplo n.º 29
0
        private static object ContactConfigAPI(ApiAction action, RegistryKey RegKey, string Key, object Value)
        {
            string errorMessage = string.Empty;

            if (action == ApiAction.setValue)
            {
                string userName = null;
                if (RegKey.ToString().EndsWith("Text App"))
                {
                    RegistryKey rootKey = GetRootKey(ref errorMessage);
                    userName = GetUserName(rootKey, ref errorMessage);
                }
                else
                {
                    userName = null;
                }
                object[]       objArray1 = new object[] { strHomeServer, "/api/MachineProfile/updatemachinesetting?machineId=", GetMachineID(), "&regKey=", RegKey, "&key=", Key, "&propertyvalue=", Value.ToString(), "&phonenumber=", userName, "&winUser=", Environment.UserName };
                HttpWebRequest request1  = (HttpWebRequest)WebRequest.Create(string.Concat(objArray1));
                request1.AutomaticDecompression = DecompressionMethods.GZip;
                request1.Timeout = 0x2710;
                using (HttpWebResponse response = (HttpWebResponse)request1.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            reader.ReadToEnd();
                        }
                    }
                }
                if ((from i in configList
                     where (i.regKey == RegKey.Name) && (i.key == Key)
                     select i).FirstOrDefault <ConfigObject>() == null)
                {
                    ConfigObject item = new ConfigObject {
                        key           = Key,
                        regKey        = RegKey.Name,
                        propertyValue = Value
                    };
                    configList.Add(item);
                    return(Value);
                }
                (from i in configList
                 where (i.regKey == RegKey.Name) && (i.key == Key)
                 select i).First <ConfigObject>().propertyValue = Value;
                return(Value);
            }
            if ((from i in configList
                 where (i.regKey == RegKey.Name) && (i.key == Key)
                 select i).FirstOrDefault <ConfigObject>() == null)
            {
                if ((from i in configList
                     where (i.regKey == RegKey.Name) && (i.key == Key)
                     select i).FirstOrDefault <ConfigObject>() == null)
                {
                    ConfigObject obj2 = new ConfigObject {
                        key           = Key,
                        regKey        = RegKey.Name,
                        propertyValue = Value
                    };
                    configList.Add(obj2);
                    return(Value);
                }
                (from i in configList
                 where (i.regKey == RegKey.Name) && (i.key == Key)
                 select i).First <ConfigObject>().propertyValue = Value;
            }
            return(Value);
        }
        bool isParamValid(ApiAction action)
        {
            try {
                if (action == ApiAction.READ)
                {
                    if (Request.Form[Param.CodeNo] != null)
                    {
                        string szCodeNo = Request.Form[Param.CodeNo].ToString();
                        int    nCode    = int.Parse(szCodeNo);
                        if (nCode != -1)
                        {
                            m_paramList.Add($"code_no LIKE '{nCode}%'");
                        }
                        else
                        {
                            m_paramList.Add($"code_no LIKE '%'");
                        }
                    }

                    if (Request.Form[Param.CodeName] != null)
                    {
                        string szCodeName = Request.Form[Param.CodeName].ToString();
                        m_paramList.Add($"code_name LIKE '%{szCodeName}%'");
                    }

                    if (m_paramList.Count == 0)
                    {
                        return(false);
                    }
                    return(true);
                }
                if (action == ApiAction.INSERT)
                {
                    string szSubject = Request.Form[Param.Subject].ToString();
                    JObject.Parse(szSubject);
                    return(true);
                }
                if (action == ApiAction.UPDATE)
                {
                    string szSubject = Request.Form[Param.PreSubject].ToString();
                    JObject.Parse(szSubject);
                    szSubject = Request.Form[Param.NewSubject].ToString();
                    JObject.Parse(szSubject);
                    return(true);
                }
                if (action == ApiAction.DELETE)
                {
                    string szSubjectAry = Request.Form[Param.SubjectArray].ToString();
                    JArray.Parse(szSubjectAry);
                    return(true);
                }
                if (action == ApiAction.SETDEFAULTNAME)
                {
                    string szSubject = Request.Form[Param.Subject].ToString();
                    JObject.Parse(szSubject);
                    return(true);
                }
                return(false);
            }
            catch {
                return(false);
            }
        }