Esempio n. 1
0
        /// <summary>
        /// Validates the specified type is a valid JsonMethodProvider sending out the first faulting method found if a method is found
        /// that doesn't conform to the requirements of a JsonMethod.
        /// </summary>
        /// <param name="serverHandler"></param>
        /// <param name="faultingMethod"></param>
        /// <returns></returns>
        public static JsonProviderValidationResult ValidateProvider(Type serverHandler, out MethodInfo faultingMethod)
        {
            faultingMethod = null;

            // make sure there is at least one JSONMethod
            MethodInfo[] methods       = serverHandler.GetMethods();
            bool         hasJsonMethod = false;

            // make sure there aren't any "overridden" methods.  ensure unique names
            List <string> jsonMethodNames = new List <string>();

            foreach (MethodInfo method in methods)
            {
                JsonMethod attr;
                if (CustomAttributeExtension.HasCustomAttributeOfType <JsonMethod>(method, out attr))
                {
                    hasJsonMethod = true;
                    if (jsonMethodNames.Contains(method.Name))
                    {
                        faultingMethod = method;
                        return(JsonProviderValidationResult.OverrideFound);
                    }

                    jsonMethodNames.Add(method.Name);
                }
            }

            if (!hasJsonMethod)
            {
                return(JsonProviderValidationResult.NoJsonMethodsFound);
            }

            return(JsonProviderValidationResult.Success);
        }
Esempio n. 2
0
        public static string[] GetPropertyVariables(Type typeToGetVariablesFor)
        {
            List <string> retVal = new List <string>();

            foreach (PropertyInfo propInfo in typeToGetVariablesFor.GetProperties())
            {
                if (propInfo.PropertyType == typeof(string) ||
                    propInfo.PropertyType == typeof(int) ||
                    propInfo.PropertyType == typeof(long) ||
                    propInfo.PropertyType == typeof(decimal) ||
                    propInfo.PropertyType == typeof(DateTime) ||
                    propInfo.PropertyType == typeof(bool) ||
                    propInfo.PropertyType.IsEnum)
                {
                    retVal.Add(string.Format("{0}{1}{2}", BoxServer.VariablePrefix, propInfo.Name, BoxServer.VariableSuffix));
                }
                else if (CustomAttributeExtension.HasCustomAttributeOfType <BoxVar>(propInfo))
                {
                    string   prefix    = string.Format("{0}{1}.", BoxServer.VariablePrefix, propInfo.Name);
                    string[] variables = GetPropertyVariables(propInfo.PropertyType);
                    foreach (string variable in variables)
                    {
                        string varName = variable.Replace(BoxServer.VariablePrefix, string.Empty).Replace(BoxServer.VariableSuffix, string.Empty);
                        retVal.Add(string.Format("{0}{1}{2}", prefix, varName, BoxServer.VariableSuffix));
                    }
                }
            }
            return(retVal.ToArray());
        }
Esempio n. 3
0
 /// <summary>
 /// Register all json providers (classes adornded with the JsonProxy attribute
 /// or having methods adorned with the JsonMethod attribute) defined in the
 /// specified assembly.
 /// </summary>
 /// <param name="type"></param>
 public static void RegisterProviders(Assembly assembly)
 {
     Type[] types = assembly.GetTypes();
     foreach (Type type in types)
     {
         if (CustomAttributeExtension.GetFirstMethodWithAttributeOfType <JsonMethod>(type) != null)
         {
             RegisterProvider(type);
         }
     }
 }
        private DaoForeignKeyInfo[] GetForeignKeys(DaoObject daoObject, string tableName)
        {
            PropertyInfo[]           columns = CustomAttributeExtension.GetPropertiesWithAttributeOfType <DaoForeignKeyColumn>(daoObject.GetType());
            List <DaoForeignKeyInfo> retVals = new List <DaoForeignKeyInfo>();

            foreach (PropertyInfo info in columns)
            {
                DaoForeignKeyColumn fk = (DaoForeignKeyColumn)info.GetCustomAttributes(typeof(DaoForeignKeyColumn), true)[0];
                retVals.Add(new DaoForeignKeyInfo(fk, tableName));
            }

            return(retVals.ToArray());
        }
