public HttpResponseMessage ReOrder(List <string> ids)
 {
     try
     {
         var         module    = new OpenContentModuleInfo(ActiveModule);
         IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
         var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);
         IDataItem   dsItem    = null;
         if (module.IsListMode())
         {
             if (ids != null)
             {
                 int i = 1;
                 foreach (var id in ids)
                 {
                     dsItem = ds.Get(dsContext, id);
                     var json = dsItem.Data;
                     json["SortIndex"] = i;
                     ds.Update(dsContext, dsItem, json);
                     i++;
                 }
             }
         }
         return(Request.CreateResponse(HttpStatusCode.OK, new
         {
             isValid = true
         }));
     }
     catch (Exception exc)
     {
         Log.Logger.Error(exc);
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
     }
 }
        public HttpResponseMessage Delete(JObject json)
        {
            try
            {
                var    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 content = null;
                if (module.IsListMode())
                {
                    content = ds.Get(dsContext, json["id"].ToString());
                    if (content != null)
                    {
                        createdByUserid = content.CreatedByUserId;
                    }
                }
                else
                {
                    dsContext.Single = true;
                    content          = ds.Get(dsContext, null);
                    if (content != null)
                    {
                        createdByUserid = content.CreatedByUserId;
                    }
                }

                //todo: can't we do some of these checks at the beginning of this method to fail faster?
                if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid))
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }

                if (content != null)
                {
                    ds.Delete(dsContext, content);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, ""));
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Add(UpdateRequest req)
        {
            try
            {
                var    module   = new OpenContentModuleInfo(req.ModuleId, req.TabId);
                string editRole = module.Settings.Template.Manifest.GetEditRole();

                OpenContentController ctrl = new OpenContentController();

                if (module.IsListMode())
                {
                    if (!OpenContentUtils.HasEditPermissions(PortalSettings, module.ViewModule, editRole, -1))
                    {
                        Log.Logger.WarnFormat("Failed the HasEditPermissions() check for ");
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Failed the HasEditPermissions() check"));
                    }
                    var             index       = module.Settings.Template.Manifest.Index;
                    var             indexConfig = OpenContentUtils.GetIndexConfig(module.Settings.Template.Key.TemplateDir, "Items");
                    OpenContentInfo content     = new OpenContentInfo()
                    {
                        ModuleId             = module.DataModule.ModuleID,
                        Collection           = req.Collection,
                        Title                = ActiveModule.ModuleTitle,
                        Json                 = req.json.ToString(),
                        CreatedByUserId      = UserInfo.UserID,
                        CreatedOnDate        = DateTime.Now,
                        LastModifiedByUserId = UserInfo.UserID,
                        LastModifiedOnDate   = DateTime.Now
                    };
                    ctrl.AddContent(content, index, indexConfig);
                    return(Request.CreateResponse(HttpStatusCode.OK, ""));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "It's not a list mode module"));
                }
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage LookupCollection(LookupCollectionRequestDTO req)
        {
            var module = new OpenContentModuleInfo(ActiveModule);
            var res    = new List <LookupResultDTO>();

            try
            {
                IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);
                dsContext.Collection = req.collection;

                if (module.IsListMode())
                {
                    var items = ds.GetAll(dsContext, null).Items;
                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            var json = item.Data as JObject;
                            if (json?[req.textField] != null)
                            {
                                res.Add(new LookupResultDTO()
                                {
                                    value = item.Id,
                                    text  = json[req.textField].ToString()
                                });
                            }
                        }
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, res));
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Add(UpdateRequest req)
        {
            try
            {
                var    module   = new OpenContentModuleInfo(req.ModuleId, req.TabId);
                string editRole = module.Settings.Template.Manifest.GetEditRole();

                var dataSource = new OpenContentDataSource();

                if (module.IsListMode())
                {
                    if (!OpenContentUtils.HasEditPermissions(PortalSettings, module.ViewModule, editRole, -1))
                    {
                        Log.Logger.Warn($"Failed the HasEditPermissions() check");
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Failed the HasEditPermissions() check"));
                    }
                    var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);
                    dsContext.Collection = req.Collection;

                    JToken data = req.json;
                    data["Title"] = ActiveModule.ModuleTitle;
                    dataSource.Add(dsContext, data);

                    return(Request.CreateResponse(HttpStatusCode.OK, ""));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "It's not a list mode module"));
                }
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Action(SubmitDTO req)
        {
            try
            {
                var    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 (req.id != null)
                    {
                        var itemId = req.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;
                    }
                }

                //todo: can't we do some of these checks at the beginning of this method to fail faster?
                if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid))
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
                try
                {
                    var res = ds.Action(dsContext, req.action, dsItem, req.form);
                    return(Request.CreateResponse(HttpStatusCode.OK, new
                    {
                        isValid = true,
                        result = res
                    }));
                }
                catch (DataNotValidException ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new
                    {
                        isValid = false,
                        validMessage = ex.Message
                    }));
                }
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Update(JObject json)
        {
            try
            {
                var    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 (json["id"] != null)
                    {
                        var itemId = json["id"].ToString();
                        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;
                    }
                }

                //todo: can't we do some of these checks at the beginning of this method to fail faster?
                if (!OpenContentUtils.HasEditPermissions(PortalSettings, ActiveModule, editRole, createdByUserid))
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
                try
                {
                    if (dsItem == null)
                    {
                        ds.Add(dsContext, json["form"] as JObject);
                    }
                    else
                    {
                        ds.Update(dsContext, dsItem, json["form"] as JObject);
                    }
                }
                catch (DataNotValidException ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new
                    {
                        isValid = false,
                        validMessage = ex.Message
                    }));
                }

                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"][DnnLanguageUtils.GetCurrentCultureCode()] != null)
                    {
                        string moduleTitle = json["form"]["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString();
                        OpenContentUtils.UpdateModuleTitle(ActiveModule, moduleTitle);
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, new
                {
                    isValid = true
                }));
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Edit(string id)
        {
            try
            {
                var         moduleInfo = new OpenContentModuleInfo(ActiveModule);
                IDataSource ds         = DataSourceManager.GetDataSource(moduleInfo.Settings.Manifest.DataSource);
                var         dsContext  = OpenContentUtils.CreateDataContext(moduleInfo);
                IDataItem   dsItem     = null;
                if (moduleInfo.IsListMode())
                {
                    if (!string.IsNullOrEmpty(id)) // not a new item
                    {
                        dsItem = ds.Get(dsContext, id);
                    }
                }
                else
                {
                    dsContext.Single = true;
                    dsItem           = ds.Get(dsContext, null);
                }
                int createdByUserid = -1;
                var json            = ds.GetAlpaca(dsContext, true, true, true);
                if (ds is IDataActions)
                {
                    var actions = ((IDataActions)ds).GetActions(dsContext, dsItem);
                    if (json["options"] == null)
                    {
                        json["options"] = new JObject();
                    }
                    if (json["options"]["form"] == null)
                    {
                        json["options"]["form"] = new JObject();
                    }
                    if (json["options"]["form"]["buttons"] == null)
                    {
                        json["options"]["form"]["buttons"] = new JObject();
                    }
                    var buttons    = json["options"]["form"]["buttons"] as JObject;
                    var newButtons = new JObject();
                    foreach (var act in actions)
                    {
                        var but = buttons[act.Name];
                        if (but == null)
                        {
                            but = new JObject();
                        }
                        but["after"]         = act.AfterExecute;
                        newButtons[act.Name] = but;
                    }
                    json["options"]["form"]["buttons"] = newButtons;
                }
                if (dsItem != null)
                {
                    json["data"] = dsItem.Data;
                    if (json["schema"]["properties"]["ModuleTitle"] is JObject)
                    {
                        if (json["data"]["ModuleTitle"] != null && json["data"]["ModuleTitle"].Type == JTokenType.String)
                        {
                            json["data"]["ModuleTitle"] = ActiveModule.ModuleTitle;
                        }
                        else if (json["data"]["ModuleTitle"] != null && json["data"]["ModuleTitle"].Type == JTokenType.Object)
                        {
                            json["data"]["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()] = ActiveModule.ModuleTitle;
                        }
                    }
                    var versions = ds.GetVersions(dsContext, dsItem);
                    if (versions != null)
                    {
                        json["versions"] = versions;
                    }
                    createdByUserid = dsItem.CreatedByUserId;
                }

                var context       = new JObject();
                var currentLocale = DnnLanguageUtils.GetCurrentLocale(PortalSettings.PortalId);
                context["culture"]                = currentLocale.Code; //todo why not use  DnnLanguageUtils.GetCurrentCultureCode() ???
                context["defaultCulture"]         = LocaleController.Instance.GetDefaultLocale(PortalSettings.PortalId).Code;
                context["numberDecimalSeparator"] = currentLocale.Culture.NumberFormat.NumberDecimalSeparator;
                context["rootUrl"]                = System.Web.VirtualPathUtility.ToAbsolute(string.Concat(System.Web.HttpRuntime.AppDomainAppVirtualPath, "/"));
                context["alpacaCulture"]          = AlpacaEngine.AlpacaCulture(currentLocale.Code);
                context["bootstrap"]              = OpenContentControllerFactory.Instance.OpenContentGlobalSettingsController(PortalSettings.PortalId).GetEditLayout() != AlpacaLayoutEnum.DNN;
                context["horizontal"]             = OpenContentControllerFactory.Instance.OpenContentGlobalSettingsController(PortalSettings.PortalId).GetEditLayout() == AlpacaLayoutEnum.BootstrapHorizontal;
                json["context"] = context;

                //todo: can't we do some of these checks at the beginning of this method to fail faster?
                if (!OpenContentUtils.HasEditPermissions(PortalSettings, moduleInfo.ViewModule, moduleInfo.Settings.Manifest.GetEditRole(), createdByUserid))
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, json));
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        public HttpResponseMessage Lookup(LookupRequestDTO req)
        {
            var module = new OpenContentModuleInfo(req.moduleid, req.tabid);

            if (module == null)
            {
                throw new Exception($"Can not find ModuleInfo (tabid:{req.tabid}, moduleid:{req.moduleid})");
            }

            List <LookupResultDTO> res = new List <LookupResultDTO>();

            try
            {
                IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);

                if (module.IsListMode())
                {
                    var items = ds.GetAll(dsContext, null).Items;
                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            var json = item.Data;

                            if (!string.IsNullOrEmpty(req.dataMember) && json[req.dataMember] != null)
                            {
                                json = json[req.dataMember];
                            }

                            var array = json as JArray;
                            if (array != null)
                            {
                                res.AddRange(array.Select(childItem =>
                                                          new LookupResultDTO
                                {
                                    value = string.IsNullOrEmpty(req.valueField) || childItem[req.valueField] == null ? "" : childItem[req.valueField].ToString(),
                                    text  = string.IsNullOrEmpty(req.textField) || childItem[req.textField] == null ? "" : childItem[req.textField].ToString()
                                }
                                                          )
                                             );
                            }
                            else
                            {
                                res.Add(new LookupResultDTO
                                {
                                    value = string.IsNullOrEmpty(req.valueField) || json[req.valueField] == null ? item.Id : json[req.valueField].ToString(),
                                    text  = string.IsNullOrEmpty(req.textField) || json[req.textField] == null ? item.Title : json[req.textField].ToString()
                                });
                            }
                        }
                    }
                }
                else
                {
                    dsContext.Single = true;
                    var struc = ds.Get(dsContext, null);
                    if (struc != null)
                    {
                        JToken json = struc.Data;
                        if (!string.IsNullOrEmpty(req.dataMember))
                        {
                            json = json[req.dataMember];
                            if (json is JArray)
                            {
                                foreach (JToken item in (JArray)json)
                                {
                                    res.Add(new LookupResultDTO()
                                    {
                                        value = item[req.valueField] == null ? "" : item[req.valueField].ToString(),
                                        text  = item[req.textField] == null ? "" : item[req.textField].ToString()
                                    });
                                }
                            }
                        }
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, res));
            }
            catch (Exception exc)
            {
                Log.Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }