Esempio n. 1
0
 public void ToJS(JSBuilder js)
 {
     if (this.Component.cacheViewedPages)
     {
         js.Add("bStateSave", "true");
     }
 }
Esempio n. 2
0
        public void ToJS(JSBuilder js)
        {
            if (this.component.collection.Count > 0)
            {
                JSBuilder     Maindeclaration = new JSBuilder();
                StringBuilder stringBuilder   = new StringBuilder();
                foreach (var element in this.component.collection)
                {
                    //Creo un JSBuilderElement para declarar un Literal Object, y luego realizaré el toString
                    var jsBuilderElement = new JSBuilder();
                    if (!element.visible)
                    {
                        jsBuilderElement.Add("bVisible", "false");
                    }
                    if (!element.sorting)
                    {
                        jsBuilderElement.Add("bSortable", "false");
                    }
                    if (!element.filtering)
                    {
                        jsBuilderElement.Add("bSearchable", "false");
                    }
                    string aTargets = String.Format("[{0}]", element.Index);
                    jsBuilderElement.Add("aTargets", aTargets);
                    stringBuilder.AppendFormat("{0},", jsBuilderElement.ToLiteralJSObject(true));
                }
                stringBuilder.Remove(stringBuilder.Length - 1, 1);

                String columnDefs = String.Format("[{0}]", stringBuilder.ToString());
                js.Add("aoColumnDefs", columnDefs);
            }
        }
Esempio n. 3
0
        private void BuildScripts()
        {
            //Empezamos por el Base Script
            if (String.IsNullOrEmpty(this.Component.HtmlProperties.Id))
            {
                this.Component.HtmlProperties.Id = Resolvers.HtmlResolver.GenerateHtmlValidId(this.ViewContext,
                                                                                              typeof(Grid <T>));
            }
            JSBuilder JS = new JSBuilder();

            this.Component.Pagination.ToJS(JS);
            this.Component.Search.ToJS(JS);
            this.Component.Binding.ToJS(JS);
            this.Component.Columns.ToJS(JS);
            this.Component.Options.ToJS(JS);
            this.Component.Resources.ToJS(JS);

            //if (this.Component.Size)
            JS.Add("sDom", "\"<'row'<'col-md-3'l><'col-md-6'f>r>t<'row'<'col-md-3'i><'col-md-6'p>>\"");
            String basescript = "$('#" + this.Component.HtmlProperties.Id + "').dataTable(" + JS.ToLiteralJSObject(true) + ");";

            ((GridScripts)this.Component.Scripts).AddScript(basescript);
            var scripts = JSResolver.JSStack(ViewContext);

            scripts.Push(((GridScripts)this.Component.Scripts).GetGeneratedScript());
        }
Esempio n. 4
0
 public void ToJS(JSBuilder js)
 {
     if (Component.IsRemote && !String.IsNullOrEmpty(Component.Action))
     {
         //js.Add("bProcessing", "true");
         js.Add("bServerSide", "true");
         js.Add("sAjaxSource", this.Component.ActionToJSValue());
     }
 }
Esempio n. 5
0
        private void BuildGroupedParameterMappings(JSBuilder builder, IEnumerable <ParameterTransformation> transformations)
        {
            // Declare all the output paramaters outside the try block
            foreach (ParameterTransformation transformation in transformations)
            {
                if (transformation.OutputParameter.ModelType is CompositeType &&
                    transformation.OutputParameter.IsRequired)
                {
                    builder.Line($"let {transformation.OutputParameter.Name} = new client.models['{transformation.OutputParameter.ModelType.Name}']();");
                }
                else
                {
                    builder.Line($"let {transformation.OutputParameter.Name};");
                }
            }

            IEnumerable <ParameterTransformation> transformationsWithMappings = transformations.Where((ParameterTransformation transformation) => transformation?.ParameterMappings?.Any() == true);

            if (transformationsWithMappings.Any())
            {
                builder.Try(tryBlock =>
                {
                    foreach (ParameterTransformation transformation in transformations)
                    {
                        tryBlock.If(BuildNullCheckExpression(transformation), ifBlock =>
                        {
                            Parameter outputParameter       = transformation.OutputParameter;
                            bool noCompositeTypeInitialized = true;
                            if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                                transformation.OutputParameter.ModelType is CompositeType)
                            {
                                //required outputParameter is initialized at the time of declaration
                                if (!transformation.OutputParameter.IsRequired)
                                {
                                    ifBlock.Line($"{transformation.OutputParameter.Name} = new client.models['{transformation.OutputParameter.ModelType.Name}']();");
                                }
                                noCompositeTypeInitialized = false;
                            }

                            foreach (ParameterMapping mapping in transformation.ParameterMappings)
                            {
                                ifBlock.Line($"{mapping.CreateCode(transformation.OutputParameter)};");
                                if (noCompositeTypeInitialized)
                                {
                                    // If composite type is initialized based on the above logic then it should not be validated.
                                    ifBlock.Line(outputParameter.ModelType.ValidateType(this, outputParameter.Name, outputParameter.IsRequired));
                                }
                            }
                        });
                    }
                })
                .Catch("error", catchAction =>
                {
                    catchAction.Return("callback(error)");
                });
            }
        }