Esempio n. 5
0
        public static MethodInfo[] GetJsonMethods(Type serverHandler)
        {
            List <MethodInfo> methods = new List <MethodInfo>();

            foreach (MethodInfo method in serverHandler.GetMethods())
            {
                if (CustomAttributeExtension.HasCustomAttributeOfType <JsonMethod>(method))
                {
                    methods.Add(method);
                }
            }

            return(methods.ToArray());
        }
Esempio n. 6
0
        public static string GetDefaultVarName(Type serverHandler)
        {
            JsonProxy proxyAttribute = null;

            if (CustomAttributeExtension.HasCustomAttributeOfType <JsonProxy>(serverHandler, out proxyAttribute))
            {
                if (!string.IsNullOrEmpty(proxyAttribute.VarName))
                {
                    return(proxyAttribute.VarName);
                }
            }

            return(GetClientTypeName(serverHandler));
        }
Esempio n. 7
0
        private static Control LoadControl(string virtualBoxPath, bool renderScripts, string requesterId, object injectionObject, bool postWindowLoad)
        {
            JavascriptPage controlLoader = new JavascriptPage();

            Control control = controlLoader.LoadControl(virtualBoxPath);
            //if (control.Controls.Count == 0)
            //    throw new UserControlIsNotBoxUserControlException(virtualBoxPath);

            BoxUserControl evolved = control as BoxUserControl;//control.Controls[0] as BoxUserControl;

            if (evolved == null)
            {
                throw new UserControlIsNotBoxUserControlException(virtualBoxPath);
            }

            Type controlType = control.GetType();

            JavascriptServer.RegisterProvider(controlType);// makes any JsonMethod methods available to the client

            controlLoader.Controls.Add(control);

            if (injectionObject != null)
            {
                MethodInfo boxInject = CustomAttributeExtension.GetFirstMethodWithAttributeOfType <BoxInject>(controlType);
                if (boxInject != null)
                {
                    ParameterInfo[] paramInfo = boxInject.GetParameters();
                    if (paramInfo.Length != 1 || paramInfo[0].ParameterType != injectionObject.GetType())
                    {
                        throw ExceptionHelper.CreateException <JsonInvalidOperationException>("The BoxInject method of control type {0} has the wrong type or number of parameters.", control.GetType().Name);
                    }

                    boxInject.Invoke(control, new object[] { injectionObject });
                }

                evolved.Inject(injectionObject);
            }

            MethodInfo boxInit = CustomAttributeExtension.GetFirstMethodWithAttributeOfType <BoxInit>(control.GetType());

            if (boxInit != null)
            {
                boxInit.Invoke(control, null);
            }

            evolved.PostBoxLoad(renderScripts, requesterId, postWindowLoad);
            //loadedControls.Add(virtualBoxPath, control);
            return(control);
        }
        private string GetIdColumnName(DaoObject daoObject)
        {
            Type type = daoObject.GetType();

            PropertyInfo[] daoIdColumnAttribute = CustomAttributeExtension.GetPropertiesWithAttributeOfType <DaoIdColumn>(type);
            if (daoIdColumnAttribute.Length > 1)
            {
                ExceptionHelper.ThrowInvalidOperation("Multiple column primary keys not supported");
            }
            if (daoIdColumnAttribute.Length == 1)
            {
                return(daoIdColumnAttribute[0].Name);
            }

            return("");
        }
        private Dictionary <PropertyInfo, DaoColumn> GetColumns(DaoObject daoObject)
        {
            PropertyInfo[] columns = CustomAttributeExtension.GetPropertiesWithAttributeOfType <DaoColumn>(daoObject.GetType());
            Dictionary <PropertyInfo, DaoColumn> retVals = new Dictionary <PropertyInfo, DaoColumn>();

            foreach (PropertyInfo info in columns)
            {
                DaoColumn column = (DaoColumn)info.GetCustomAttributes(typeof(DaoColumn), true)[0];
                if (!(column is DaoForeignKeyColumn))
                {
                    retVals.Add(info, column);
                }
            }

            return(retVals);
        }
