Example #1
0
        private JToken GetOptions()
        {
            string physicalDirectory = HostingEnvironment.MapPath("~/" + VirtualDirectory);
            JToken optionsJson       = null;
            // default options
            string optionsFilename = physicalDirectory + "\\" + (string.IsNullOrEmpty(Prefix) ? "" : Prefix + "-") + "options.json";

            if (File.Exists(optionsFilename))
            {
                string fileContent = File.ReadAllText(optionsFilename);
                if (!string.IsNullOrWhiteSpace(fileContent))
                {
                    optionsJson = JObject.Parse(fileContent);
                }
            }
            // language options
            optionsFilename = physicalDirectory + "\\" + (string.IsNullOrEmpty(Prefix) ? "" : Prefix + "-") + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json";
            if (File.Exists(optionsFilename))
            {
                string fileContent = File.ReadAllText(optionsFilename);
                if (!string.IsNullOrWhiteSpace(fileContent))
                {
                    if (optionsJson == null)
                    {
                        optionsJson = JObject.Parse(fileContent);
                    }
                    else
                    {
                        optionsJson = optionsJson.JsonMerge(JObject.Parse(fileContent));
                    }
                }
            }
            return(optionsJson);
        }
Example #2
0
        protected void ExtendModel(JObject model, bool onlyData, bool onlyMainData)
        {
            if (_module.CanvasUnavailable)
            {
                onlyData = true;
            }

            if (_templateFiles != null)
            {
                // include additional data in the Model
                if (_templateFiles.AdditionalDataInTemplate && _manifest.AdditionalDataDefined())
                {
                    model["AdditionalData"] = GetAdditionalData(onlyData);
                }
                // include collections
                if (_templateFiles.Model != null)
                {
                    var additionalCollections = _templateFiles.Model.Where(c => c.Key != _collection);
                    if (additionalCollections.Any())
                    {
                        var collections  = model["Collections"] = new JObject();
                        var dsColContext = OpenContentUtils.CreateDataContext(_module);
                        foreach (var item in additionalCollections)
                        {
                            var colManifest = item.Value;
                            dsColContext.Collection = item.Key;
                            Select select = null;
                            if (item.Value.Query != null)
                            {
                                var          indexConfig  = OpenContentUtils.GetIndexConfig(_module.Settings.TemplateDir, item.Key);
                                QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                                var          u            = PortalSettings.Current.UserInfo;
                                queryBuilder.Build(item.Value.Query, true, u.UserID, DnnLanguageUtils.GetCurrentCultureCode(), u.Social.Roles.FromDnnRoles());
                                select = queryBuilder.Select;
                            }
                            IDataItems dataItems   = _ds.GetAll(dsColContext, select);
                            var        colDataJson = new JArray();
                            foreach (var dataItem in dataItems.Items)
                            {
                                var json = dataItem.Data;
                                if (json != null)
                                {
                                    JsonUtils.SimplifyJson(json, GetCurrentCultureCode());
                                }
                                if (json is JObject)
                                {
                                    JObject context = new JObject();
                                    json["Context"] = context;
                                    context["Id"]   = dataItem.Id;
                                    EnhanceSelect2(json as JObject, onlyData);
                                    JsonUtils.SimplifyJson(json, GetCurrentCultureCode());
                                }
                                colDataJson.Add(json);
                            }
                            collections[item.Key]          = new JObject();
                            collections[item.Key]["Items"] = colDataJson;
                        }
                    }
                }
            }
            // include settings in the Model
            if (!onlyMainData && _templateManifest != null && _templateManifest.SettingsNeeded() && !string.IsNullOrEmpty(_settingsJson))
            {
                try
                {
                    var jsonSettings = JToken.Parse(_settingsJson);
                    if (DnnLanguageUtils.GetPortalLocales(_portalId).Count > 1)
                    {
                        JsonUtils.SimplifyJson(jsonSettings, GetCurrentCultureCode());
                    }
                    model["Settings"] = jsonSettings;
                }
                catch (Exception ex)
                {
                    throw new Exception("Error parsing Json of Settings", ex);
                }
            }

            // include static localization in the Model
            if (!onlyMainData)
            {
                var localizationJson = LocalizationUtils.LoadLocalizationJson(_module.Settings.TemplateDir, GetCurrentCultureCode());
                if (localizationJson != null)
                {
                    model["Localization"] = localizationJson;
                }
            }
            if (!onlyData)
            {
                // include CONTEXT in the Model
                JObject context = new JObject();
                model["Context"]        = context;
                context["TabId"]        = _module.ViewModule.TabId;
                context["ModuleId"]     = _module.ViewModule.ModuleId;
                context["GoogleApiKey"] = App.Services.CreateGlobalSettingsRepository(_portalId).GetGoogleApiKey();
                context["ModuleTitle"]  = _module.ViewModule.ModuleTitle;
                var editIsAllowed = !_manifest.DisableEdit && IsEditAllowed(-1);
                context["IsEditable"]    = editIsAllowed; //allowed to edit the item or list (meaning allow Add)
                context["IsEditMode"]    = IsEditMode;
                context["PortalId"]      = _portalId;
                context["MainUrl"]       = _module.GetUrl(_detailTabId, GetCurrentCultureCode());
                context["HomeDirectory"] = _module.HomeDirectory;
                context["HTTPAlias"]     = _module.HostName;
                context["PortalName"]    = _module.PortalName;
            }
        }
        public HttpResponseMessage GetExcel(int moduleId, int tabId, string template, string fileName)
        {
            IEnumerable <IDataItem> dataList = new List <IDataItem>();
            var module   = OpenContentModuleConfig.Create(moduleId, tabId, PortalSettings);
            var manifest = module.Settings.Template.Manifest;

            if (!module.HasAllUsersViewPermissions())
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            bool useLucene = module.Settings.Template.Manifest.Index;

            if (useLucene)
            {
                var indexConfig = OpenContentUtils.GetIndexConfig(module.Settings.Template);

                QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                queryBuilder.Build(module.Settings.Query, PortalSettings.UserMode != PortalSettings.Mode.Edit, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles.FromDnnRoles());
                IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);

                var dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                dataList = dsItems.Items;
            }

            var     mf    = new ModelFactoryMultiple(dataList, null, manifest, null, null, module);
            dynamic model = mf.GetModelAsDictionary(true);

            var    rssTemplate = new FileUri(module.Settings.TemplateDir, template + ".hbs");
            string source      = rssTemplate.FileExists ? FileUriUtils.ReadFileFromDisk(rssTemplate) : GenerateTemplateFromModel(model, rssTemplate);

            HandlebarsEngine hbEngine = new HandlebarsEngine();
            string           res      = hbEngine.Execute(source, model);

            var fileBytes = ExcelUtils.CreateExcel(res);

            return(ExcelUtils.CreateExcelResponseMessage(fileName, fileBytes));
        }
        public HttpResponseMessage GetExcelByQuery(int moduleId, int tabId, string queryName, string filter = null, string sort = null)
        {
            RestSelect restSelect = new RestSelect()
            {
                PageIndex = 0,
                PageSize  = 100000
            };

            if (!string.IsNullOrEmpty(filter))
            {
                restSelect.Query = JsonConvert.DeserializeObject <RestGroup>(filter);
            }
            if (!string.IsNullOrEmpty(sort))
            {
                restSelect.Sort = JsonConvert.DeserializeObject <List <RestSort> >(sort);
            }
            IEnumerable <IDataItem> dataList = new List <IDataItem>();
            var module   = OpenContentModuleConfig.Create(moduleId, tabId, PortalSettings);
            var manifest = module.Settings.Template.Manifest;

            if (!module.HasAllUsersViewPermissions())
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            string filename  = queryName;
            bool   useLucene = module.Settings.Template.Manifest.Index;

            if (useLucene)
            {
                var indexConfig = OpenContentUtils.GetIndexConfig(module.Settings.Template);

                QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                queryBuilder.Build(module.Settings.Query, true, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles.FromDnnRoles());
                RestQueryBuilder.MergeQuery(indexConfig, queryBuilder.Select, restSelect, DnnLanguageUtils.GetCurrentCultureCode());
                IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);

                if (string.IsNullOrEmpty(queryName))
                {
                    var dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                    dataList = dsItems.Items;
                    filename = dsContext.Collection;
                }
                else
                {
                    var qds   = ds as IDataQueries;
                    var query = qds?.GetQueries(dsContext).SingleOrDefault(q => q.Name == queryName);
                    if (query != null)
                    {
                        var dsItems = query.GetAll(dsContext, queryBuilder.Select);
                        dataList = dsItems.Items;
                    }
                }
            }

            var     mf    = new ModelFactoryMultiple(dataList, null, manifest, null, null, module);
            dynamic model = mf.GetModelAsDictionary(true);

            var    rssTemplate = new FileUri(module.Settings.TemplateDir, filename + "-excel.hbs");
            string source      = rssTemplate.FileExists ? FileUriUtils.ReadFileFromDisk(rssTemplate) : GenerateTemplateFromModel(model, rssTemplate);

            HandlebarsEngine hbEngine = new HandlebarsEngine();
            string           res      = hbEngine.Execute(source, model);

            var fileBytes = ExcelUtils.CreateExcel(res);

            return(ExcelUtils.CreateExcelResponseMessage(filename + ".xlsx", fileBytes));
        }
Example #5
0
        private void SaveData()
        {
            TemplateManifest    template = null;
            OpenContentSettings settings = this.OpenContentSettings();
            int  ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
            bool index = false;

            if (settings.TemplateAvailable)
            {
                template = settings.Template;
                index    = settings.Template.Manifest.Index;
            }

            /*
             * FieldConfig indexConfig = null;
             * if (index)
             * {
             *  indexConfig = OpenContentUtils.GetIndexConfig(settings.Template.Key.TemplateDir);
             * }
             */
            var ds        = DataSourceManager.GetDataSource(settings.Manifest.DataSource);
            var dsContext = new DataSourceContext()
            {
                ModuleId       = ModId,
                ActiveModuleId = ModuleContext.ModuleId,
                TemplateFolder = settings.TemplateDir.FolderPath,
                Index          = index,
                UserId         = UserInfo.UserID,
                Config         = settings.Manifest.DataSourceConfig
            };

            if (template != null && template.IsListTemplate)
            {
                string itemId = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(itemId))
                {
                    var dsItem = ds.Get(dsContext, itemId);
                    if (string.IsNullOrEmpty(txtSource.Text))
                    {
                        if (dsItem != null)
                        {
                            ds.Delete(dsContext, dsItem);
                        }
                    }
                    else
                    {
                        var json = txtSource.Text.ToJObject("Saving txtSource");
                        if (dsItem == null)
                        {
                            ds.Add(dsContext, json);
                        }
                        else
                        {
                            ds.Update(dsContext, dsItem, json);
                        }
                        if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
                        {
                            string ModuleTitle = json["ModuleTitle"].ToString();
                            OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                        }
                        else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
                        {
                            string ModuleTitle = json["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString();
                            OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                        }
                    }
                }
                else
                {
                    JArray lst = null;
                    if (!string.IsNullOrEmpty(txtSource.Text))
                    {
                        lst = JArray.Parse(txtSource.Text);
                    }
                    var dataList = ds.GetAll(dsContext, null).Items;
                    foreach (var item in dataList)
                    {
                        ds.Delete(dsContext, item);
                    }
                    if (lst != null)
                    {
                        foreach (JObject json in lst)
                        {
                            ds.Add(dsContext, json);
                        }
                    }
                }
            }
            else
            {
                dsContext.Single = true;
                var dsItem = ds.Get(dsContext, null);
                if (string.IsNullOrEmpty(txtSource.Text))
                {
                    if (dsItem != null)
                    {
                        ds.Delete(dsContext, dsItem);
                    }
                }
                else
                {
                    var json = txtSource.Text.ToJObject("Saving txtSource");
                    if (dsItem == null)
                    {
                        ds.Add(dsContext, json);
                    }
                    else
                    {
                        ds.Update(dsContext, dsItem, json);
                    }
                    if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
                    {
                        string ModuleTitle = json["ModuleTitle"].ToString();
                        OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                    }
                    else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
                    {
                        string ModuleTitle = json["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString();
                        OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                    }
                }
            }
        }
Example #6
0
        private FieldConfig CreateFieldConfigFromSchemaAndOptionFile(string key)
        {
            var          newConfig    = new FieldConfig(true);
            var          jsonEdit     = Build(key, DnnLanguageUtils.GetCurrentCultureCode(), true, true, false, false);
            SchemaConfig schemaConfig = new SchemaConfig();
            var          schemaJson   = jsonEdit["schema"];

            if (schemaJson != null)
            {
                schemaConfig = schemaJson.ToObject <SchemaConfig>();
            }
            OptionsConfig optionsConfig = new OptionsConfig();
            JToken        optionsJson   = jsonEdit["options"];

            if (optionsJson != null)
            {
                optionsConfig = optionsJson.ToObject <OptionsConfig>();
            }
            foreach (var prop in schemaConfig.Properties)
            {
                OptionsConfig opts = null;
                if (optionsConfig.Fields != null)
                {
                    opts = optionsConfig.Fields.ContainsKey(prop.Key) ? optionsConfig.Fields[prop.Key] : null;
                }

                if (prop.Value.Type == "array")
                {
                    string optType = (opts == null) ? "array" : opts.Type ?? "array";
                    if (prop.Value.Enum != null || optType == "select" || optType == "select2" || optType == "role2")
                    {
                        var newField = new FieldConfig()
                        {
                            Items = new FieldConfig()
                            {
                                IndexType = "key",
                                Index     = true,
                                Sort      = true
                            },
                            Index = true,
                            Sort  = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                }
                else
                {
                    string optType = (opts == null) ? "text" : opts.Type ?? "text";
                    if (prop.Value.Enum != null || optType == "select" || optType == "select2" || optType == "role2")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "key",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (prop.Value.Type == "boolean")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "boolean",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (prop.Value.Type == "number")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "float",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "text" || optType == "textarea" || optType == "email")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "text",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "wysihtml")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "html",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "ckeditor")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "html",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "mltext")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType     = "text",
                            Index         = true,
                            Sort          = true,
                            MultiLanguage = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "mlwysihtml")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType     = "html",
                            Index         = true,
                            Sort          = true,
                            MultiLanguage = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "mlckeditor")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType     = "html",
                            Index         = true,
                            Sort          = true,
                            MultiLanguage = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                    else if (optType == "date" || optType == "datetime" || optType == "time")
                    {
                        var newField = new FieldConfig()
                        {
                            IndexType = "datetime",
                            Index     = true,
                            Sort      = true
                        };
                        newConfig.Fields.Add(prop.Key, newField);
                    }
                }
            }
            //var json = JObject.FromObject(newConfig);
            //File.WriteAllText(_templateUri.PhysicalFullDirectory + "\\test.json", json.ToString());

            return(newConfig);
        }
Example #7
0
        public JObject BuildQuerySettings(string collection)
        {
            var          indexConfig = OpenContentUtils.GetIndexConfig(_templateUri, collection);
            var          jsonEdit    = Build(collection, DnnLanguageUtils.GetCurrentCultureCode(), true, true, false, false);
            SchemaConfig newSchema   = new SchemaConfig(true);

            // max results
            newSchema.Properties.Add("MaxResults", new SchemaConfig()
            {
                Title = "MaxResults",
                Type  = "number"
            });
            // Default no results
            newSchema.Properties.Add("DefaultNoResults", new SchemaConfig()
            {
                Title = "Default No Results",
                Type  = "boolean"
            });
            // Remove current item
            newSchema.Properties.Add("ExcludeCurrentItem", new SchemaConfig()
            {
                Title = "Exclude Current Item",
                Type  = "boolean"
            });
            // Show only Current User Items
            newSchema.Properties.Add("CurrentUserItems", new SchemaConfig()
            {
                Title = "Only Current User Items",
                Type  = "boolean"
            });
            // Filter
            SchemaConfig newSchemaFilter = new SchemaConfig(true)
            {
                Title = "Filter"
            };

            newSchema.Properties.Add("Filter", newSchemaFilter);
            OptionsConfig newOptions       = new OptionsConfig(true);
            OptionsConfig newOptionsFilter = new OptionsConfig(true);

            newOptions.Fields.Add("Filter", newOptionsFilter);

            SchemaConfig schemaConfig = new SchemaConfig();
            var          schemaJson   = jsonEdit["schema"];

            if (schemaJson != null)
            {
                schemaConfig = schemaJson.ToObject <SchemaConfig>();
            }
            OptionsConfig optionsConfig = new OptionsConfig();
            JToken        optionsJson   = jsonEdit["options"];

            if (optionsJson != null)
            {
                optionsConfig = optionsJson.ToObject <OptionsConfig>();
            }
            List <string> fieldLst = new List <string>();

            GetFields(newSchemaFilter, newOptionsFilter, schemaConfig, optionsConfig, fieldLst, indexConfig);
            // Sort
            SchemaConfig newSchemaSort = new SchemaConfig()
            {
                Type  = "array",
                Title = "Sort"
            };

            newSchema.Properties.Add("Sort", newSchemaSort);

            newSchemaSort.Type  = "array";
            newSchemaSort.Items = new SchemaConfig(true);
            newSchemaSort.Items.Properties.Add("Field", new SchemaConfig()
            {
                Title = "Field",
                Enum  = fieldLst
            });
            newSchemaSort.Items.Properties.Add("Order", new SchemaConfig()
            {
                Title = "Order",
                Enum  = new List <string>(new string[] { "asc", "desc" })
            });

            OptionsConfig newOptionsSort = new OptionsConfig();

            newOptions.Fields.Add("Sort", newOptionsSort);
            newOptionsSort.Type  = "table";
            newOptionsSort.Items = new OptionsConfig(true);
            newOptionsSort.Items.Fields.Add("Field", new OptionsConfig()
            {
                Type = "select",
                RemoveDefaultNone = true
            });
            newOptionsSort.Items.Fields.Add("Order", new OptionsConfig()
            {
                Type = "select",
                RemoveDefaultNone = true
            });

            var json = new JObject();

            json["schema"]  = JObject.FromObject(newSchema);
            json["options"] = JObject.FromObject(newOptions);

            //File.WriteAllText(TemplateUri.PhysicalFullDirectory + "\\test.json", json.ToString());
            return(json);
        }