Esempio n. 6
0
 public void ToJS(JSBuilder JS)
 {
     if (this.Component.ActivateSearch)
     {
         JS.Add("bFilter", "true");
     }
     else
     {
         JS.Add("bFilter", "false");
     }
 }
Esempio n. 7
0
        /// <summary>
        /// Generates input mapping code block.
        /// </summary>
        /// <returns></returns>
        public string BuildInputMappings()
        {
            JSBuilder builder = new JSBuilder();
            IEnumerable <ParameterTransformation> transformations = InputParameterTransformation;

            if (AreWeFlatteningParameters(transformations))
            {
                BuildFlattenParameterMappings(builder, transformations);
            }
            else
            {
                BuildGroupedParameterMappings(builder, transformations);
            }
            return(builder.ToString());
        }
Esempio n. 8
0
        private static void BuildFlattenParameterMappings(JSBuilder builder, IEnumerable <ParameterTransformation> transformations)
        {
            foreach (ParameterTransformation transformation in transformations)
            {
                builder.Line($"let {transformation.OutputParameter.Name};");
                builder.If(BuildNullCheckExpression(transformation), ifBlock =>
                {
                    if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                        transformation.OutputParameter.ModelType is CompositeType)
                    {
                        ifBlock.Line($"{transformation.OutputParameter.Name} = new client.models['{transformation.OutputParameter.ModelType.Name}']();");
                    }

                    foreach (ParameterMapping mapping in transformation.ParameterMappings)
                    {
                        ifBlock.Line($"{mapping.CreateCode(transformation.OutputParameter)};");
                    }
                });
            }
        }
Esempio n. 9
0
 public void ToJS(JSBuilder js)
 {
     #region pagination
     if (this.Component.IsPaginable)
     {
         js.Add("bPaginate", "true");
         if (!this.Component.CanDisplayPaginationOptions)
         {
             js.Add("bLengthChange", "false");
         }
         if (this.Component.RowsPerPage != 10)
         {
             js.Add("iDisplayLength", this.Component.RowsPerPage.ToString());
         }
     }
     else
     {
         js.Add("bPaginate", "false");
     }
     #endregion
 }
