public HttpResponseMessage Post(string entity, [FromBody] JObject value) { // Add try { var collection = entity; OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); var manifest = module.Settings.Template.Manifest; string editRole = manifest.GetEditRole(); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = collection; if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, -1)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } ds.Add(dsContext, value.Properties().First().Value as JObject); return(Request.CreateResponse(HttpStatusCode.OK, "")); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public static bool CheckIfEditable(this OpenContentModuleInfo dataModule, OpenContentModuleConfig ocModuleConfig) { bool isEditable; //first check some weird Dnn issue if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) { var personalization = (PersonalizationInfo)HttpContext.Current.Items["Personalization"]; if (personalization != null && personalization.UserId == -1) { //this should never happen. //Let us make sure that the wrong value is no longer cached HttpContext.Current.Items.Remove("Personalization"); } } bool blnPreview = ocModuleConfig.PreviewEnabled; if (Globals.IsHostTab(ocModuleConfig.TabId)) { blnPreview = false; } bool blnHasModuleEditPermissions = dataModule.HasEditRightsOnModule(); if (blnPreview == false && blnHasModuleEditPermissions) { isEditable = true; } else { isEditable = false; } return(isEditable); }
private List <dynamic> GetDataAsListOfDynamics() { var module = new OpenContentModuleInfo(this.ModuleConfiguration); OpenContentController ctrl = new OpenContentController(ModuleContext.PortalId); var data = ctrl.GetContents(module.DataModule.ModuleID, "Submissions").OrderByDescending(c => c.CreatedOnDate); var dynData = new List <dynamic>(); foreach (var item in data) { dynamic o = new ExpandoObject(); var dict = (IDictionary <string, object>)o; o.CreatedOnDate = item.CreatedOnDate; o.Title = item.Title; //o.Json = item.Json; dynamic d = JsonUtils.JsonToDynamic(item.Json); //o.Data = d; Dictionary <String, Object> jdic = Dyn2Dict(d); foreach (var p in jdic) { dict[p.Key] = p.Value; } dynData.Add(o); } return(dynData); }
private void IndexModule(LuceneController lc, OpenContentModuleInfo module) { OpenContentUtils.CheckOpenContentSettings(module); if (module.IsListMode() && !module.Settings.IsOtherModule) { IndexModuleData(lc, module.ViewModule.ModuleID, module.Settings); } }
public HttpResponseMessage Put(string entity, string id, [FromBody] JObject value) { // update try { OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem dsItem = null; if (module.IsListMode()) { if (id != null) { var itemId = id; dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } if (dsItem == null) { ds.Add(dsContext, value.Properties().First().Value as JObject); } else { ds.Update(dsContext, dsItem, value.Properties().First().Value as JObject); } return(Request.CreateResponse(HttpStatusCode.OK, "")); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Put(string entity, string id, string memberAction, [FromBody] JObject value) { // action try { var collection = entity; OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = collection; IDataItem dsItem = null; if (module.IsListMode()) { if (id != null) { var itemId = id; dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); //dsItem = ctrl.GetFirstContent(module.ModuleID); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } //var indexConfig = OpenContentUtils.GetIndexConfig(settings.Template.Key.TemplateDir); JToken res = null; if (dsItem != null) { res = ds.Action(dsContext, memberAction, dsItem, value); } return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Post(string entity, [FromBody] JObject value) { // Add try { OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); var manifest = module.Settings.Template.Manifest; string editRole = manifest.GetEditRole(); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, -1)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } ds.Add(dsContext, value.Properties().First().Value as JObject); var dsItem = ds.Get(dsContext, dsContext.Id); var res = new JObject(); res["meta"] = new JObject(); var items = new JArray(); if (dsItem != null) { var collection = AppConfig.DEFAULT_COLLECTION; var mf = new ModelFactorySingle(dsItem, module, PortalSettings, collection); var model = mf.GetModelAsJson(false); items.Add(model); model["id"] = dsContext.Id; res["meta"]["total"] = dsItem == null ? 0 : 1; JsonUtils.IdJson(model); if (LogContext.IsLogActive) { var logKey = "Query"; LogContext.Log(module.ViewModule.ModuleID, logKey, "model", model); res["meta"]["logs"] = JToken.FromObject(LogContext.Current.ModuleLogs(module.ViewModule.ModuleID)); } } res[entity] = items; return(Request.CreateResponse(HttpStatusCode.OK, res)); //return Request.CreateResponse(HttpStatusCode.OK, ""); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Delete(string entity, string id) { try { OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem dsItem = null; if (module.IsListMode()) { if (id != null) { var itemId = id; dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } //var indexConfig = OpenContentUtils.GetIndexConfig(settings.Template.Key.TemplateDir); if (dsItem != null) { ds.Delete(dsContext, dsItem); } return(Request.CreateResponse(HttpStatusCode.OK, "")); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public ModelFactoryBase(string settingsJson, string physicalTemplateFolder, Manifest.Manifest manifest, TemplateManifest templateManifest, TemplateFiles templateFiles, OpenContentModuleInfo module, int portalId, string cultureCode) { this._settingsJson = settingsJson; this._physicalTemplateFolder = physicalTemplateFolder; this._manifest = manifest; this._templateFiles = templateFiles; this._module = module; this._cultureCode = cultureCode; this._portalId = portalId; this._templateManifest = templateManifest; this._collection = templateManifest.Collection; this._detailTabId = DnnUtils.GetTabByCurrentCulture(this._portalId, module.GetDetailTabId(), GetCurrentCultureCode()); _ds = DataSourceManager.GetDataSource(_manifest.DataSource); _dsContext = OpenContentUtils.CreateDataContext(_module); }
/// <summary> /// Determines whether current logged in user has edit rights on module. /// </summary> /// <remarks></remarks> public static bool HasEditRightsOnModule(this OpenContentModuleInfo activeModule) { bool blnHasModuleEditPermissions = false; if (activeModule != null) { //DNN already checks SuperUser and Administrator var moduleInfo = DnnUtils.GetDnnModule(activeModule); if (moduleInfo == null) { App.Services.Logger.Error($"Module {activeModule.ModuleId} of tab {activeModule.TabId} was not found while in HasEditRightsOnModule(). StackTrace: {Environment.StackTrace}"); throw new Exception($"(Other)Module was not found. Check your Switch Template config. See log for more info."); } blnHasModuleEditPermissions = ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "CONTENT", moduleInfo); } return(blnHasModuleEditPermissions); }
public ModelFactoryBase(OpenContentModuleInfo module, PortalSettings portalSettings, string collection) { OpenContentSettings settings = module.Settings; this._settingsJson = settings.Data; this._physicalTemplateFolder = settings.Template.ManifestFolderUri.PhysicalFullDirectory + "\\"; this._manifest = settings.Template.Manifest; this._templateFiles = settings.Template?.Main; this._module = module; this._portalSettings = portalSettings; this._portalId = portalSettings.PortalId; this._templateManifest = settings.Template; this._collection = collection; this._detailTabId = DnnUtils.GetTabByCurrentCulture(this._portalId, module.GetDetailTabId(), GetCurrentCultureCode()); _ds = DataSourceManager.GetDataSource(_manifest.DataSource); _dsContext = OpenContentUtils.CreateDataContext(_module); }
public HttpResponseMessage Get(string entity) { try { var collection = entity; OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); var manifest = module.Settings.Manifest; TemplateManifest templateManifest = module.Settings.Template; if (manifest.AdditionalDataDefined(entity)) { var dataManifest = manifest.AdditionalDataDefinition[entity]; //string scope = AdditionalDataUtils.GetScope(dataManifest, PortalSettings.PortalId, ActiveModule.TabID, module.ModuleID, ActiveModule.TabModuleID); //var templateFolder = string.IsNullOrEmpty(dataManifest.TemplateFolder) ? settings.TemplateDir : settings.TemplateDir.ParentFolder.Append(dataManifest.TemplateFolder); //var fb = new FormBuilder(templateFolder); //JObject json = fb.BuildForm(entity); var res = new JObject(); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = collection; var dsItem = ds.GetData(dsContext, dataManifest.ScopeType, dataManifest.StorageKey ?? entity); if (dsItem != null) { var json = dsItem.Data; //JsonUtils.IdJson(json); res[entity] = json; } return(Request.CreateResponse(HttpStatusCode.OK, res)); } else { return(Get(entity, 0, 100, null, null)); } } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage GetExcel(int moduleId, int tabId, string template, string fileName) { ModuleController mc = new ModuleController(); IEnumerable <IDataItem> dataList = new List <IDataItem>(); var module = new OpenContentModuleInfo(moduleId, tabId); var manifest = module.Settings.Template.Manifest; if (!OpenContentUtils.HasAllUsersViewPermissions(PortalSettings, module.ViewModule)) { 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); 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, module.Settings.TemplateDir.PhysicalFullDirectory, manifest, null, null, module, PortalSettings); dynamic model = mf.GetModelAsDictionary(true); var rssTemplate = new FileUri(module.Settings.TemplateDir, template + ".hbs"); string source = rssTemplate.FileExists ? FileUriUtils.ReadFileFromDisk(rssTemplate) : GenerateCsvTemplateFromModel(model, rssTemplate); HandlebarsEngine hbEngine = new HandlebarsEngine(); string res = hbEngine.Execute(source, model); var fileBytes = ExcelUtils.OutputFile(res); return(ExcelUtils.CreateExcelResponseMessage(fileName, fileBytes)); }
public HttpResponseMessage GetFeed(int moduleId, int tabId, string template, string mediaType) { ModuleController mc = new ModuleController(); IEnumerable <IDataItem> dataList = new List <IDataItem>(); var module = new OpenContentModuleInfo(moduleId, tabId); var manifest = module.Settings.Template.Manifest; if (!OpenContentUtils.HasAllUsersViewPermissions(PortalSettings, module.ViewModule)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } var rssTemplate = new FileUri(module.Settings.TemplateDir, template + ".hbs"); string source = File.ReadAllText(rssTemplate.PhysicalFilePath); 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); 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, module.Settings.TemplateDir.PhysicalFullDirectory, manifest, null, null, module, PortalSettings); dynamic model = mf.GetModelAsDictionary(false, true); HandlebarsEngine hbEngine = new HandlebarsEngine(); string res = hbEngine.Execute(source, model); var response = new HttpResponseMessage(); response.Content = new StringContent(res); response.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); return(response); }
protected void bIndex_Click(object sender, EventArgs e) { //LuceneController.Instance.ReIndexModuleData(ModuleId, this.OpenContentSettings()); var module = new OpenContentModuleInfo(this.ModuleConfiguration); var settings = module.Settings; bool index = false; if (settings.TemplateAvailable) { index = settings.Manifest.Index; } IDataSource ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource); if (index && ds is IDataIndex) { FieldConfig indexConfig = OpenContentUtils.GetIndexConfig(settings.Template); var dsContext = OpenContentUtils.CreateDataContext(module); var dataIndex = (IDataIndex)ds; dataIndex.Reindex(dsContext); } }
public static void CreateUserForItems(int TabId, int ModuleId, int userToChangeId, string passPrefix, string passSuffix, string roleName, string titlePath, string emailPath, string firstName) { //int ModuleId = 585; // dev 682; //int TabId = 160; // dev 210; ModuleController mc = new ModuleController(); var activeModule = mc.GetModule(ModuleId, TabId, false); if (activeModule != null) { var ocModule = new OpenContentModuleInfo(activeModule); //IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(ocModule); var ds = new OpenContentDataSource(); var items = ds.GetAll(dsContext); foreach (var item in items.Items) { if (item.CreatedByUserId == userToChangeId) { var title = item.Data.SelectToken(titlePath, false)?.ToString(); var email = item.Data.SelectToken(emailPath, false)?.ToString(); if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(email)) { //var name = title.Replace(" ", "").ToLower(); //var password = (new Guid()).ToString().Substring(0, 10); try { int userid = CreateUser(email, passPrefix + item.Id + passSuffix, firstName, title, email, roleName); var content = (OpenContentInfo)item.Item; content.CreatedByUserId = userid; ds.Update(dsContext, item, item.Data); } catch (Exception) { } } } } } }
public void GetDetailData(RenderInfo info, OpenContentModuleInfo module) { info.ResetData(); var ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module); var dsItem = ds.Get(dsContext, info.DetailItemId); //if (LogContext.IsLogActive) //{ // var logKey = "Get detail data"; // LogContext.Log(_module.ModuleID, logKey, "debuginfo", dsItems.DebugInfo); //} if (dsItem != null) { //check permissions var portalSettings = PortalSettings.Current; bool isEditable = _module.ViewModule.CheckIfEditable(portalSettings); if (!isEditable) { var indexConfig = OpenContentUtils.GetIndexConfig(info.Template); string raison; if (!OpenContentUtils.HaveViewPermissions(dsItem, portalSettings.UserInfo, indexConfig, out raison)) { if (module.ViewModule.HasEditRightsOnModule()) { Exceptions.ProcessHttpException(new NotAuthorizedException(404, $"No detail view permissions for id={info.DetailItemId} (due to {raison}) \nGo into Edit Mode to view/change the item")); } else { Exceptions.ProcessHttpException(new NotAuthorizedException(404, "Access denied. You might want to contact your administrator for more information.")); } } } info.SetData(dsItem, dsItem.Data, module.Settings.Data); } }
public ModelFactoryMultiple(IEnumerable <IDataItem> dataList, string settingsJson, string physicalTemplateFolder, Manifest.Manifest manifest, TemplateManifest templateManifest, TemplateFiles templateFiles, OpenContentModuleInfo moduleinfo, PortalSettings portalSettings) : base(settingsJson, manifest, templateManifest, templateFiles, OpenContentModuleConfig.Create(moduleinfo.ModuleId, moduleinfo.TabId, portalSettings)) { this._dataList = dataList; }
public HttpResponseMessage Put(string entity, string id, [FromBody] JObject value) { // update try { var collection = entity; OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = collection; IDataItem dsItem = null; if (module.IsListMode()) { if (id != null) { var itemId = id; dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } //var indexConfig = OpenContentUtils.GetIndexConfig(settings.Template.Key.TemplateDir); if (dsItem == null) { ds.Add(dsContext, value.Properties().First().Value as JObject); } else { ds.Update(dsContext, dsItem, value.Properties().First().Value as JObject); } //if (json["form"]["ModuleTitle"] != null && json["form"]["ModuleTitle"].Type == JTokenType.String) //{ // string moduleTitle = json["form"]["ModuleTitle"].ToString(); // OpenContentUtils.UpdateModuleTitle(ActiveModule, moduleTitle); //} //else if (json["form"]["ModuleTitle"] != null && json["form"]["ModuleTitle"].Type == JTokenType.Object) //{ // if (json["form"]["ModuleTitle"][DnnUtils.GetCurrentCultureCode()] != null) // { // string moduleTitle = json["form"]["ModuleTitle"][DnnUtils.GetCurrentCultureCode()].ToString(); // OpenContentUtils.UpdateModuleTitle(ActiveModule, moduleTitle); // } //} return(Request.CreateResponse(HttpStatusCode.OK, "")); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
private readonly OpenContentModuleInfo _module; // active module (not datasource module) public RenderEngine(ModuleInfo viewmodule, IDictionary moduleSettings = null) { _module = new OpenContentModuleInfo(viewmodule, moduleSettings); _renderinfo = new RenderInfo(_module.Settings.Template, _module.Settings.IsOtherModule); }
public HttpResponseMessage Get(string entity, string id) { try { //if (entity == "items") var collection = AppConfig.DEFAULT_COLLECTION; OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); JObject reqOptions = null; //if (!string.IsNullOrEmpty(req.options)) //{ // reqOptions = JObject.Parse(req.options); //} //string editRole = manifest.GetEditRole(); if (module.IsListMode()) { var indexConfig = OpenContentUtils.GetIndexConfig(module.Settings.TemplateDir, collection); //bool isEditable = ActiveModule.CheckIfEditable(PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID, false, reqOptions); dsContext.Collection = collection; var dsItem = ds.Get(dsContext, id); var res = new JObject(); res["meta"] = new JObject(); var items = new JArray(); if (dsItem != null) { var mf = new ModelFactorySingle(dsItem, module, PortalSettings, collection); string raison = ""; if (!OpenContentUtils.HaveViewPermissions(dsItem, PortalSettings.UserInfo, indexConfig, out raison)) { Exceptions.ProcessHttpException(new HttpException(404, "No detail view permissions for id=" + id + " (" + raison + ")")); //throw new UnauthorizedAccessException("No detail view permissions for id " + info.DetailItemId); } mf.Options = reqOptions; var model = mf.GetModelAsJson(false); items.Add(model); model["id"] = dsItem.Id; res["meta"]["total"] = dsItem == null ? 0 : 1; JsonUtils.IdJson(model); if (LogContext.IsLogActive) { var logKey = "Query"; LogContext.Log(module.ViewModule.ModuleID, logKey, "model", model); res["meta"]["logs"] = JToken.FromObject(LogContext.Current.ModuleLogs(module.ViewModule.ModuleID)); } } res[entity] = items; 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)); } }
public HttpResponseMessage Json(int moduleId, int tabId) { try { var module = new OpenContentModuleInfo(moduleId, tabId); var manifest = module.Settings.Manifest; string templateFolder = module.Settings.TemplateDir.UrlFolder; var swagger = new SwaggerRoot(); swagger.Info.Title = "OpenContent Rest API"; swagger.Info.License = new License() { Name = "MIT", Url = "https://opencontent.codeplex.com/license" }; swagger.Info.Version = "1.0"; swagger.Host = PortalSettings.PortalAlias.HTTPAlias; swagger.BasePath = "/Desktopmodules/OpenContent/api/Rest/v1"; swagger.Schemes = new List <Protocol>(); swagger.Schemes.Add(Protocol.Http); swagger.Consumes.Add("application/json"); swagger.Produces.Add("application/json"); swagger.Tags.Add(new Tag() { Name = "Items", Description = manifest.Title }); if (manifest.AdditionalDataDefinition != null) { foreach (var entity in manifest.AdditionalDataDefinition) { swagger.Tags.Add(new Tag() { Name = entity.Key, Description = entity.Value.Title }); } } //swagger.Consumes.Add("text/html"); //swagger.Produces.Add("text/html"); var headers = new List <Parameter>(); /* * headers.Add(new Parameter() * { * Name = "TabId", * In = Location.Header, * Description = "Tab Id", * Required = true, * Type = SchemaType.String, * * }); * headers.Add(new Parameter() * { * Name = "ModuleId", * In = Location.Header, * Description = "Module Id", * Required = true, * Type = SchemaType.String, * * }); */ { // main item var schemaJson = JsonUtils.LoadJsonFromFile(templateFolder + "schema.json"); //var resItems = new List<SchemaObject>(); //resItems.Add(new SchemaObject() //{ // Ref = "#/definitions/items" //}); // Get() // Get(pageIndex, pageSize, filter, sort) var pi = new PathItem(); pi.Parameters = headers; var getParams = new List <Parameter>(); getParams.Add(new Parameter() { Name = "pageIndex", Description = "Page Index (start at 0)", In = Location.Query, Required = true, Type = SchemaType.Number, Default = 0 }); getParams.Add(new Parameter() { Name = "pageSize", Description = "Page Size", In = Location.Query, Required = true, Type = SchemaType.Number, Default = 10 }); getParams.Add(new Parameter() { Name = "filter", Description = "Filter definition (JSON.stringify)", In = Location.Query, Required = false, Type = SchemaType.String }); getParams.Add(new Parameter() { Name = "sort", Description = "Sort definition (JSON.stringify)", In = Location.Query, Required = false, Type = SchemaType.String }); pi.Get = new Operation() { Summary = "Get main items", Description = "No parameters for all items otherwise all parameters are required", Parameters = getParams }; pi.Get.Responses.Add("200", new Response() { Description = "succes", Schema = new SchemaObject() { Type = SchemaType.Array, Items = new SchemaObject() { Ref = "#/definitions/items" } } }); pi.Get.Tags.Add("Items"); // Post() var postProps = new Dictionary <string, SchemaObject>(); postProps.Add("item", new SchemaObject() { Ref = "#/definitions/items" }); var postParams = new List <Parameter>(); postParams.Add(new Parameter() { Name = "body", In = Location.Body, Required = true, Schema = new SchemaObject() { Type = SchemaType.Object, Properties = postProps //Ref = "#/definitions/items" } }); pi.Post = new Operation() { Summary = "Add new item", Parameters = postParams }; pi.Post.Responses.Add("200", new Response() { Description = "succes" }); pi.Post.Tags.Add("Items"); swagger.Paths.Add("/items", pi); // Get(id) pi = new PathItem(); pi.Parameters = headers; getParams = new List <Parameter>(); getParams.Add(new Parameter() { Name = "id", In = Location.Path, Required = true, Type = SchemaType.String }); pi.Get = new Operation() { Summary = "Get a item", Parameters = getParams }; pi.Get.Responses.Add("200", new Response() { Description = "succes", Schema = new SchemaObject() { Type = SchemaType.Array, Items = new SchemaObject() { Ref = "#/definitions/items" } } }); pi.Get.Tags.Add("Items"); // Put(id) - update var putProps = new Dictionary <string, SchemaObject>(); putProps.Add("item", new SchemaObject() { Ref = "#/definitions/items" }); var putParams = new List <Parameter>(); putParams.Add(new Parameter() { Name = "id", In = Location.Path, Required = true, Type = SchemaType.String }); putParams.Add(new Parameter() { Name = "body", In = Location.Body, Required = true, Schema = new SchemaObject() { Type = SchemaType.Object, Properties = putProps //Ref = "#/definitions/items" } }); pi.Put = new Operation() { Summary = "Update a item", Parameters = putParams }; pi.Put.Responses.Add("200", new Response() { Description = "succes" }); pi.Put.Tags.Add("Items"); // Delete(id) var deleteParams = new List <Parameter>(); deleteParams.Add(new Parameter() { Name = "id", In = Location.Path, Required = true, Type = SchemaType.String }); pi.Delete = new Operation() { Summary = "Delete a item", Parameters = deleteParams }; pi.Delete.Responses.Add("200", new Response() { Description = "succes", Schema = new SchemaObject() { Type = SchemaType.Array, Items = new SchemaObject() { Ref = "#/definitions/items" } } }); pi.Delete.Tags.Add("Items"); swagger.Paths.Add("/items/{id}", pi); // main item definition var props = new Dictionary <string, SchemaObject>(); props.Add("Title", new SchemaObject() { Type = SchemaType.String }); swagger.Definitions.Add("items", schemaJson); } if (manifest.AdditionalDataDefinition != null) { foreach (var entity in manifest.AdditionalDataDefinition.Keys) { var schemaJson = JsonUtils.LoadJsonFromFile(templateFolder + entity + "-schema.json"); if (schemaJson["items"] != null) { var entityName = entity.ToLower(); var resItems = new List <SchemaObject>(); resItems.Add(new SchemaObject() { Ref = "#/definitions/" + entityName }); var pi = new PathItem(); pi.Get = new Operation() { Summary = "Get all " + entity, //Parameters = headers OperationId = "get" + entity }; pi.Get.Responses.Add("200", new Response() { Description = "succes", Schema = new SchemaObject() { Type = SchemaType.Array, Items = new SchemaObject() { Ref = "#/definitions/" + entityName } } }); pi.Parameters = headers; pi.Get.Tags.Add(entity); swagger.Paths.Add("/" + entity, pi); swagger.Definitions.Add(entityName, schemaJson["items"]); } } } return(Request.CreateResponse(HttpStatusCode.OK, swagger, Configuration.Formatters.JsonFormatter)); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage List(RequestDTO req) { try { OpenContentModuleInfo module = new OpenContentModuleInfo(ActiveModule); 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 = ActiveModule.CheckIfEditable(PortalSettings); queryBuilder.Build(module.Settings.Query, !isEditable, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles); JplistQueryBuilder.MergeJpListQuery(indexConfig, queryBuilder.Select, req.StatusLst, 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); dsItems = ds.GetAll(dsContext, queryBuilder.Select); } var mf = new ModelFactoryMultiple(dsItems.Items, module, PortalSettings); 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) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Get(string entity, int pageIndex, int pageSize, string filter = null, string sort = null) { try { var collection = entity; //if (entity == "items") collection = AppConfig.DEFAULT_COLLECTION; // backward compatibility 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)); } }
public ModelFactorySingle(IDataItem data, string settingsJson, string physicalTemplateFolder, Manifest.Manifest manifest, TemplateManifest templateManifest, TemplateFiles templateFiles, OpenContentModuleInfo module, PortalSettings portalSettings) : base(settingsJson, physicalTemplateFolder, manifest, templateManifest, templateFiles, module, portalSettings) { this._dataJson = data.Data; this._data = data; }
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 ModelFactoryMultiple(IEnumerable <IDataItem> dataList, OpenContentModuleInfo module, PortalSettings portalSettings, string collection) : base(module, portalSettings, collection) { this._dataList = dataList; }
public static void LookupSelect2InOtherModule(JObject o, JObject options) { foreach (var child in o.Children <JProperty>().ToList()) { JObject opt = null; if (options?["fields"] != null) { opt = options["fields"][child.Name] as JObject; } if (opt == null) { continue; } bool lookup = opt["type"] != null && opt["type"].ToString() == "select2" && opt["dataService"]?["data"]?["moduleId"] != null && opt["dataService"]?["data"]?["tabId"] != null; string dataMember = ""; string valueField = "Id"; string moduleId = ""; string tabId = ""; if (lookup) { dataMember = opt["dataService"]["data"]["dataMember"]?.ToString() ?? ""; valueField = opt["dataService"]["data"]["valueField"]?.ToString() ?? "Id"; moduleId = opt["dataService"]["data"]["moduleId"]?.ToString() ?? "0"; tabId = opt["dataService"]["data"]["tabId"]?.ToString() ?? "0"; } var childProperty = child; if (childProperty.Value is JArray) { var array = childProperty.Value as JArray; JArray newArray = new JArray(); foreach (var value in array) { var obj = value as JObject; if (obj != null) { LookupSelect2InOtherModule(obj, opt["items"] as JObject); } else if (lookup) { var val = value as JValue; if (val != null) { try { var module = new OpenContentModuleInfo(int.Parse(moduleId), int.Parse(tabId)); var ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module); IDataItem dataItem = ds.Get(dsContext, val.ToString()); newArray.Add(GenerateObject(dataItem, val.ToString())); } catch (System.Exception) { Debugger.Break(); } } } } if (lookup) { childProperty.Value = newArray; } } else if (childProperty.Value is JObject) { var obj = childProperty.Value as JObject; LookupSelect2InOtherModule(obj, opt); } else if (childProperty.Value is JValue) { if (lookup) { string val = childProperty.Value.ToString(); try { var module = new OpenContentModuleInfo(int.Parse(moduleId), int.Parse(tabId)); var ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module); IDataItem dataItem = ds.Get(dsContext, val); o[childProperty.Name] = GenerateObject(dataItem, val); } catch (System.Exception ex) { Debugger.Break(); } } } } }
public ModelFactoryMultiple(IEnumerable <IDataItem> dataList, string settingsJson, string physicalTemplateFolder, Manifest.Manifest manifest, TemplateManifest templateManifest, TemplateFiles templateFiles, OpenContentModuleInfo module, int portalId, string cultureCode) : base(settingsJson, physicalTemplateFolder, manifest, templateManifest, templateFiles, module, portalId, cultureCode) { this._dataList = dataList; }
public ModelFactorySingle(IDataItem data, OpenContentModuleInfo module, PortalSettings portalSettings, string collection) : base(module, portalSettings, collection) { this._dataJson = data.Data; this._data = data; }