Example #8
0
        public string GetDataList(RenderInfo info, OpenContentSettings settings, bool clientSide)
        {
            string templateKey = "";

            info.ResetData();
            var ds        = DataSourceManager.GetDataSource(settings.Manifest.DataSource);
            var dsContext = new DataSourceContext()
            {
                ModuleId       = info.ModuleId,
                ActiveModuleId = _module.ModuleID,
                TemplateFolder = settings.TemplateDir.FolderPath,
                Config         = settings.Manifest.DataSourceConfig
            };
            IEnumerable <IDataItem> resultList = new List <IDataItem>();

            if (clientSide || !info.Files.DataInTemplate)
            {
                if (ds.Any(dsContext))
                {
                    info.SetData(resultList, settings.Data);
                    info.DataExist = true;
                }

                if (info.Template.Views != null)
                {
                    var indexConfig = OpenContentUtils.GetIndexConfig(info.Template.Key.TemplateDir);
                    templateKey = GetTemplateKey(indexConfig);
                }
            }
            else
            {
                //server side
                bool useLucene = info.Template.Manifest.Index;
                if (useLucene)
                {
                    PortalSettings portalSettings = PortalSettings.Current;
                    var            indexConfig    = OpenContentUtils.GetIndexConfig(info.Template.Key.TemplateDir);
                    if (info.Template.Views != null)
                    {
                        templateKey = GetTemplateKey(indexConfig);
                    }
                    bool         isEditable   = _module.CheckIfEditable(portalSettings);//portalSettings.UserMode != PortalSettings.Mode.Edit;
                    QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                    queryBuilder.Build(settings.Query, !isEditable, portalSettings.UserId, DnnLanguageUtils.GetCurrentCultureCode(), portalSettings.UserInfo.Social.Roles, QueryString);

                    resultList = ds.GetAll(dsContext, queryBuilder.Select).Items;
                    if (LogContext.IsLogActive)
                    {
                        //LogContext.Log(_module.ModuleID, "RequestContext", "EditMode", !addWorkFlow);
                        LogContext.Log(_module.ModuleID, "RequestContext", "IsEditable", isEditable);
                        LogContext.Log(_module.ModuleID, "RequestContext", "UserRoles", portalSettings.UserInfo.Social.Roles.Select(r => r.RoleName));
                        LogContext.Log(_module.ModuleID, "RequestContext", "CurrentUserId", portalSettings.UserId);
                        var logKey = "Query";
                        LogContext.Log(_module.ModuleID, logKey, "select", queryBuilder.Select);
                        LogContext.Log(_module.ModuleID, logKey, "result", resultList);
                    }
                    //Log.Logger.DebugFormat("Query returned [{0}] results.", total);
                    if (!resultList.Any())
                    {
                        if (ds.Any(dsContext) && settings.Query.IsEmpty())
                        {
                            //there seems to be data in de database, but we did not find it in Lucene, so probably the data isn't indexed anymore/yet
                            Components.Lucene.LuceneController.Instance.ReIndexModuleData(_module.ModuleID, settings);
                        }
                        //Log.Logger.DebugFormat("Query did not return any results. API request: [{0}], Lucene Filter: [{1}], Lucene Query:[{2}]", settings.Query, queryDef.Filter == null ? "" : queryDef.Filter.ToString(), queryDef.Query == null ? "" : queryDef.Query.ToString());
                        if (ds.Any(dsContext))
                        {
                            info.SetData(resultList, settings.Data);
                            info.DataExist = true;
                        }
                    }
                }
                else
                {
                    resultList = ds.GetAll(dsContext, null).Items;
                    if (LogContext.IsLogActive)
                    {
                        var logKey = "Get all data of module";
                        LogContext.Log(_module.ModuleID, logKey, "result", resultList);
                    }
                }
                if (resultList.Any())
                {
                    info.SetData(resultList, settings.Data);
                }
            }
            return(templateKey);
        }
Example #9
0
        public FieldConfig BuildIndex(string key)
        {
            string      prefix    = (string.IsNullOrEmpty(key) || key == "Items") ? "" : key + "-";
            string      cacheKey  = _templateUri.UrlFolder + prefix + "index.json";
            FieldConfig newConfig = (FieldConfig)DataCache.GetCache(cacheKey);

            if (newConfig == null)
            {
                var file = new FileUri(_templateUri.UrlFolder, prefix + "index.json");
                if (file.FileExists)
                {
                    string content = File.ReadAllText(file.PhysicalFilePath);
                    newConfig = JsonConvert.DeserializeObject <FieldConfig>(content);
                    DataCache.SetCache(cacheKey, newConfig, new DNNCacheDependency(file.PhysicalFilePath));
                    return(newConfig);
                }
                else
                {
                    newConfig = new FieldConfig(true);
                    var          jsonEdit     = Build(key, DnnLanguageUtils.GetCurrentCultureCode(), true, true, false, false);
                    SchemaConfig schemaConfig = new SchemaConfig();
                    var          schemaJson   = jsonEdit["schema"];
                    if (schemaJson != null)
                    {
                        schemaConfig = schemaJson.ToObject <SchemaConfig>();
                    }
                    OptionsConfig optionsConfig = new OptionsConfig();
                    JToken        optionsJson   = jsonEdit["options"];
                    if (optionsJson != null)
                    {
                        optionsConfig = optionsJson.ToObject <OptionsConfig>();
                    }
                    foreach (var prop in schemaConfig.Properties)
                    {
                        OptionsConfig opts = null;
                        if (optionsConfig.Fields != null)
                        {
                            opts = optionsConfig.Fields.ContainsKey(prop.Key) ? optionsConfig.Fields[prop.Key] : null;
                        }
                        string optType = (opts == null) ? "text" : opts.Type ?? "text";
                        if (prop.Value.Type == "array" && (prop.Value.Enum != null || optType == "select" || optType == "select2" || optType == "role2"))
                        {
                            var newField = new FieldConfig()
                            {
                                Items = new FieldConfig()
                                {
                                    IndexType = "key",
                                    Index     = true,
                                    Sort      = true
                                }
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (prop.Value.Enum != null || optType == "select" || optType == "select2" || optType == "role2")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "key",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (prop.Value.Type == "boolean")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "boolean",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (prop.Value.Type == "number")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "float",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "text" || optType == "textarea" || optType == "email")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "text",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "wysihtml")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "html",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "ckeditor")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "html",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "mltext")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType     = "text",
                                Index         = true,
                                Sort          = true,
                                MultiLanguage = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "mlwysihtml")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType     = "html",
                                Index         = true,
                                Sort          = true,
                                MultiLanguage = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "mlckeditor")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType     = "html",
                                Index         = true,
                                Sort          = true,
                                MultiLanguage = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                        else if (optType == "date" || optType == "datetime" || optType == "time")
                        {
                            var newField = new FieldConfig()
                            {
                                IndexType = "datetime",
                                Index     = true,
                                Sort      = true
                            };
                            newConfig.Fields.Add(prop.Key, newField);
                        }
                    }
                    //var json = JObject.FromObject(newConfig);
                    //File.WriteAllText(templateUri.PhysicalFullDirectory + "\\test.json", json.ToString());

                    var schemaFile  = new FileUri(_templateUri.UrlFolder, prefix + "schema.json");
                    var optionsFile = new FileUri(_templateUri.UrlFolder, prefix + "options.json");
                    DataCache.SetCache(cacheKey, newConfig, new DNNCacheDependency(new[] { schemaFile.PhysicalFilePath, optionsFile.PhysicalFilePath }));
                }
            }

            return(newConfig);
        }
Example #10
0
        private void BindDetailPage(int currentDetailTabId, int othermoduleTabId, int dataModuleId)
        {
            string   format;
            ListItem li;

            ActivateDetailPage();
            ddlDetailPage.Items.Clear();

            int othermoduleDetailTabId = GetOtherModuleDetailTabId(othermoduleTabId, dataModuleId);

            if (othermoduleDetailTabId > 0)
            {
                //add extra li with "Default Detail Page" directly to dropdown
                format = LogContext.IsLogActive ? "Main Module Detail Page - [{0}]" : "Main Module Detail Page";
                li     = new ListItem(string.Format(format, othermoduleDetailTabId), othermoduleDetailTabId.ToString());
                ddlDetailPage.Items.Add(li);
            }

            var listItems = new List <ListItem>();
            Dictionary <string, int> tabs = TabController.GetTabPathDictionary(ModuleContext.PortalId, DnnLanguageUtils.GetCurrentCultureCode());

            foreach (var tabId in tabs.Where(i => IsTabWithModuleWithSameMainModule(i.Value, dataModuleId) && IsAccessibleTab(i.Value)))
            {
                string tabname = tabId.Key.Replace("//", " / ").TrimStart(" / ");

                if ((othermoduleTabId > 0 && tabId.Value == othermoduleTabId) || (othermoduleTabId == -1 && tabId.Value == ModuleContext.TabId))
                {
                    //add extra li with "Main Module Page" directly to dropdown
                    format = LogContext.IsLogActive ? "Main Module Page - {0} [{1}]" : "Main Module Page";
                    li     = new ListItem(string.Format(format, tabname, tabId.Value), "-1");
                    ddlDetailPage.Items.Add(li);
                }
                if (othermoduleTabId > 0 && tabId.Value == ModuleContext.TabId)
                {
                    //add extra li with "CurrentPage" directly to dropdown
                    format = LogContext.IsLogActive ? "Current Page - {0} [{1}]" : "Current Page";
                    li     = new ListItem(string.Format(format, tabname, tabId.Value), tabId.Value.ToString());
                    ddlDetailPage.Items.Add(li);
                }

                format = LogContext.IsLogActive ? "{0} [{1}]" : "{0}";
                li     = new ListItem(string.Format(format, tabname, tabId.Value), tabId.Value.ToString());

                listItems.Add(li);
                if (tabId.Value == currentDetailTabId)
                {
                    li.Selected = true;
                }
            }
            foreach (ListItem listItem in listItems.OrderBy(x => x.Text))
            {
                ddlDetailPage.Items.Add(listItem);
            }
        }
        protected void ExtendModel(JObject model, bool onlyData)
        {
            if (_portalSettings == null)
            {
                onlyData = true;
            }

            if (_templateFiles != null)
            {
                // include additional data in the Model
                if (_templateFiles.AdditionalDataInTemplate && _manifest.AdditionalDataDefined())
                {
                    model["AdditionalData"] = GetAdditionalData();
                }
                // include collections
                if (_templateFiles.Model != null)
                {
                    var additionalCollections = _templateFiles.Model.Where(c => c.Key != _collection);
                    if (additionalCollections.Any())
                    {
                        var collections  = model["Collections"] = new JObject();
                        var dsColContext = OpenContentUtils.CreateDataContext(_module);
                        foreach (var item in additionalCollections)
                        {
                            var colManifest = item.Value;
                            dsColContext.Collection = item.Key;
                            Select select = null;
                            if (item.Value.Query != null)
                            {
                                var          indexConfig  = OpenContentUtils.GetIndexConfig(_module.Settings.TemplateDir, item.Key);
                                QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                                var          u            = PortalSettings.Current.UserInfo;
                                queryBuilder.Build(item.Value.Query, true, u.UserID, DnnLanguageUtils.GetCurrentCultureCode(), u.Social.Roles);
                                select = queryBuilder.Select;
                            }
                            IDataItems dataItems   = _ds.GetAll(dsColContext, select);
                            var        colDataJson = new JArray();
                            foreach (var dataItem in dataItems.Items)
                            {
                                var json = dataItem.Data;

                                if (json != null && LocaleController.Instance.GetLocales(_portalId).Count > 1)
                                {
                                    JsonUtils.SimplifyJson(json, GetCurrentCultureCode());
                                }
                                if (json is JObject)
                                {
                                    JObject context = new JObject();
                                    json["Context"] = context;
                                    context["Id"]   = dataItem.Id;
                                    EnhanceSelect2(json as JObject);
                                }
                                colDataJson.Add(json);
                            }
                            collections[item.Key]          = new JObject();
                            collections[item.Key]["Items"] = colDataJson;
                        }
                    }
                }
            }
            // include settings in the Model
            if (!onlyData && _templateManifest.SettingsNeeded() && !string.IsNullOrEmpty(_settingsJson))
            {
                try
                {
                    var jsonSettings = JToken.Parse(_settingsJson);
                    if (LocaleController.Instance.GetLocales(_portalId).Count > 1)
                    {
                        JsonUtils.SimplifyJson(jsonSettings, GetCurrentCultureCode());
                    }
                    model["Settings"] = jsonSettings;
                }
                catch (Exception ex)
                {
                    throw new Exception("Error parsing Json of Settings", ex);
                }
            }

            // include static localization in the Model
            if (!onlyData)
            {
                JToken localizationJson     = null;
                string localizationFilename = _physicalTemplateFolder + GetCurrentCultureCode() + ".json";
                if (File.Exists(localizationFilename))
                {
                    string fileContent = File.ReadAllText(localizationFilename);
                    if (!string.IsNullOrWhiteSpace(fileContent))
                    {
                        localizationJson = fileContent.ToJObject("Localization: " + localizationFilename);
                    }
                }
                if (localizationJson != null)
                {
                    model["Localization"] = localizationJson;
                }
            }
            if (!onlyData)
            {
                // include CONTEXT in the Model
                JObject context = new JObject();
                model["Context"]        = context;
                context["ModuleId"]     = _module.ViewModule.ModuleID;
                context["GoogleApiKey"] = OpenContentControllerFactory.Instance.OpenContentGlobalSettingsController(_portalId).GetGoogleApiKey();
                context["ModuleTitle"]  = _module.ViewModule.ModuleTitle;
                var editIsAllowed = !_manifest.DisableEdit && IsEditAllowed(-1);
                context["IsEditable"]    = editIsAllowed; //allowed to edit the item or list (meaning allow Add)
                context["IsEditMode"]    = IsEditMode;
                context["PortalId"]      = _portalId;
                context["MainUrl"]       = Globals.NavigateURL(_detailTabId, false, _portalSettings, "", GetCurrentCultureCode());
                context["HomeDirectory"] = _portalSettings.HomeDirectory;
                context["HTTPAlias"]     = _portalSettings.PortalAlias.HTTPAlias;
            }
        }