Esempio n. 10
0
        public void GenerateSampleMethod(JSBuilder builder, bool isBrowser = false)
        {
            Method           method             = GetSampleMethod();
            string           methodGroup        = GetSampleMethodGroupName();
            List <Parameter> requiredParameters = method.LogicalParameters.Where(
                p => p != null && !p.IsClientProperty && !string.IsNullOrWhiteSpace(p.Name) && !p.IsConstant).OrderBy(item => !item.IsRequired).ToList();

            foreach (Parameter param in requiredParameters)
            {
                string parameterName = param.Name;
                if (param.ModelType is CompositeType && !isBrowser)
                {
                    parameterName += $": {ClientPrefix}Models.{param.ModelTypeName}";
                }

                string parameterValue = param.ModelType.InitializeType(param.Name, isBrowser);

                builder.ConstVariable(parameterName, parameterValue);
            }

            builder.FunctionCall($"client.{(string.IsNullOrEmpty(methodGroup) ? "" : $"{methodGroup}.")}{method.Name.ToCamelCase()}", argumentList =>
Esempio n. 11
0
        public void ToJS(JSBuilder js)
        {
            /*
             *  "sLengthMenu": 'Display <select>' +
             *                '<option value="10">10</option>' +
             *                '<option value="20">20</option>' +
             *                '<option value="50">50</option>' +
             *                '<option value="100">100</option>' +
             *                '<option value="-1">all</option>' +
             *                '</select> ids'
             * }
             */
            JSBuilder jsInternal = new JSBuilder();

            #region General
            jsInternal.Add("sProcessing", String.Format("\"{0}\"", Sushi.Resources.Resources.gridProcessing));
            jsInternal.Add("sZeroRecords", String.Format("\"{0}\"", Sushi.Resources.Resources.gridZeroRecords));
            jsInternal.Add("sInfo", String.Format("\"{0}\"", Sushi.Resources.Resources.gridInfo));
            jsInternal.Add("sInfoEmpty", String.Format("\"{0}\"", Sushi.Resources.Resources.gridInfoEmpty));
            jsInternal.Add("sInfoFiltered", String.Format("\"{0}\"", Sushi.Resources.Resources.gridInfoFiltered));
            jsInternal.Add("sInfoPostFix", String.Format("\"{0}\"", Sushi.Resources.Resources.gridInfoPostFix));
            jsInternal.Add("sSearch", String.Format("\"{0}\"", Sushi.Resources.Resources.gridSearch));
            jsInternal.Add("sUrl", String.Format("\"{0}\"", Sushi.Resources.Resources.gridUrl));
            jsInternal.Add("sLengthMenu", String.Format("\"{0}\"", Sushi.Resources.Resources.gridLengthMenu));
            #endregion

            #region pagination
            JSBuilder jsPagination = new JSBuilder();
            jsPagination.Add("sFirst", String.Format("\"{0}\"", Sushi.Resources.Resources.gridFirst));
            jsPagination.Add("sLast", String.Format("\"{0}\"", Sushi.Resources.Resources.gridLast));
            jsPagination.Add("sNext", String.Format("\"{0}\"", Sushi.Resources.Resources.gridNext));
            jsPagination.Add("sPrevious", String.Format("\"{0}\"", Sushi.Resources.Resources.gridPrevious));
            jsInternal.Add("oPaginate", jsPagination.ToLiteralJSObject(true));
            #endregion

            //jsInternal.Add("sLenghtMenu", String.Format("\"{0}\"", Sushi.Resources.Resources.gridLengthMenu));

            js.Add("oLanguage", jsInternal.ToLiteralJSObject(true));
        }
        public static JSBFunction CreateLinkFunction(string baseApiPath, string controller, MethodInfo info, bool useName)
        {
            List <ParameterInfo> paras = info.GetParameters().Where(x => !BodyAttribute.HasAttribute(x)).ToList();

            ParameterInfo bodyParameter = info.GetParameters().FirstOrDefault(x => BodyAttribute.HasAttribute(x));
            string        bodyParaName  = (bodyParameter != null) ? bodyParameter.Name : "";
            BodyAttribute bodyAttr      = null;

            if (bodyParameter != null)
            {
                bodyAttr = BodyAttribute.GetAttribute(bodyParameter);
            }


            List <string> stringParas = paras.Select(x => x.Name).ToList();

            MethodDescriptorAttribute descriptor = MethodDescriptorAttribute.GetDescriptor(info);

            if (descriptor != null)
            {
                //stringParas = new List<string>();

                foreach (string para in descriptor.Parameters)
                {
                    if (!stringParas.Contains(para))
                    {
                        stringParas.Add(para);
                    }
                }

                if (descriptor.HasPostParameter)
                {
                    bodyParaName = descriptor.PostParameter;
                }
            }

            if (RequiresTokenAttribute.HasAttribute(info))
            {
                stringParas.Add("t");
            }

            JSBuilder code = new JSBuilder();

            StringBuilder paraString = new StringBuilder();

            for (int i = 0; i < stringParas.Count; i++)
            {
                if (i == 0)
                {
                    paraString.Append("?");
                }
                else
                {
                    paraString.Append("&");
                }
                paraString.Append(stringParas[i] + "=' + " + stringParas[i] + " + '");
            }

            if (RequiresTokenAttribute.HasAttribute(info))
            {
                code.AddCode("if(!t) t = Sync.Token;");
            }

            string baseUrlPrepend = ((APIBaseUrl != "") ? $"{APIBaseUrl}/" : "");

            if (!string.IsNullOrEmpty(bodyParaName))
            {
                if (bodyAttr != null && bodyAttr.BodyType == BodyType.Raw)
                {
                    if (descriptor != null && descriptor.ResponseType == BodyType.Raw)
                    {
                        code.AddCode($"SyncPostRawRaw('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', {bodyParaName}, callback);");
                    }
                    else
                    {
                        code.AddCode($"SyncPostRawJson('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', {bodyParaName}, callback);");
                    }
                }
                else
                {
                    if (descriptor != null && descriptor.ResponseType == BodyType.Raw)
                    {
                        code.AddCode($"SyncPostJsonRaw('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', {"JSON.stringify(" + bodyParaName + ")"}, callback);");
                    }
                    else
                    {
                        code.AddCode($"SyncPostJson('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', {"JSON.stringify(" + bodyParaName + ")"}, callback);");
                    }
                }
            }
            else
            {
                if (descriptor != null && descriptor.ResponseType == BodyType.Raw)
                {
                    code.AddCode($"SyncGetRaw('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', callback);");
                }
                else
                {
                    code.AddCode($"SyncGetJson('{baseUrlPrepend + controller}/{info.Name}{paraString.ToString()}', callback);");
                }
            }

            if (!string.IsNullOrEmpty(bodyParaName))
            {
                if (stringParas.LastOrDefault() == "t")
                {
                    stringParas.Insert(stringParas.Count - 1, bodyParaName);
                }
                else
                {
                    stringParas.Add(bodyParaName);
                }
            }
            if (stringParas.LastOrDefault() == "t")
            {
                stringParas.Insert(stringParas.Count - 1, "callback");
            }
            else
            {
                stringParas.Add("callback");
            }

            JSBFunction func = new JSBFunction(((useName) ? info.Name : null), code, stringParas.ToArray());

            return(func);
        }
        public string Sync()
        {
            bool isUpdate = false;

            if (Request.Parameters.ContainsKey("update"))
            {
                bool.TryParse(Request.Parameters["update"], out isUpdate);
            }


            if ((Authenticated && !GeneratedSyncAuthorized.ContainsKey(AuthenticationLevel)) || (!Authenticated && string.IsNullOrEmpty(GeneratedSync)))
            {
                JSBObject jsControllers = new JSBObject();

                foreach (ControllerRoute tkv in GetControllers())
                {
                    string controllerPath = tkv.Path;
                    //System.Console.WriteLine(controllerPath);
                    ControllerDescriptor template = tkv.Controller;

                    JSBObject jsController = new JSBObject();

                    foreach (KeyValuePair <string, CallDescriptor> mkv in template.Calls.Where(x => !IgnoreSyncAttribute.HasAttribute(x.Value.Info)))
                    {
                        MethodInfo method = mkv.Value.Info;

                        RequiresTokenAttribute requiresVerify = RequiresTokenAttribute.GetAttribute(method);

                        if (requiresVerify == null || (requiresVerify != null && Authenticated && requiresVerify.LevelRequired <= AuthenticationLevel))
                        {
                            string typeName       = template.ControllerType.Name;
                            string controllerName = typeName.Replace("Controller", "").Replace("`1", "");


                            JSBFunction func = CreateLinkFunction(APIBaseUrl, controllerPath, method, false);

                            if (!jsController.Properties.ContainsKey(method.Name))
                            {
                                jsController.AddFunction(method.Name, func);
                            }
                        }
                    }
                    if (jsController.Properties.Any())
                    {
                        jsControllers.AddObject(template.ControllerType.Name.Replace("Controller", "").Replace("`1", ""), jsController);
                    }
                }

                JSBuilder js = new JSBuilder().AssignVariable("Sync", jsControllers);

                if (!isUpdate)
                {
                    js.DefineFunction("SyncGetJson", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200)
                                /*callback(JSON.parse(ajax.responseText))*/
                                callback(ResolveReferences(ajax.responseText))
                        };
                        ajax.open('GET', url, true);
                        ajax.setRequestHeader('Accept', 'application/json');
                            ajax.send();
                    ", "url", "callback")
                    .DefineFunction("SyncPostJson", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200) {
                                /*callback(JSON.parse(ajax.responseText))*/
                                callback(ResolveReferences(ajax.responseText))
                            }
                        };
                        ajax.open('POST', url, true);
                        ajax.send(data);
                    ", "url", "data", "callback")
                    .DefineFunction("SyncGetRaw", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200)
                                /*callback(JSON.parse(ajax.responseText))*/
                                callback(ajax.responseText)
                        };
                        ajax.open('GET', url, true);
                        ajax.setRequestHeader('Accept', 'application/json');
                            ajax.send();
                    ", "url", "callback")
                    .DefineFunction("SyncPostJsonRaw", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200) {
                                callback(ajax.responseText)
                            }
                        };
                        ajax.open('POST', url, true);
                        ajax.send(data);
                    ", "url", "data", "callback")
                    .DefineFunction("SyncPostRawRaw", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200) {
                                callback(ajax.responseText)
                            }
                        };
                        ajax.open('POST', url, true);
                        ajax.send(data);
                    ", "url", "data", "callback")
                    .DefineFunction("SyncPostRawJson", @"
                        var ajax = new XMLHttpRequest();
                        ajax.onreadystatechange = function () {
                            if (ajax.readyState == 4 && ajax.status == 200) {
                                callback(ResolveReferences(ajax.responseText))
                            }
                        };
                        ajax.open('POST', url, true);
                        ajax.send(data);
                    ", "url", "data", "callback")

                    .DefineFunction("ResolveReferences", @"
                        if (typeof json === 'string')
                            json = JSON.parse(json);

                        var byid = {};
                        var refs = [];
                        json = (function recurse(obj, prop, parent) {
                            if (typeof obj !== 'object' || !obj)
                                return obj;
                            if (Object.prototype.toString.call(obj) === '[object Array]') {
                                for (var i = 0; i < obj.length; i++)
                                    if (typeof obj[i] !== 'object' || !obj[i])
                                        continue;
                                    else if (""$ref "" in obj[i])
                                        obj[i] = recurse(obj[i], i, obj);
                                    else
                                        obj[i] = recurse(obj[i], prop, obj);
                                    return obj;
                                }
                                if (""$ref"" in obj) {
                                    var ref = obj.$ref;
                                    if (ref in byid)
                                    return byid[ref];
                                    refs.push([parent, prop, ref]);
                                    return;
                                } else if (""$id"" in obj) {
                                    var id = obj.$id;
                                    delete obj.$id;
                                    if (""$values"" in obj)
                                    obj = obj.$values.map(recurse);
                                else
                                    for (var prop in obj)
                                        obj[prop] = recurse(obj[prop], prop, obj);
                                    byid[id] = obj;
                                }
                                return obj;
                            })(json);

                        for (var i = 0; i<refs.length; i++) {
                            var ref = refs[i];
                            ref[0][ref[1]] = byid[ref[2]];
                        }
                        return json;", "json");
                }


                if (Authenticated)
                {
                    GeneratedSyncAuthorized.Add(AuthenticationLevel, js.BuildCode());
                }
                else
                {
                    GeneratedSync = js.BuildCode();
                }
            }

            Request.Response.ContentType = "application/javascript";

            string addition = "";

            if (Authenticated)
            {
                addition += $"Sync.Token = '{Token.UrlEncode()}';";
            }

            if (isUpdate)
            {
                return(((Authenticated) ? GeneratedSyncAuthorized[AuthenticationLevel] : GeneratedSync) + "\n" + addition);
            }
            else
            {
                return(((Authenticated) ? "var " + GeneratedSyncAuthorized[AuthenticationLevel] : "var " + GeneratedSync) + "\n" + addition);
            }
        }