Esempio n. 10
0
        private void WriteObject(object obj)
        {
            _output.Append("{ ");

            bool pendingSeparator = false;


            foreach (FieldInfo field in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                if (pendingSeparator)
                {
                    _output.Append(" , ");
                }


                WritePair(field.Name, field.GetValue(obj));

                pendingSeparator = true;
            }

            foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (CustomAttributeExtension.HasCustomAttributeOfType <JsonIgnore>(property))
                {
                    continue;
                }
                if (!property.CanRead)
                {
                    continue;
                }

                if (pendingSeparator)
                {
                    _output.Append(" , ");
                }

                WritePair(property.Name, property.GetValue(obj, null));

                pendingSeparator = true;
            }

            _output.Append(" }");
        }
Esempio n. 11
0
        /// <summary>
        /// 将对象属性转换为key-value对
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>字典</returns>
        private static Dictionary <string, string> ToMap <T>(T obj)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();
            Type t = typeof(T);

            foreach (PropertyInfo property in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                string name = property.Name;
                DynamicExpressionAttribute dynamicExpressionAttribute = CustomAttributeExtension <DynamicExpressionAttribute> .GetCustomAttributeValue(t, property);

                string key = dynamicExpressionAttribute.Name ?? name;
                var    val = property.GetValue(obj);
                string value;
                if (dynamicExpressionAttribute.IsDynamicExpression)
                {
                    if (!string.IsNullOrWhiteSpace(dynamicExpressionAttribute.Operator))
                    {
                        if (dynamicExpressionAttribute.Operator == "yyyy-MM-dd")
                        {
                            if (val != null)
                            {
                                value = Convert.ToDateTime(val).ToString(dynamicExpressionAttribute.Operator);
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        else
                        {
                            value = val?.ToString();
                        }
                    }
                    else
                    {
                        value = val?.ToString();
                    }
                }
                else
                {
                    value = val.SerializeObject();
                }
                if (value != null)
                {
                    result.Add(key, value);
                }
            }
            if (result.Count <= 0)
            {
                var    str     = obj.SerializeObject();
                string pattern = "(\"(?<key>[^,^\"]+)\":\"(?<value>[^:^\"]+)\")|(\"(?<key>[^,^\"]+)\":(?<value>[\\d\\.]+))";
                Regex  regex   = new Regex(pattern);
                var    match   = regex.Matches(str);
                foreach (Match item in match)
                {
                    var key   = item.Groups["key"].ToString();
                    var value = item.Groups["value"].ToString();
                    result.Add(key, value);
                }
            }
            return(result);
        }
Esempio n. 12
0
        private static JsonResult GetJsonResultFromInvoke(string typeName, string methodName, string[] parameters)
        {
            Expect.IsNotNullOrEmpty(typeName, "typeName not specified");
            Expect.IsNotNullOrEmpty(methodName, "methodName not specified");
            JsonResult ret = new JsonResult();

            ret.Status = JsonResultStatus.Unknown;
            ret.Input  = parameters;
            if (HttpContext.Current == null)
            {
                ret.Status = JsonResultStatus.Error;
                ret.Data   = NewInvalidOperationException();
            }
            else
            {
                object handler = GetInstance(typeName);//HttpContext.Current.Session[typeName.ToLowerInvariant()];
                if (handler == null)
                {
                    ret.Status = JsonResultStatus.Error;
                    ret.Data   = new Exception("The specified type was not registered to handle json requests");
                }
                else
                {
                    MethodInfo[] methods = handler.GetType().GetMethods();
                    foreach (MethodInfo method in methods)
                    {
                        JsonMethod jsonMethodAttribute = null;
                        if (!CustomAttributeExtension.HasCustomAttributeOfType <JsonMethod>(method, out jsonMethodAttribute))
                        {
                            continue;
                        }

                        if (method.Name.ToLowerInvariant().Equals(methodName.ToLowerInvariant()))
                        {
                            try
                            {
                                switch (jsonMethodAttribute.Verb)
                                {
                                case Verbs.GET:
                                    ret.Data   = method.Invoke(handler, (object[])parameters);
                                    ret.Status = JsonResultStatus.Success;
                                    break;

                                case Verbs.POST:
                                    ParameterInfo[] parameterInfos = method.GetParameters();
                                    string[]        jsonParameters = null;
                                    using (StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream))
                                    {
                                        string inputString = sr.ReadToEnd();
                                        jsonParameters = StringExtensions.DelimitSplit(inputString, ParameterDelimiter);
                                    }

                                    if (jsonParameters.Length != parameterInfos.Length)
                                    {
                                        ExceptionHelper.Throw <JsonInvalidOperationException>("Parameter count mismatch in call to method {0}, required {1} parameters received {2}", method.Name, parameterInfos.Length, jsonParameters.Length);
                                    }


                                    List <object> parameterList = new List <object>();
                                    for (int i = 0; i < parameterInfos.Length; i++)
                                    {
                                        ParameterInfo parameterInfo = parameterInfos[i];
                                        Serializer    serializer    = new Serializer(parameterInfo.ParameterType);
                                        parameterList.Add(serializer.Deserialize(jsonParameters[i]));
                                    }

                                    ret.Data   = method.Invoke(handler, parameterList.ToArray());
                                    ret.Status = JsonResultStatus.Success;
                                    ret.Input  = jsonParameters;
                                    break;
                                }

                                break;
                            }
                            catch (Exception ex)
                            {
                                string parms = parameters != null?StringExtensions.ToDelimited(parameters, ",") : "";

                                LogManager.CurrentLog.AddEntry("An error occurred during Javascript Method Invokation: typeName={0};methodName={1};parameters={2}", ex, typeName, methodName, parms);
                                if (ex.InnerException != null)
                                {
                                    ex = ex.InnerException;
                                }
                                ret.Status       = JsonResultStatus.Error;
                                ret.Data         = ex.Message;
                                ret.ErrorMessage = ex.Message;
#if DEBUG
                                ret.StackTrace = ex.StackTrace;
#endif
                                break;
                            }
                        }
                    }
                }
            }

            return(ret);
        }