Example #12
0
        private void SaveData()
        {
            var module   = new OpenContentModuleInfo(this.ModuleConfiguration);
            var manifest = module.Settings.Manifest;
            TemplateManifest template = module.Settings.Template;
            string           editRole = manifest.GetEditRole();
            bool             listMode = template != null && template.IsListTemplate;

            IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
            var         dsContext = OpenContentUtils.CreateDataContext(module);



            if (template != null && template.IsListTemplate)
            {
                string itemId = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(itemId))
                {
                    var dsItem = ds.Get(dsContext, itemId);
                    if (string.IsNullOrEmpty(txtSource.Text))
                    {
                        if (dsItem != null)
                        {
                            ds.Delete(dsContext, dsItem);
                        }
                    }
                    else
                    {
                        var json = txtSource.Text.ToJObject("Saving txtSource");
                        if (dsItem == null)
                        {
                            ds.Add(dsContext, json);
                        }
                        else
                        {
                            ds.Update(dsContext, dsItem, json);
                        }
                        if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
                        {
                            string ModuleTitle = json["ModuleTitle"].ToString();
                            OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                        }
                        else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
                        {
                            string ModuleTitle = json["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString();
                            OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                        }
                    }
                }
                else
                {
                    JArray lst = null;
                    if (!string.IsNullOrEmpty(txtSource.Text))
                    {
                        lst = JArray.Parse(txtSource.Text);
                    }
                    var dataList = ds.GetAll(dsContext, null).Items;
                    foreach (var item in dataList)
                    {
                        ds.Delete(dsContext, item);
                    }
                    if (lst != null)
                    {
                        foreach (JObject json in lst)
                        {
                            ds.Add(dsContext, json);
                        }
                    }
                }
            }
            else
            {
                dsContext.Single = true;
                var dsItem = ds.Get(dsContext, null);
                if (string.IsNullOrEmpty(txtSource.Text))
                {
                    if (dsItem != null)
                    {
                        ds.Delete(dsContext, dsItem);
                    }
                }
                else
                {
                    var json = txtSource.Text.ToJObject("Saving txtSource");
                    if (dsItem == null)
                    {
                        ds.Add(dsContext, json);
                    }
                    else
                    {
                        ds.Update(dsContext, dsItem, json);
                    }
                    if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
                    {
                        string ModuleTitle = json["ModuleTitle"].ToString();
                        OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                    }
                    else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
                    {
                        string ModuleTitle = json["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString();
                        OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
                    }
                }
            }
        }
        public HttpResponseMessage List(RequestDTO req)
        {
            try
            {
                OpenContentModuleConfig module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings);
                JObject reqOptions             = null;
                if (!string.IsNullOrEmpty(req.options))
                {
                    reqOptions = JObject.Parse(req.options);
                }
                if (module.IsListMode())
                {
                    var          indexConfig  = OpenContentUtils.GetIndexConfig(module.Settings.Template);
                    QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                    bool         isEditable   = module.ViewModule.CheckIfEditable(module);
                    queryBuilder.Build(module.Settings.Query, !isEditable, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles.FromDnnRoles());

                    JplistQueryBuilder.MergeJpListQuery(indexConfig, queryBuilder.Select, req.StatusLst, DnnLanguageUtils.GetCurrentCultureCode());
                    IDataItems dsItems;
                    if (queryBuilder.DefaultNoResults && queryBuilder.Select.IsEmptyQuery)
                    {
                        dsItems = new DefaultDataItems()
                        {
                            Items = new List <DefaultDataItem>(),
                            Total = 0
                        };
                    }
                    else
                    {
                        IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                        var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID, false, reqOptions);
                        dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                    }
                    var mf = new ModelFactoryMultiple(dsItems.Items, module);
                    mf.Options = reqOptions;
                    var model = mf.GetModelAsJson(false, req.onlyItems);

                    //model["luceneQuery"] = dsItems.DebugInfo;
                    if (LogContext.IsLogActive)
                    {
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "IsEditable", isEditable);
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "UserRoles", PortalSettings.UserInfo.Social.Roles.Select(r => r.RoleName));
                        LogContext.Log(ActiveModule.ModuleID, "RequestContext", "CurrentUserId", PortalSettings.UserId);
                        var logKey = "Query";
                        LogContext.Log(ActiveModule.ModuleID, logKey, "select", queryBuilder.Select);
                        LogContext.Log(ActiveModule.ModuleID, logKey, "debuginfo", dsItems.DebugInfo);
                        LogContext.Log(ActiveModule.ModuleID, logKey, "model", model);
                        model["Logs"] = JToken.FromObject(LogContext.Current.ModuleLogs(ActiveModule.ModuleID));
                    }
                    var res = new ResultDTO()
                    {
                        data  = model,
                        count = dsItems.Total
                    };
                    return(Request.CreateResponse(HttpStatusCode.OK, res));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "not supported because not in multi items template "));
                }
            }
            catch (Exception exc)
            {
                App.Services.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
Example #14
0
        private string GetDataList(RenderInfo info, OpenContentModuleConfig ocModuleConfig)
        {
            var    clientSide  = info.Template.ClientSideData;
            string templateKey = "";

            info.ResetData();

            IDataSource ds        = DataSourceManager.GetDataSource(_settings.Manifest.DataSource);
            var         dsContext = OpenContentUtils.CreateDataContext(ocModuleConfig);

            IEnumerable <IDataItem> resultList = new List <IDataItem>();

            if (clientSide || !info.Files.DataInTemplate)
            {
                if (ds.Any(dsContext))
                {
                    info.SetData(resultList, ocModuleConfig.Settings.Data);
                    info.DataExist = true;
                }

                if (info.Template.Views != null)
                {
                    var indexConfig = OpenContentUtils.GetIndexConfig(info.Template);
                    templateKey = GetTemplateKey(indexConfig);
                }
            }
            else
            {
                //server side
                bool useLucene = info.Template.Manifest.Index;
                if (useLucene)
                {
                    var indexConfig = OpenContentUtils.GetIndexConfig(info.Template);
                    if (info.Template.Views != null)
                    {
                        templateKey = GetTemplateKey(indexConfig);
                    }
                    bool         isEditable   = _module.ViewModule.CheckIfEditable(ocModuleConfig);
                    QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                    queryBuilder.Build(ocModuleConfig.Settings.Query, !isEditable, ocModuleConfig.UserId, DnnLanguageUtils.GetCurrentCultureCode(), ocModuleConfig.UserRoles.FromDnnRoles(), QueryString);

                    resultList = ds.GetAll(dsContext, queryBuilder.Select).Items;
                    if (LogContext.IsLogActive)
                    {
                        //LogContext.Log(_module.ModuleID, "RequestContext", "EditMode", !addWorkFlow);
                        LogContext.Log(_module.ViewModule.ModuleId, "RequestContext", "IsEditable", isEditable);
                        LogContext.Log(_module.ViewModule.ModuleId, "RequestContext", "UserRoles", ocModuleConfig.UserRoles.Select(r => r.RoleName));
                        LogContext.Log(_module.ViewModule.ModuleId, "RequestContext", "CurrentUserId", ocModuleConfig.UserId);
                        var logKey = "Query";
                        LogContext.Log(_module.ViewModule.ModuleId, logKey, "select", queryBuilder.Select);
                        //LogContext.Log(_module.ModuleID, logKey, "result", resultList);
                    }
                    //App.Services.Logger.Debug($"Query returned [{0}] results.", total);
                    if (!resultList.Any())
                    {
                        //App.Services.Logger.Debug($"Query did not return any results. API request: [{0}], Lucene Filter: [{1}], Lucene Query:[{2}]", settings.Query, queryDef.Filter == null ? "" : queryDef.Filter.ToString(), queryDef.Query == null ? "" : queryDef.Query.ToString());
                        if (ds.Any(dsContext))
                        {
                            info.SetData(resultList, ocModuleConfig.Settings.Data);
                            info.DataExist = true;
                        }
                    }
                }
                else
                {
                    resultList = ds.GetAll(dsContext, null).Items;
                    //if (LogContext.IsLogActive)
                    //{
                    //    var logKey = "Get all data of module";
                    //    LogContext.Log(_module.ModuleID, logKey, "result", resultList);
                    //}
                }
                if (resultList.Any())
                {
                    info.SetData(resultList, ocModuleConfig.Settings.Data);
                }
            }
            return(templateKey);
        }
Example #15
0
 public JObject BuildForm(string key)
 {
     return(Build(key, DnnLanguageUtils.GetCurrentCultureCode(), true, true, true, true));
 }
Example #16
0
        internal static JObject GetSchemaAndOptionsJson(FolderUri desktopFolder, FolderUri portalFolder, string prefix)
        {
            JObject json = new JObject();

            if (!portalFolder.FolderExists)
            {
                Directory.CreateDirectory(portalFolder.PhysicalFullDirectory);
            }
            if (!string.IsNullOrEmpty(prefix))
            {
                prefix = prefix + "-";
            }
            // schema
            string schemaFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "schema.json";

            if (!File.Exists(schemaFilename))
            {
                schemaFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "schema.json";
            }
            JObject schemaJson = JObject.Parse(File.ReadAllText(schemaFilename));

            json["schema"] = schemaJson;
            // default options
            string optionsFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "options.json";

            if (!File.Exists(optionsFilename))
            {
                optionsFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "options.json";
            }
            if (File.Exists(optionsFilename))
            {
                string fileContent = File.ReadAllText(optionsFilename);
                if (!string.IsNullOrWhiteSpace(fileContent))
                {
                    JObject optionsJson = JObject.Parse(fileContent);
                    json["options"] = optionsJson;
                }
            }
            // language options
            optionsFilename = portalFolder.PhysicalFullDirectory + "\\" + prefix + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json";
            if (!File.Exists(optionsFilename))
            {
                optionsFilename = desktopFolder.PhysicalFullDirectory + "\\" + prefix + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json";
            }
            if (File.Exists(optionsFilename))
            {
                string fileContent = File.ReadAllText(optionsFilename);
                if (!string.IsNullOrWhiteSpace(fileContent))
                {
                    JObject optionsJson = JObject.Parse(fileContent);
                    json["options"] = json["options"].JsonMerge(optionsJson);
                }
            }
            return(json);
        }
Example #17
0
 private JObject Build()
 {
     return(Build("", DnnLanguageUtils.GetCurrentCultureCode(), true, true, true, true));
 }
Example #18
0
        public HttpResponseMessage Get(string entity, int pageIndex, int pageSize, string filter = null, string sort = null)
        {
            try
            {
                var        collection = entity;
                RestSelect restSelect = new RestSelect()
                {
                    PageIndex = pageIndex,
                    PageSize  = pageSize
                };
                if (!string.IsNullOrEmpty(filter))
                {
                    restSelect.Query = JsonConvert.DeserializeObject <RestGroup>(filter);
                }
                if (!string.IsNullOrEmpty(sort))
                {
                    restSelect.Sort = JsonConvert.DeserializeObject <List <RestSort> >(sort);
                }

                ModuleInfo activeModule = ActiveModule;

                OpenContentSettings   settings = activeModule.OpenContentSettings();
                OpenContentModuleInfo module   = new OpenContentModuleInfo(ActiveModule);
                JObject reqOptions             = null;

                if (module.IsListMode())
                {
                    var          indexConfig  = OpenContentUtils.GetIndexConfig(settings.TemplateDir, collection);
                    QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                    bool         isEditable   = ActiveModule.CheckIfEditable(PortalSettings);
                    queryBuilder.Build(settings.Query, !isEditable, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles);

                    RestQueryBuilder.MergeQuery(indexConfig, queryBuilder.Select, restSelect, DnnLanguageUtils.GetCurrentCultureCode());
                    IDataItems dsItems;
                    if (queryBuilder.DefaultNoResults && queryBuilder.Select.IsQueryEmpty)
                    {
                        dsItems = new DefaultDataItems()
                        {
                            Items = new List <DefaultDataItem>(),
                            Total = 0
                        };
                    }
                    else
                    {
                        IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                        var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID, false, reqOptions);
                        dsContext.Collection = collection;
                        dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                    }
                    var mf = new ModelFactoryMultiple(dsItems.Items, module, PortalSettings, collection);
                    mf.Options = reqOptions;
                    var model = mf.GetModelAsJson(false);
                    var res   = new JObject();
                    res["meta"] = new JObject();
                    if (LogContext.IsLogActive)
                    {
                        var logKey = "Query";
                        LogContext.Log(activeModule.ModuleID, logKey, "select", queryBuilder.Select);
                        LogContext.Log(activeModule.ModuleID, logKey, "debuginfo", dsItems.DebugInfo);
                        LogContext.Log(activeModule.ModuleID, logKey, "model", model);
                        res["meta"]["logs"] = JToken.FromObject(LogContext.Current.ModuleLogs(activeModule.ModuleID));

                        if (restSelect != null)
                        {
                            //res["meta"]["select"] = JObject.FromObject(restSelect);
                        }
                    }
                    foreach (var item in model["Items"] as JArray)
                    {
                        item["id"] = item["Context"]["Id"];
                        JsonUtils.IdJson(item);
                    }
                    res[entity]          = model[collection];
                    res["meta"]["total"] = dsItems.Total;
                    return(Request.CreateResponse(HttpStatusCode.OK, res));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "not supported because not in multi items template "));
                }
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
Example #19
0
        private JToken GetOptions()
        {
            string Template         = ModuleContext.Settings["template"] as string;
            string templateFilename = HostingEnvironment.MapPath("~/" + Template);
            //string templateFilename = "~/" + Template;
            string optionsFilename = Path.GetDirectoryName(templateFilename) + "\\" + "options.json";

            // default options
            JToken optionsJson = JsonUtils.GetJsonFromFile(optionsFilename);


            // language options
            optionsFilename = Path.GetDirectoryName(templateFilename) + "\\" + $"options.{DnnLanguageUtils.GetCurrentCultureCode()}.json";
            if (File.Exists(optionsFilename))
            {
                JToken languageOptionsJson = JsonUtils.GetJsonFromFile(optionsFilename);
                optionsJson = optionsJson.JsonMerge(languageOptionsJson);
            }
            return(optionsJson);
        }