Esempio n. 13
0
        /// <summary>
        /// Primary entry point for this method is from the private SendClientInstantiationScript method, but
        /// in theory this method could be used to generate client instantiation scripts for any Type.
        /// </summary>
        /// <param name="clientName">The name of the "var"ed instance on the client.</param>
        /// <param name="serverHandler">The Type to generate the script for.</param>
        /// <returns></returns>
        public static string GetClientInstantiationScript(string clientName, Type serverHandler)
        {
            HttpRequest request  = HttpContext.Current.Request;
            string      callback = request.QueryString["cb"];// +";\r\n"; // a callback is only used for dynamic loading of ascx JsonMethod providers

            if (!string.IsNullOrEmpty(callback))
            {
                callback += ";";
            }
            string baseUrl = request.Url.PathAndQuery.Replace(request.Url.Query, "");//GetLeftPart(UriPartial.Authority) + request.ApplicationPath;

            // if no handler is specified send an error back to the client
            if (serverHandler == null && !string.IsNullOrEmpty(callback))
            {
                string message = string.Empty;
#if DEBUG
                message = "The specified serverHandler Type was not registered or null (" + clientName + ").";
#else
                message = @"There was an error that occurred on the server. 
                We are working to correct the problem.  Please restart your browser.";
#endif
                string errorScript = "\r\nif(MessageBox !== undefined)\r\n";
                errorScript += string.Format("\tMessageBox.Show('{0}');\r\n", message);
                errorScript += "else";
                errorScript += string.Format("\talert('{0}');", message);
                string serverType = serverHandler == null ? "null" : serverHandler.Namespace + "." + serverHandler.Name;
                LogManager.CurrentLog.AddEntry("Failed to create instantiation script: [clientName: {0}, serverHandler: {1}]", LogEventType.Warning, clientName, serverType);
                return(errorScript);
            }

            string script = "window." + clientName + " = new JsonProxy();\r\n";
            script += "var " + clientName + " = window." + clientName + ";\r\n";
            script += clientName + ".type = '" + GetClientTypeName(serverHandler) + "';";
            script += string.Format("{0}.name = \"{0}\";\r\n", clientName);
            script += "ProxyUtil.AddServerProxy('" + clientName + "', " + clientName + ");\r\n";

            string methodHooks   = string.Empty;
            string methodHooksEx = string.Empty;
            string methodVerbs   = string.Empty;

            methodHooks += clientName + ".MethodEndpoints = {};\r\n"; //string.Format("{0}.MethodEndpoints = [];\r\n", clientName);
            methodVerbs += clientName + ".MethodVerbs = {};\r\n";     //string.Format("{0}.MethodVerbs = [];\r\n", clientName);
            MethodInfo[] methods = serverHandler.GetMethods();

            foreach (MethodInfo method in methods)
            {
                //object[] obj = method.GetCustomAttributes(typeof(JsonMethod), true);

                //if (obj.Length > 0)
                JsonMethod jsonMethodAttribute;
                if (CustomAttributeExtension.HasCustomAttributeOfType <JsonMethod>(method, out jsonMethodAttribute))
                {
                    string verb        = jsonMethodAttribute.Verb.ToString();//((JsonMethod)obj[0]).Verb.ToString();
                    string multiInvoke = jsonMethodAttribute.MultiInvoke ? "true": "false";
                    string argJsArray  = "[";

                    string methodCallPath = string.Format("{0}?t={1}&m={2}&inv=true", baseUrl, GetClientTypeName(serverHandler), method.Name.ToLowerInvariant());

                    methodHooks += string.Format("{0}.MethodEndpoints['{1}'] = '{2}';\r\n", clientName, method.Name, methodCallPath);
                    methodHooks += clientName + ".MethodEndpoints['" + method.Name + "'].multiInvoke = " + multiInvoke + ";\r\n";
                    methodVerbs += string.Format("{0}.MethodVerbs['{1}'] = '{2}';\r\n", clientName, method.Name, verb);

                    ParameterInfo[] parameters = method.GetParameters();
                    methodHooks   += string.Format("{0}.{1} = function(", clientName, method.Name);
                    methodHooksEx += string.Format("{0}.{1}Ex = function(", clientName, method.Name);

                    if (parameters.Length > 0)
                    {
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            methodHooks   += string.Format("{0}", parameters[i].Name);
                            methodHooksEx += string.Format("{0}", parameters[i].Name);

                            argJsArray    += parameters[i].Name;
                            methodHooks   += ",";
                            methodHooksEx += ",";

                            if (i != parameters.Length - 1)
                            {
                                argJsArray += ",";
                            }
                        }
                    }
                    argJsArray  += "]";
                    methodHooks += "callBack, format){ \r\n\tthis.InvokeMethod('" + method.Name + "', " + argJsArray + ", JSUI.IsFunction(callBack) ? callBack : this." + method.Name + "Callback, format ? format: 'json');\r\n}\r\n";
                    methodHooks += clientName + "." + method.Name + "Callback = function(){};// this should be overridden if functionality is required\r\n";

                    methodHooksEx += "options, callBack){\r\n\tthis.InvokeMethodEx('" + method.Name + "', " + argJsArray + ", options, callBack);\r\n}\r\n";
                }
            }

            return(script + methodHooks + methodHooksEx + methodVerbs + callback);
        }