Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Recursos", ApplicationVirtualPath + "admin/resource/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Recursos", ApplicationVirtualPath + "admin/resource/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 resourceId = 0;

            try
            {
                resourceId = Int64.Parse((String)RouteData.Values["id"]);

                if (resourceId < 0)
                {
                    resourceId = 0;
                }
            }
            catch { }

            String            error       = "";
            ResourceGetResult retResource = null;
            String            filter      = "";
            HashData          hashData    = new HashData(this);


            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((resourceId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "resource.get",
                        parameters = new
                        {
                            resourceid = resourceId
                        },
                        id = 1
                    };

                    String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    retResource = JSON.Deserialize <ResourceGetResult>(jData);
                    if (retResource == null)
                    {
                        error = MessageResource.GetMessage("resource_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retResource.error != null)
                    {
                        error       = retResource.error.data;
                        retResource = null;
                    }
                    else if (retResource.result == null || retResource.result.info == null)
                    {
                        error       = MessageResource.GetMessage("resource_not_found");
                        retResource = null;
                    }
                    else
                    {
                        menu3.Name = retResource.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    retResource = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    try
                    {
                        var tmpReq = new
                        {
                            jsonrpc    = "1.0",
                            method     = "context.list",
                            parameters = new { },
                            id         = 1
                        };

                        error = "";
                        String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                        String jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);


                        if (String.IsNullOrWhiteSpace(jData))
                        {
                            throw new Exception("");
                        }

                        ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                        if (contextList == null)
                        {
                            error = MessageResource.GetMessage("context_not_found");
                            //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                        }
                        else if (contextList.error != null)
                        {
                            error = contextList.error.data;
                        }
                        else if (contextList.result == null)
                        {
                            error = MessageResource.GetMessage("context_not_found");
                        }
                        else
                        {
                            var tmpReq2 = new
                            {
                                jsonrpc    = "1.0",
                                method     = "proxy.list",
                                parameters = new { },
                                id         = 1
                            };

                            error = "";
                            rData = SafeTrend.Json.JSON.Serialize2(tmpReq2);
                            jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            ProxyListResult proxyList = JSON.Deserialize <ProxyListResult>(jData);
                            if (proxyList == null)
                            {
                                error = MessageResource.GetMessage("proxy_not_found");
                                //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                            }
                            else if (proxyList.error != null)
                            {
                                error = proxyList.error.data;
                            }
                            else if (proxyList.result == null)
                            {
                                error = MessageResource.GetMessage("proxy_not_found");
                            }
                            else
                            {
                                html  = "<h3>Adição de recurso</h3>";
                                html += "<form id=\"form_add_resource\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/resource/action/add_resource/\"><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"><label>Nome</label><input id=\"resource_name\" name=\"resource_name\" placeholder=\"Digite o nome do recurso\" type=\"text\"\"></div>";
                                html += "<div class=\"form-group\"><label>Contexto</label><select id=\"resource_context\" name=\"resource_context\" ><option value=\"\"></option>";
                                foreach (ContextData c in contextList.result)
                                {
                                    html += "<option value=\"" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                                }
                                html += "</select></div>";
                                html += "<div class=\"form-group\"><label>Proxy</label><select id=\"resource_proxy\" name=\"resource_proxy\" ><option value=\"\"></option>";
                                foreach (ProxyData p in proxyList.result)
                                {
                                    html += "<option value=\"" + p.proxy_id + "\" " + (hashData.GetValue("proxy") == p.proxy_id.ToString() ? "selected" : "") + ">" + p.name + "</option>";
                                }
                                html += "</select></div>";
                                html += "<div class=\"clear-block\"></div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button>    <a href=\"" + ApplicationVirtualPath + "admin/resource/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        error = MessageResource.GetMessage("api_error");
                    }

                    if (error != "")
                    {
                        contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                    }
                }
                else
                {
                    if (retResource == null)
                    {
                        Int32   page     = 1;
                        Int32   pageSize = 20;
                        Boolean hasNext  = true;

                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }


                        String roleTemplate = "<div id=\"role-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        roleTemplate += "<table>";
                        roleTemplate += "   <tbody>";
                        roleTemplate += "       <tr>";
                        roleTemplate += "           <td class=\"col1\">";
                        roleTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        roleTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/resource_plugin/#resource/{0}\">";
                        roleTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver vínculos</span></div>";
                        roleTemplate += "               </a>";
                        roleTemplate += "           </td>";
                        roleTemplate += "           <td class=\"col2\">";
                        roleTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"resource_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#resource_name_{0}',null,resourceNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        roleTemplate += "               <div class=\"description\">";
                        roleTemplate += "                   <div class=\"first\">{4}</div>";
                        roleTemplate += "               </div>";
                        roleTemplate += "               <div class=\"links\">";
                        roleTemplate += "                   <div class=\"\"><a href=\"" + ApplicationVirtualPath + "admin/resource/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a><a href=\"" + ApplicationVirtualPath + "admin/roles/{0}/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários do perfil '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a></div>";
                        roleTemplate += "                   <div class=\"last\">{5}</div>";
                        roleTemplate += "               </div>";
                        roleTemplate += "           </td>";
                        roleTemplate += "       </tr>";
                        roleTemplate += "   </tbody>";
                        roleTemplate += "</table></div>";

                        js += "resourceNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            String rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "resource.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page,
                                        filter    = new { contextid = hashData.GetValue("context"), proxyid = hashData.GetValue("proxy") }
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }
                            else
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "resource.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page,
                                        filter    = new { contextid = hashData.GetValue("context"), proxyid = hashData.GetValue("proxy") }
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }

                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            ResourceListResult ret2 = JSON.Deserialize <ResourceListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("resource_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("resource_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (ResourceData resource in ret2.result)
                                {
                                    String text = "Contexto: " + resource.context_name + ", Proxy: " + resource.proxy_name;

                                    html += String.Format(roleTemplate, resource.resource_id, resource.name, resource.resource_plugin_qty, (resource.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(resource.create_date), true) : ""), text, (resource.resource_plugin_qty > 0 ? "" : "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/resource/" + resource.resource_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o recurso '" + resource.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>"));
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading role-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.role-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.role-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado a role
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":
                                String infoTemplate = "<div class=\"form-group\">";
                                infoTemplate += "<label>{0}</label>";
                                infoTemplate += "<span class=\"no-edit\">{1}</span></div>";
                                String jsAdd = "";

                                if (hashData.GetValue("edit") == "1")
                                {
                                    var tmpReq = new
                                    {
                                        jsonrpc    = "1.0",
                                        method     = "context.list",
                                        parameters = new { },
                                        id         = 1
                                    };

                                    error = "";
                                    String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                                    String jData = "";
                                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                                    if (String.IsNullOrWhiteSpace(jData))
                                    {
                                        throw new Exception("");
                                    }

                                    ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                                    if (contextList == null)
                                    {
                                        error = MessageResource.GetMessage("context_not_found");
                                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                                    }
                                    else if (contextList.error != null)
                                    {
                                        error = contextList.error.data;
                                    }
                                    else if (contextList.result == null)
                                    {
                                        error = MessageResource.GetMessage("context_not_found");
                                    }
                                    else
                                    {
                                        var tmpReq2 = new
                                        {
                                            jsonrpc    = "1.0",
                                            method     = "proxy.list",
                                            parameters = new { },
                                            id         = 1
                                        };

                                        error = "";
                                        rData = SafeTrend.Json.JSON.Serialize2(tmpReq2);
                                        jData = "";
                                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                            jData = WebPageAPI.ExecuteLocal(database, this, rData);


                                        if (String.IsNullOrWhiteSpace(jData))
                                        {
                                            throw new Exception("");
                                        }

                                        ProxyListResult proxyList = JSON.Deserialize <ProxyListResult>(jData);
                                        if (contextList == null)
                                        {
                                            error = MessageResource.GetMessage("proxy_not_found");
                                            //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                                        }
                                        else if (contextList.error != null)
                                        {
                                            error = contextList.error.data;
                                        }
                                        else if (contextList.result == null)
                                        {
                                            error = MessageResource.GetMessage("proxy_not_found");
                                        }
                                        else
                                        {
                                            html += "<form  id=\"form_resource_change\"  method=\"POST\" action=\"" + ApplicationVirtualPath + "admin/resource/" + retResource.result.info.resource_id + "/action/change/\">";
                                            html += "<h3>Edição de recurso</h3>";
                                            html += "<div class=\"no-tabs pb10\">";

                                            String contexto = "";
                                            contexto += "<select id=\"resource_context\" name=\"resource_context\" ><option value=\"\"></option>";
                                            foreach (ContextData c in contextList.result)
                                            {
                                                contexto += "<option value=\"" + c.context_id + "\" " + (retResource.result.info.context_id == c.context_id ? "selected" : "") + ">" + c.name + "</option>";
                                            }
                                            contexto += "</select>";

                                            String proxy = "";
                                            proxy += "<select id=\"resource_proxy\" name=\"resource_proxy\" ><option value=\"\"></option>";
                                            foreach (ProxyData c in proxyList.result)
                                            {
                                                proxy += "<option value=\"" + c.proxy_id + "\" " + (retResource.result.info.proxy_id == c.proxy_id ? "selected" : "") + ">" + c.name + "</option>";
                                            }
                                            proxy += "</select>";

                                            html += String.Format(infoTemplate, "Nome", "<input id=\"name\" name=\"name\" placeholder=\"Digite o nome do recurso\" type=\"text\"\" value=\"" + retResource.result.info.name + "\">");
                                            html += String.Format(infoTemplate, "Contexto", contexto);
                                            html += String.Format(infoTemplate, "Proxy", proxy);
                                            html += String.Format(infoTemplate, "Desabilitado", "<input id=\"disabled\" name=\"disabled\" type=\"checkbox\" " + (!retResource.result.info.enabled ? "checked" : "") + ">");
                                            html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(retResource.result.info.create_date), false));

                                            html += "<div class=\"clear-block\"></div></div>";
                                        }
                                    }
                                }
                                else
                                {
                                    html += "<h3>Informações gerais<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div></h3>";
                                    html += "<div class=\"no-tabs pb10\">";

                                    html += String.Format(infoTemplate, "Nome", retResource.result.info.name);
                                    html += String.Format(infoTemplate, "Contexto", retResource.result.info.context_name);
                                    html += String.Format(infoTemplate, "Proxy", retResource.result.info.proxy_name);
                                    html += String.Format(infoTemplate, "Desabilitado", (!retResource.result.info.enabled ? MessageResource.GetMessage("yes") : MessageResource.GetMessage("no")));
                                    html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(retResource.result.info.create_date), false));

                                    html += "<div class=\"clear-block\"></div></div>";
                                }

                                if (hashData.GetValue("edit") == "1")
                                {
                                    html += "<button type=\"submit\" id=\"resource-save\" class=\"button secondary floatleft\">Salvar</button>    <a class=\"button link floatleft\" onclick=\"iamadmin.changeHash( 'edit/0' );\">Cancelar</a></form>";
                                }

                                contentRet    = new WebJsonResponse("#content-wrapper", html);
                                contentRet.js = jsAdd;
                                break;

                            case "identity":
                                break;
                            }
                        }
                    }
                }

                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/resource/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo recurso</button></div>";

                    switch (filter)
                    {
                    case "add_user":
                        break;

                    default:
                        /*if (retRole != null)
                         *  html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/roles/" + retRole.result.info.role_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Adicionar usuários</button></div>";*/
                        break;
                    }
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":

                switch (filter)
                {
                case "":
                    if (retResource == null)
                    {
                        js = "";
                        try
                        {
                            String rData = SafeTrend.Json.JSON.Serialize2(new
                            {
                                jsonrpc    = "1.0",
                                method     = "context.list",
                                parameters = new
                                {
                                    page_size = Int32.MaxValue
                                },
                                id = 1
                            });
                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                            if ((contextList != null) && (contextList.error == null) && (contextList.result != null))
                            {
                                html += "<select id=\"filter_context\" name=\"filter_context\" ><option value=\"\">Todos os contextos</option>";
                                foreach (ContextData c in contextList.result)
                                {
                                    html += "<option value=\"context/" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                                }
                                html += "</select>";
                                js   += "$('#filter_context').change(function() { iamadmin.changeHash( $( this ).val() ); });";
                            }
                        }
                        catch (Exception ex) { }

                        try
                        {
                            String rData = SafeTrend.Json.JSON.Serialize2(new
                            {
                                jsonrpc    = "1.0",
                                method     = "proxy.list",
                                parameters = new
                                {
                                    page_size = Int32.MaxValue
                                },
                                id = 1
                            });
                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            ProxyListResult proxyList = JSON.Deserialize <ProxyListResult>(jData);
                            if ((proxyList != null) && (proxyList.error == null) && (proxyList.result != null))
                            {
                                html += "<select id=\"filter_proxy\" name=\"filter_proxy\" ><option value=\"\">Todos os proxies</option>";
                                foreach (ProxyData p in proxyList.result)
                                {
                                    html += "<option value=\"proxy/" + p.proxy_id + "\" " + (hashData.GetValue("proxy") == p.proxy_id.ToString() ? "selected" : "") + ">" + p.name + "</option>";
                                }
                                html += "</select>";

                                js += "$('#filter_proxy').change(function() { iamadmin.changeHash( $( this ).val() ); });";
                            }
                        }
                        catch (Exception ex) { }

                        contentRet    = new WebJsonResponse("#btnbox", html);
                        contentRet.js = js;
                    }
                    break;
                }
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Perfis", ApplicationVirtualPath + "admin/roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Perfis de usuário", ApplicationVirtualPath + "admin/roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 roleId = 0;

            try
            {
                roleId = Int64.Parse((String)RouteData.Values["id"]);

                if (roleId < 0)
                {
                    roleId = 0;
                }
            }
            catch { }

            String        error    = "";
            RoleGetResult retRole  = null;
            String        filter   = "";
            HashData      hashData = new HashData(this);


            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((roleId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.get",
                        parameters = new
                        {
                            roleid = roleId
                        },
                        id = 1
                    };

                    String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    retRole = JSON.Deserialize <RoleGetResult>(jData);
                    if (retRole == null)
                    {
                        error = MessageResource.GetMessage("role_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retRole.error != null)
                    {
                        error   = retRole.error.data;
                        retRole = null;
                    }
                    else if (retRole.result == null || retRole.result.info == null)
                    {
                        error   = MessageResource.GetMessage("role_not_found");
                        retRole = null;
                    }
                    else
                    {
                        menu3.Name = retRole.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    retRole = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    try
                    {
                        var tmpReq = new
                        {
                            jsonrpc    = "1.0",
                            method     = "context.list",
                            parameters = new { },
                            id         = 1
                        };

                        error = "";
                        String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                        String jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);


                        if (String.IsNullOrWhiteSpace(jData))
                        {
                            throw new Exception("");
                        }

                        ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                        if (contextList == null)
                        {
                            error = MessageResource.GetMessage("context_not_found");
                            //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                        }
                        else if (contextList.error != null)
                        {
                            error   = contextList.error.data;
                            retRole = null;
                        }
                        else if (contextList.result == null)
                        {
                            error   = MessageResource.GetMessage("context_not_found");
                            retRole = null;
                        }
                        else
                        {
                            html  = "<h3>Adição de perfil</h3>";
                            html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/roles/action/add_role/\"><div class=\"no-tabs pb10\">";
                            html += "<div class=\"form-group\"><label>Nome</label><input id=\"add_role_name\" name=\"add_role_name\" placeholder=\"Digite o nome do perfil\" type=\"text\"\"></div>";
                            html += "<div class=\"form-group\"><label>Contexto</label><select id=\"add_role_context\" name=\"add_role_context\" ><option value=\"\"></option>";
                            foreach (ContextData c in contextList.result)
                            {
                                html += "<option value=\"" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                            }
                            html += "</select></div>";
                            html += "<div class=\"clear-block\"></div></div>";
                            html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button>    <a href=\"" + ApplicationVirtualPath + "admin/roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                    }
                    catch (Exception ex)
                    {
                        error = MessageResource.GetMessage("api_error");
                    }

                    if (error != "")
                    {
                        contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                    }
                }
                else
                {
                    if (retRole == null)
                    {
                        Int32   page     = 1;
                        Int32   pageSize = 20;
                        Boolean hasNext  = true;

                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }


                        String roleTemplate = "<div id=\"role-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        roleTemplate += "<table>";
                        roleTemplate += "   <tbody>";
                        roleTemplate += "       <tr>";
                        roleTemplate += "           <td class=\"col1\">";
                        roleTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        roleTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/roles/{0}/users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\">";
                        roleTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver usuários</span></div>";
                        roleTemplate += "               </a>";
                        roleTemplate += "           </td>";
                        roleTemplate += "           <td class=\"col2\">";
                        roleTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"role_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#role_name_{0}',null,roleNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        roleTemplate += "               <div class=\"links no-bg\">";
                        roleTemplate += "                   <div class=\"first\"><a href=\"" + ApplicationVirtualPath + "admin/roles/{0}/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a><br clear=\"all\"></div>";
                        roleTemplate += "                   <div class=\"\"><a href=\"" + ApplicationVirtualPath + "admin/roles/{0}/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários do perfil '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a></div>";
                        roleTemplate += "                   <div class=\"last\"><a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/roles/{0}/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o perfil '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a><br clear=\"all\"></div>";
                        roleTemplate += "               </div><br clear=\"all\">";
                        roleTemplate += "           </td>";
                        roleTemplate += "       </tr>";
                        roleTemplate += "   </tbody>";
                        roleTemplate += "</table></div>";

                        js += "roleNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            String rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "role.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page,
                                        filter    = new { contextid = hashData.GetValue("context") }
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }
                            else
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "role.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page,
                                        filter    = new { contextid = hashData.GetValue("context") }
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }

                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            RoleListResult ret2 = JSON.Deserialize <RoleListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("role_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("role_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (RoleData role in ret2.result)
                                {
                                    html += String.Format(roleTemplate, role.role_id, role.name, role.entity_qty, (role.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(role.create_date), true) : ""));
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading role-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.role-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.role-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado a role
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":
                            case "users":

                                Int32   page     = 1;
                                Int32   pageSize = 20;
                                Boolean hasNext  = true;

                                Int32.TryParse(Request.Form["page"], out page);

                                if (page < 1)
                                {
                                    page = 1;
                                }

                                if (page == 1)
                                {
                                    html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                                    html += "    <tr>";
                                    html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                                    html += "        <th class=\"pointer header headerSortDown\" data-column=\"name\">Nome <div class=\"icomoon\"></div></th>";
                                    html += "        <th class=\"pointer tHide mHide header\" data-column=\"login\">Login <div class=\"icomoon\"></div></th>";
                                    html += "        <th class=\"pointer w200 tHide mHide header\" data-column=\"last_login\">Ações <div class=\"icomoon\"></div></th>";
                                    html += "    </tr>";
                                    html += "</thead>";

                                    html += "<tbody>";
                                }

                                String trTemplate = "    <tr class=\"user\" data-login=\"{1}\" data-userid=\"{0}\">";
                                trTemplate += "            <td class=\"select mHide\"><div class=\"checkbox\"></div></td>";
                                trTemplate += "            <td class=\"ident10\">{2}</td>";
                                trTemplate += "            <td class=\"tHide mHide\">{1}</td>";
                                trTemplate += "            <td class=\"tHide mHide\"><button class=\"a-btn\" onclick=\"window.location = '" + ApplicationVirtualPath + "admin/users/{0}/';\">Abrir</button> <button href=\"" + ApplicationVirtualPath + "admin/roles/" + retRole.result.info.role_id + "/action/delete_user/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"a-btn confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o vínculo do usuário '{2}' com o perfil '" + retRole.result.info.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\">Excluir</button></td>";
                                trTemplate += "    </tr>";

                                try
                                {
                                    String rData = "";

                                    var tmpReq = new
                                    {
                                        jsonrpc    = "1.0",
                                        method     = "role.users",
                                        parameters = new
                                        {
                                            page_size = pageSize,
                                            page      = page,
                                            roleid    = roleId
                                        },
                                        id = 1
                                    };

                                    rData = SafeTrend.Json.JSON.Serialize2(tmpReq);

                                    String jData = "";
                                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                                    if (String.IsNullOrWhiteSpace(jData))
                                    {
                                        throw new Exception("");
                                    }

                                    SearchResult ret2 = JSON.Deserialize <SearchResult>(jData);
                                    if (ret2 == null)
                                    {
                                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                                        hasNext = false;
                                    }
                                    else if (ret2.error != null)
                                    {
                                        eHtml += String.Format(errorTemplate, ret2.error.data);
                                        //ret = new WebJsonResponse("", ret2.error.data, 3000, true);
                                        hasNext = false;
                                    }
                                    else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                                    {
                                        eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                                        hasNext = false;
                                    }
                                    else
                                    {
                                        foreach (UserData user in ret2.result)
                                        {
                                            html += String.Format(trTemplate, user.userid, user.login, user.full_name);
                                        }

                                        if (ret2.result.Count < pageSize)
                                        {
                                            hasNext = false;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                                }

                                if (page == 1)
                                {
                                    html += "</tbody></table>";

                                    html += "<span class=\"empty-results content-loading user-list-loader hide\"></span>";

                                    contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                }
                                else
                                {
                                    contentRet = new WebJsonResponse("#content-wrapper tbody", (eHtml != "" ? eHtml : html), true);
                                }

                                contentRet.js = "$( document ).unbind('end_of_scroll.loader_usr');";

                                if (hasNext)
                                {
                                    contentRet.js += "$( document ).bind( 'end_of_scroll.loader_usr', function() { $( document ).unbind('end_of_scroll.loader_usr'); $('.user-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'' }, function(){ $('.user-list-loader').addClass('hide'); } ); });";
                                }

                                break;

                            case "add_user":
                                html  = "<h3>Adição de usuário</h3>";
                                html += "<form id=\"form_add_user\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/roles/" + roleId + "/action/add_user/\"><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"  id=\"add_user\"><label>Usuário</label><input id=\"add_user_text\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"></div>";
                                html += "<div class=\"clear-block\"></div></div>";
                                html += "<h3>Usuários selecionados</h3>";
                                html += "<div id=\"box-container\" class=\"box-container\"><div class=\"no-tabs pb10 none\">";
                                html += "Nenhum usuário selecionado";
                                html += "</div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Cadastrar</button>    <a href=\"" + ApplicationVirtualPath + "admin/roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                contentRet.js = "iamadmin.autoCompleteText('#add_user_text', '" + ApplicationVirtualPath + "admin/users/content/search_user/', {context_id: '" + retRole.result.info.context_id + "'} , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )";

                                break;
                            }
                        }
                    }
                }

                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/roles/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo perfil</button></div>";

                    switch (filter)
                    {
                    case "add_user":
                        break;

                    default:
                        if (retRole != null)
                        {
                            html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/roles/" + retRole.result.info.role_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Adicionar usuários</button></div>";
                        }
                        break;
                    }
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":

                switch (filter)
                {
                case "":

                    try
                    {
                        var tmpReq = new
                        {
                            jsonrpc    = "1.0",
                            method     = "context.list",
                            parameters = new { },
                            id         = 1
                        };

                        error = "";
                        String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                        String jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);


                        if (String.IsNullOrWhiteSpace(jData))
                        {
                            throw new Exception("");
                        }

                        ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                        if (contextList == null)
                        {
                            error = MessageResource.GetMessage("context_not_found");
                            //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                        }
                        else if (contextList.error != null)
                        {
                            error   = contextList.error.data;
                            retRole = null;
                        }
                        else if (contextList.result == null)
                        {
                            error   = MessageResource.GetMessage("context_not_found");
                            retRole = null;
                        }
                        else
                        {
                            html += "<select id=\"filter_context\" name=\"filter_context\" ><option value=\"\">Todos os contextos</option>";
                            foreach (ContextData c in contextList.result)
                            {
                                html += "<option value=\"context/" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                            }
                            html         += "</select>";
                            contentRet    = new WebJsonResponse("#btnbox", html);
                            contentRet.js = "$('#filter_context').change(function() { iamadmin.changeHash( $( this ).val() ); });";
                        }
                    }
                    catch (Exception ex)
                    {
                        error = MessageResource.GetMessage("api_error");
                    }


                    break;
                }
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Contexto", ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Contexto", ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 contextId = 0;

            try
            {
                contextId = Int64.Parse((String)RouteData.Values["id"]);

                if (contextId < 0)
                {
                    contextId = 0;
                }
            }
            catch { }

            String           error           = "";
            ContextGetResult selectedContext = null;
            String           filter          = "";
            HashData         hashData        = new HashData(this);


            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((contextId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    String rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.get",
                        parameters = new
                        {
                            contextid = contextId
                        },
                        id = 1
                    });
                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    selectedContext = JSON.Deserialize <ContextGetResult>(jData);
                    if (selectedContext == null)
                    {
                        error = MessageResource.GetMessage("context_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (selectedContext.error != null)
                    {
                        error           = selectedContext.error.data;
                        selectedContext = null;
                    }
                    else if (selectedContext.result == null || selectedContext.result.info == null)
                    {
                        error           = MessageResource.GetMessage("context_not_found");
                        selectedContext = null;
                    }
                    else
                    {
                        menu3.Name = selectedContext.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedContext = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            String groupTemplate          = "<div id=\"{0}\"><div class=\"group\" group-id=\"{0}\"><div class=\"wrapper\"><div class=\"cmd-bar\"><div class=\"ico icon-close floatright\"></div></div>{1}<div class=\"cmd-bar1\"><div class=\"ico icon-plus floatright\"></div></div></div><div class=\"clear-block\"></div></div><div class=\"selector-wrapper\">{2}</div></div>";
            String groupSelectorTemplate  = "<div class=\"group-selector\"><div class=\"item selected\" value=\"or\">OU</div><div class=\"clear-block\"></div></div>";
            String filterSelectorTemplate = "<div class=\"filter-selector\"><div class=\"item selected\">+</div><div class=\"clear-block\"></div></div>";

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    html  = "<h3>Adição de contexto</h3>";
                    html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/context/action/add_context/\"><div class=\"no-tabs pb10\">";
                    html += "<div class=\"form-group\"><label>Nome</label><input id=\"add_context_name\" name=\"add_context_name\" placeholder=\"Digite o nome do contexto\" type=\"text\"\"></div>";
                    html += "<div class=\"form-group\"><label>Regra de senha</label><div class=\"custom-item\" id=\"pwd_rule\" onclick=\"iamadmin.buildPwdRule(this);\" data-uri=\"" + ApplicationVirtualPath + "admin/context/new/content/pwd-build/\"><input type=\"hidden\" name=\"pwd_rule\" /><span>Nenhuma regra definida</span><i class=\"icon-change\"></i></div></div>";
                    html += "<div class=\"clear-block\"></div></div>";

                    html += "<h3>Complexidade de senha</h3><div class=\"no-tabs pb10\">";
                    html += "<div class=\"form-group\"><label>Tamanho mínimo</label><input id=\"pwd_length\" name=\"pwd_length\" placeholder=\"Digite o tamanho mínimo de senha\" type=\"text\"\" value=\"8\"></div>";
                    html += "<div class=\"form-group\"><label>Caracter maiúsculo</label><input id=\"pwd_upper_case\" name=\"pwd_upper_case\" type=\"checkbox\" checked><span class=\"checkbox-label\">Exigir</span></div>";
                    html += "<div class=\"form-group\"><label>Caracter minúsculo</label><input id=\"pwd_lower_case\" name=\"pwd_lower_case\" type=\"checkbox\" checked><span class=\"checkbox-label\">Exigir</span></div>";
                    html += "<div class=\"form-group\"><label>Número</label><input id=\"pwd_digit\" name=\"pwd_digit\" type=\"checkbox\" checked><span class=\"checkbox-label\">Exigir</span></div>";
                    html += "<div class=\"form-group\"><label>Caracter especiais</label><input id=\"pwd_symbol\" name=\"pwd_symbol\" type=\"checkbox\" checked><span class=\"checkbox-label\">Exigir</span></div>";
                    html += "<div class=\"form-group\"><label>Parte do nome</label><input id=\"pwd_no_name\" name=\"pwd_no_name\" type=\"checkbox\" checked><span class=\"checkbox-label\">Não permitir</span></div>";
                    html += "<div class=\"clear-block\"></div></div>";
                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button>    <a href=\"" + ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                    contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                }
                else
                {
                    if (selectedContext == null)
                    {
                        Int32   page     = 1;
                        Int32   pageSize = 20;
                        Boolean hasNext  = true;

                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }


                        String roleTemplate = "<div id=\"role-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        roleTemplate += "<table>";
                        roleTemplate += "   <tbody>";
                        roleTemplate += "       <tr>";
                        roleTemplate += "           <td class=\"col1\">";
                        roleTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        roleTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/users/#context/{0}\">";
                        roleTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver usuários</span></div>";
                        roleTemplate += "               </a>";
                        roleTemplate += "           </td>";
                        roleTemplate += "           <td class=\"col2\">";
                        roleTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"context_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#context_name_{0}',null,contextNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        roleTemplate += "               <div class=\"links no-bg\">";
                        roleTemplate += "                   <div class=\"first\"><a href=\"" + ApplicationVirtualPath + "admin/context/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a><a href=\"" + ApplicationVirtualPath + "admin/context/{0}/login_rule/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-cogs\">Regra de criação de login</div></a><a href=\"" + ApplicationVirtualPath + "admin/context/{0}/mail_rule/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-cogs\">Regra de criação de e-mails</div></a><br clear=\"all\"></div>";
                        roleTemplate += "                   <div class=\"\"><a href=\"" + ApplicationVirtualPath + "admin/context/{0}/flow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-sitemap\">Fluxo de dados</div></a></div>";
                        roleTemplate += "                   <div class=\"last\"><a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/context/{0}/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o contexto '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a><br clear=\"all\"></div>";
                        roleTemplate += "               </div><br clear=\"all\">";
                        roleTemplate += "           </td>";
                        roleTemplate += "       </tr>";
                        roleTemplate += "   </tbody>";
                        roleTemplate += "</table></div>";

                        js += "contextNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            String rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "context.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }
                            else
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "context.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }

                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            ContextListResult ret2 = JSON.Deserialize <ContextListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("context_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("context_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (ContextData role in ret2.result)
                                {
                                    html += String.Format(roleTemplate, role.context_id, role.name, role.entity_qty, (role.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(role.create_date), true) : ""));
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading role-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.role-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.role-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado a role
                    {
                        String jData = "";
                        String rData = "";

                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":
                                html  = "<h3>Edição de contexto</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/context/" + selectedContext.result.info.context_id + "/action/change/\"><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"><label>Nome</label><input id=\"add_context_name\" name=\"add_context_name\" placeholder=\"Digite o nome do contexto\" type=\"text\"\" value=\"" + selectedContext.result.info.name + "\"></div>";
                                html += "<div class=\"form-group\"><label>Regra de senha</label><div class=\"custom-item\" id=\"pwd_rule\" onclick=\"iamadmin.buildPwdRule(this);\" data-uri=\"" + ApplicationVirtualPath + "admin/context/new/content/pwd-build/\"><input type=\"hidden\" name=\"pwd_rule\" value=\"" + selectedContext.result.info.password_rule + "\" /><span>" + selectedContext.result.info.password_rule + "</span><i class=\"icon-change\"></i></div></div>";
                                html += "<div class=\"clear-block\"></div></div>";

                                html += "<h3>Complexidade de senha</h3><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"><label>Tamanho mínimo</label><input id=\"pwd_length\" name=\"pwd_length\" placeholder=\"Digite o tamanho mínimo de senha\" type=\"text\"\" value=\"" + selectedContext.result.info.password_length + "\"></div>";
                                html += "<div class=\"form-group\"><label>Caracter maiúsculo</label><input id=\"pwd_upper_case\" name=\"pwd_upper_case\" type=\"checkbox\" " + (selectedContext.result.info.password_upper_case ? "checked" : "") + "><span class=\"checkbox-label\">Exigir</span></div>";
                                html += "<div class=\"form-group\"><label>Caracter minúsculo</label><input id=\"pwd_lower_case\" name=\"pwd_lower_case\" type=\"checkbox\" " + (selectedContext.result.info.password_lower_case ? "checked" : "") + "><span class=\"checkbox-label\">Exigir</span></div>";
                                html += "<div class=\"form-group\"><label>Número</label><input id=\"pwd_digit\" name=\"pwd_digit\" type=\"checkbox\" " + (selectedContext.result.info.password_digit ? "checked" : "") + "><span class=\"checkbox-label\">Exigir</span></div>";
                                html += "<div class=\"form-group\"><label>Caracter especiais</label><input id=\"pwd_symbol\" name=\"pwd_symbol\" type=\"checkbox\" " + (selectedContext.result.info.password_symbol ? "checked" : "") + "><span class=\"checkbox-label\">Exigir</span></div>";
                                html += "<div class=\"form-group\"><label>Parte do nome</label><input id=\"pwd_no_name\" name=\"pwd_no_name\" type=\"checkbox\" " + (selectedContext.result.info.password_no_name ? "checked" : "") + "><span class=\"checkbox-label\">Não permitir</span></div>";
                                html += "<div class=\"clear-block\"></div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                break;


                            case "login_rule":

                                //

                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "context.getloginrules",
                                    parameters = new
                                    {
                                        contextid = contextId
                                    },
                                    id = 1
                                });


                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                if (String.IsNullOrWhiteSpace(jData))
                                {
                                    throw new Exception("");
                                }

                                ContextLoginMailRulesResult ctxLoginRules = JSON.Deserialize <ContextLoginMailRulesResult>(jData);
                                if (ctxLoginRules == null)
                                {
                                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                                }
                                else if (ctxLoginRules.error != null)
                                {
                                    error      = ctxLoginRules.error.data;
                                    contentRet = new WebJsonResponse("", ctxLoginRules.error.data, 3000, true);
                                }
                                else if (ctxLoginRules.result == null)
                                {
                                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                                }
                                else
                                {
                                    String loginTemplate = GetLoginTemplate("");

                                    html  = "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/context/" + selectedContext.result.info.context_id + "/action/change_login_rules/\">";
                                    html += "<h3>Regra para criação de login</h3><div class=\"no-tabs pb10\">";
                                    html += "<div id=\"filter_conditions\"><div><div class=\"a-btn blue secondary\" onclick=\"iamfnc.addRule();\">Inserir regra</div></div>";
                                    html += "<div class=\"filter-groups\">";

                                    if (ctxLoginRules.result.Count == 0)
                                    {
                                        String rules = String.Format(loginTemplate, "R0", "0", "");
                                        html += String.Format(groupTemplate, "0", rules, "");
                                    }
                                    else
                                    {
                                        for (Int32 r = 0; r < ctxLoginRules.result.Count; r++)
                                        {
                                            String rules = "";

                                            //Split items
                                            String[] fi = ctxLoginRules.result[r].rule.Split(",".ToCharArray());

                                            for (Int32 fIndex = 0; fIndex < fi.Length; fIndex++)
                                            {
                                                String fId = r + "-" + fIndex;

                                                String ft = GetLoginTemplate(fi[fIndex]);

                                                rules += String.Format(ft, "R" + fId, r, (fIndex < fi.Length - 1 ? String.Format(filterSelectorTemplate, fId) : ""));
                                            }

                                            html += String.Format(groupTemplate, r, rules, (r < ctxLoginRules.result.Count - 1 ? String.Format(groupSelectorTemplate, r) : ""));

                                            //html += String.Format(groupTemplate, fr.FilterGroups[g].GroupId, filters, (g < fr.FilterGroups.Count - 1 ? (fr.FilterGroups[g].Selector == FilterSelector.AND ? String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "", "selected") : String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "selected", "")) : ""));
                                        }
                                    }

                                    html += "</div>";

                                    html += "</div><div class=\"clear-block\"></div></div>";
                                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                    contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                    contentRet.js = GetLoginJS(groupTemplate, groupSelectorTemplate, loginTemplate, filterSelectorTemplate);
                                }


                                break;


                            case "mail_rule":

                                //

                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "context.getmailrules",
                                    parameters = new
                                    {
                                        contextid = contextId
                                    },
                                    id = 1
                                });

                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                if (String.IsNullOrWhiteSpace(jData))
                                {
                                    throw new Exception("");
                                }

                                ContextLoginMailRulesResult ctxMailRules = JSON.Deserialize <ContextLoginMailRulesResult>(jData);
                                if (ctxMailRules == null)
                                {
                                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                                }
                                else if (ctxMailRules.error != null)
                                {
                                    error      = ctxMailRules.error.data;
                                    contentRet = new WebJsonResponse("", ctxMailRules.error.data, 3000, true);
                                }
                                else if (ctxMailRules.result == null)
                                {
                                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                                }
                                else
                                {
                                    String loginTemplate = GetLoginTemplate("");

                                    html  = "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/context/" + selectedContext.result.info.context_id + "/action/change_mail_rules/\">";
                                    html += "<h3>Regra para criação de e-mail</h3><div class=\"no-tabs pb10\">";
                                    html += "<div id=\"filter_conditions\"><div><div class=\"a-btn blue secondary\" onclick=\"iamfnc.addRule();\">Inserir regra</div></div>";
                                    html += "<div class=\"filter-groups\">";

                                    if (ctxMailRules.result.Count == 0)
                                    {
                                        String rules = String.Format(loginTemplate, "R0", "0", "");
                                        html += String.Format(groupTemplate, "0", rules, "");
                                    }
                                    else
                                    {
                                        for (Int32 r = 0; r < ctxMailRules.result.Count; r++)
                                        {
                                            String rules = "";

                                            //Split items
                                            String[] fi = ctxMailRules.result[r].rule.Split(",".ToCharArray());

                                            for (Int32 fIndex = 0; fIndex < fi.Length; fIndex++)
                                            {
                                                String fId = r + "-" + fIndex;

                                                String ft = GetLoginTemplate(fi[fIndex]);

                                                rules += String.Format(ft, "R" + fId, r, (fIndex < fi.Length - 1 ? String.Format(filterSelectorTemplate, fId) : ""));
                                            }

                                            html += String.Format(groupTemplate, r, rules, (r < ctxMailRules.result.Count - 1 ? String.Format(groupSelectorTemplate, r) : ""));

                                            //html += String.Format(groupTemplate, fr.FilterGroups[g].GroupId, filters, (g < fr.FilterGroups.Count - 1 ? (fr.FilterGroups[g].Selector == FilterSelector.AND ? String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "", "selected") : String.Format(groupSelectorTemplate, fr.FilterGroups[g].GroupId, "selected", "")) : ""));
                                        }
                                    }

                                    html += "</div>";

                                    html += "</div><div class=\"clear-block\"></div></div>";
                                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                    contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                    contentRet.js = GetLoginJS(groupTemplate, groupSelectorTemplate, loginTemplate, filterSelectorTemplate);
                                }


                                break;


                            case "flow":

                                String js2 = "";
                                if (filter == "" || filter == "flow")
                                {
                                    html += "<h3>Fluxo de dados</h3>";
                                    html += "<div id=\"contextChart\"></div>";
                                    js2   = "$('#contextChart').flowchart({load_uri: '" + ApplicationVirtualPath + "admin/chartdata/flow/context/" + selectedContext.result.info.context_id + "/'});";
                                }

                                contentRet    = new WebJsonResponse("#content-wrapper", html);
                                contentRet.js = js2;
                                break;
                            }
                        }
                    }
                }

                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/context/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo contexto</button></div>";

                    switch (filter)
                    {
                    case "add_user":
                    case "login_rule":
                        break;

                    default:
                        if (selectedContext != null)
                        {
                            html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" style=\"font-size: 13px;\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/context/" + selectedContext.result.info.context_id + "/login_rule/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Regras de criação de login</button></div>";
                        }
                        break;
                    }
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":

                switch (filter)
                {
                case "":
                    break;
                }
                break;


            case "pwd-build":
                html += "<div class=\"no-tabs pb10\" style=\"width:480px;\">";
                html += "<div class=\"form-group\"><label>Tipo</label><select id=\"pwd_rule\" name=\"pwd_rule\"><option value=\"\"></option><option value=\"default\">Senha padrão</option><option value=\"random\">Senha randomica</option></select></div>";
                html += "<div class=\"form-group\" style=\"visibility:hidden;\" id=\"field_pass\"><label>Senha padrão</label><input id=\"pwd_pass\" name=\"pwd_pass\" placeholder=\"Digite a senha padrão\" type=\"text\"\"></div>";
                html += "<div class=\"clear-block\"></div></div>";

                contentRet    = new WebJsonResponse("#modal-box .alert-box-content", html);
                contentRet.js = "$('#modal-box #pwd_rule').change(function(oThis){ if ($( this ).val() == 'default'){ $('#modal-box #field_pass').css('visibility','visible') }else{ $('#modal-box #field_pass').css('visibility','hidden') } });";
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Pastas", ApplicationVirtualPath + "admin/workflow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Pastas", ApplicationVirtualPath + "admin/workflow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 workflowId = 0;

            try
            {
                workflowId = Int64.Parse((String)RouteData.Values["id"]);

                if (workflowId < 0)
                {
                    workflowId = 0;
                }
            }
            catch { }

            String            error            = "";
            WorkflowGetResult selectedWorkflow = null;
            String            filter           = "";
            HashData          hashData         = new HashData(this);

            String rData = null;
            //SqlConnection conn = null;
            String jData = "";

            Int32   page     = 1;
            Int32   pageSize = 20;
            Boolean hasNext  = true;

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((workflowId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "workflow.get",
                        parameters = new
                        {
                            workflowid = workflowId
                        },
                        id = 1
                    });
                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    selectedWorkflow = JSON.Deserialize <WorkflowGetResult>(jData);
                    if (selectedWorkflow == null)
                    {
                        error = MessageResource.GetMessage("workflow_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (selectedWorkflow.error != null)
                    {
                        error            = selectedWorkflow.error.data;
                        selectedWorkflow = null;
                    }
                    else if (selectedWorkflow.result == null || selectedWorkflow.result.info == null)
                    {
                        error            = MessageResource.GetMessage("workflow_not_found");
                        selectedWorkflow = null;
                    }
                    else
                    {
                        menu3.Name = selectedWorkflow.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedWorkflow = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            String infoTemplate = "<tr {0}><td class=\"col1\">{1}</td><td class=\"col2\"><span class=\"no-edit\">{2}</span></td></tr>";

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    error = "";
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.list",
                        parameters = new { },
                        id         = 1
                    });

                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                    if (contextList == null)
                    {
                        error = MessageResource.GetMessage("context_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (contextList.error != null)
                    {
                        error = contextList.error.data;
                    }
                    else if (contextList.result == null)
                    {
                        error = MessageResource.GetMessage("context_not_found");
                    }
                    else
                    {
                        rData = SafeTrend.Json.JSON.Serialize2(new
                        {
                            jsonrpc    = "1.0",
                            method     = "container.list",
                            parameters = new
                            {
                                page_size = Int32.MaxValue,
                                page      = 1
                            },
                            id = 1
                        });


                        jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);

                        List <ContainerData> conteinerList = new List <ContainerData>();
                        ContainerListResult  cl            = JSON.Deserialize <ContainerListResult>(jData);
                        if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
                        {
                            conteinerList.AddRange(cl.result);
                        }

                        html  = "<h3>Adição de workflow</h3>";
                        html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/workflow/action/add_container/\">";
                        html += "<div class=\"no-tabs fields\"><table><tbody>";

                        html += String.Format(infoTemplate, "", "Nome", "<input id=\"workflow_name\" name=\"workflow_name\" placeholder=\"Digite o nome do workflow\" type=\"text\"\">");

                        String select = "<select id=\"workflow_context\" name=\"workflow_context\" ><option value=\"\"></option>";
                        foreach (ContextData c in contextList.result)
                        {
                            select += "<option value=\"" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                        }
                        select += "</select>";

                        html += String.Format(infoTemplate, "", "Contexto", select);

                        select = "<select id=\"workflow_type\" name=\"workflow_type\" ><option value=\"\"></option>";
                        foreach (IAM.Workflow.WorkflowAccessType type in (IAM.Workflow.WorkflowAccessType[])Enum.GetValues(typeof(IAM.Workflow.WorkflowAccessType)))
                        {
                            if (type != IAM.Workflow.WorkflowAccessType.None)
                            {
                                select += "<option value=\"" + (Int32)type + "\">" + MessageResource.GetMessage("wf_" + type.ToString().ToLower(), type.ToString()) + "</option>";
                            }
                        }
                        select += "</select>";

                        html += String.Format(infoTemplate, "", "Tipo", select);

                        html += String.Format(infoTemplate, "id=\"" + (Int32)IAM.Workflow.WorkflowAccessType.RoleGrant + "\" class=\"workflow_type_hidden\" style=\"display:none;\"", "Perfis", "<input id=\"role\" name=\"role\" placeholder=\"Digite o nome do perfil desejado\" type=\"text\"\"><div id=\"selected_role\" class=\"item-box\"></div><span class=\"description red-text none-role\" style=\"opacity:1;\">Nenhum perfil selecionado</span>");

                        html += String.Format(infoTemplate, "", "Proprietário", "<input id=\"owner\" name=\"owner\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"><div id=\"selected_user\" class=\"item-box\"></div><span class=\"description red-text none-user\" style=\"opacity:1;\">Nenhum usuário selecionado</span>");

                        html += String.Format(infoTemplate, "", "Descrição", "<textarea id=\"description\" name=\"description\" rows=\"5\" placeholder=\"Digite a descrição que será exibida ao usuário requisitante do acesso\"></textarea>");

                        html += "</tbody></table><div class=\"clear-block\"></div></div>";


                        html += "<h3>Passos de aprovação</h3>";
                        html += "<div class=\"no-tabs fields\"><table><tbody>";

                        String stepTemplate = "<div class=\"custom-item\" id=\"act_[id]\" onclick=\"iamadmin.buildWorkflowAct(this);\" data-uri=\"" + ApplicationVirtualPath + "admin/workflow/content/activity-build/\"><input type=\"hidden\" name=\"act\" value=\"[id]\" /><input type=\"hidden\" name=\"act_key_[id]\" class=\"key\" /><span></span><i class=\"icon-change\"></i></div><div class=\"ico icon-add act-add-subtract left\"  onclick=\"iamfnc.addActivity(this);\"></div>";

                        html += String.Format(infoTemplate, "class=\"activity\"", "Passo de aprovação", stepTemplate.Replace("[id]", "1"));

                        html += "</tbody></table><div class=\"clear-block\"></div></div>";

                        html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/workflow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                        js = "iamadmin.autoCompleteText('#owner', '" + ApplicationVirtualPath + "admin/workflow/content/search_user/', { content_id: 'owner_id' } , function(thisId, selectedItem){ $(thisId).val(''); $('.none-user').remove(); $('#selected_user').html(selectedItem.html); } );";

                        js += "iamadmin.autoCompleteText('#role', '" + ApplicationVirtualPath + "admin/workflow/content/search_role/', { content_id: 'role_id' } , function(thisId, selectedItem){ $(thisId).val(''); $('.none-role').remove(); $('#selected_role').append(selectedItem.html); } );";

                        js += "$('#workflow_type').change(function() {";
                        js += "    $('.workflow_type_hidden').css('display','none');";
                        js += "    $('#' + $( this ).val()).css('display','table-row');";
                        js += "});";

                        js += "iamfnc.addActivity = function(objThis){ ";
                        js += "    var lc = $(objThis).closest('.activity');";
                        js += "    var id = new Date().getTime(); console.log(lc);";
                        js += "    $('" + String.Format(infoTemplate, "class=\"activity\"", "Passo de aprovação", stepTemplate + "<div class=\"ico icon-subtract act-add-subtract left\" onclick=\"iamadmin.removeLine(this);\"></div>") + "'.replace(/\\[id\\]/g,id)).insertAfter(lc);";
                        js += "};";

                        js += "iamadmin.removeLine = function(objThis){ ";
                        js += "    $(objThis).closest('.activity').remove();";
                        js += "};";

                        //js += "$('#filter_context').change(function() { iamadmin.changeHash( $( this ).val() ); });";

                        contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        contentRet.js = js;
                    }
                }
                else
                {
                    if (selectedWorkflow == null)
                    {
                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }

                        String containerTemplate = "<div id=\"proxy-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        containerTemplate += "<table>";
                        containerTemplate += "   <tbody>";
                        containerTemplate += "       <tr>";
                        containerTemplate += "           <td class=\"col1\">";
                        containerTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        containerTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/users/\">";
                        containerTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Requisições</span></div>";
                        containerTemplate += "               </a>";
                        containerTemplate += "           </td>";
                        containerTemplate += "           <td class=\"col2\">";
                        containerTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"workflow_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#workflow_name_{0}',null,workflowNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        containerTemplate += "               <div class=\"description\">";
                        containerTemplate += "                   <div class=\"first\">{4}</div>";
                        containerTemplate += "               </div>";
                        containerTemplate += "               <div class=\"links\">";
                        containerTemplate += "                   <div class=\"line\">{5}</div><div class=\"clear-block\"></div>";
                        containerTemplate += "               </div>";
                        containerTemplate += "           </td>";
                        containerTemplate += "       </tr>";
                        containerTemplate += "   </tbody>";
                        containerTemplate += "</table></div>";

                        js += "workflowNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "workflow.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }
                            else
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "workflow.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }

                            jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);

                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            WorkflowListResult ret2 = JSON.Deserialize <WorkflowListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("workflow_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("workflow_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (WorkflowData w in ret2.result)
                                {
                                    String text = "";
                                    if (w.description != null)
                                    {
                                        text += "<span>Descrição: " + w.description + "</span><br />";
                                    }

                                    if (w.activities != null)
                                    {
                                        text += "<span>Atividades de aprovação: " + (w.activities.Count == 0 ? "Nenhuma atividade cadastrada":"");

                                        foreach (WorkflowDataActivity a in w.activities)
                                        {
                                            text += "<div style=\"padding-left: 20px;\">" + a.name + "</div>";
                                        }

                                        text += "</span>";
                                    }


                                    //if (w. != null)
                                    //    text += "<span>Contexto: " + c.context_name + "</span>";

                                    String links = "";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/workflow/" + w.workflow_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/workflow/" + w.workflow_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a>";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/workflow/" + w.workflow_id + "/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários da pasta '" + w.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a>";
                                    links += "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/workflow/" + w.workflow_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente a pasta '" + w.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>";

                                    html += String.Format(containerTemplate, w.workflow_id, w.name, w.request_qty, (w.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(w.create_date), true) : ""), text, links);
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading proxy-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.proxy-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.proxy-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado o content
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":



                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "container.list",
                                    parameters = new
                                    {
                                        page_size = Int32.MaxValue,
                                        page      = 1
                                    },
                                    id = 1
                                });


                                jData = "";
                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                List <ContainerData> conteinerList = new List <ContainerData>();
                                ContainerListResult  cl            = JSON.Deserialize <ContainerListResult>(jData);
                                if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
                                {
                                    conteinerList.AddRange(cl.result);
                                }

                                html  = "<h3>Edição do workflow</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/workflow/" + selectedWorkflow.result.info.workflow_id + "/action/change/\">";
                                html += "<div class=\"no-tabs fields\"><table><tbody>";
                                html += String.Format(infoTemplate, "", "Nome", "<input id=\"container_name\" name=\"container_name\" placeholder=\"Digite o nome da pasta\" type=\"text\"\" value=\"" + selectedWorkflow.result.info.name + "\">");

                                html += String.Format(infoTemplate, "", "Contexto", selectedWorkflow.result.info.name);

                                html += "</tbody></table><div class=\"clear-block\"></div></div>";

                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/workflow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));

                                break;


                            case "add_user":
                                html  = "<h3>Adição de usuário</h3>";
                                html += "<form id=\"form_add_user\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/workflow/" + workflowId + "/action/add_user/\"><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"  id=\"add_user\"><label>Usuário</label><input id=\"add_user_text\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"></div>";
                                html += "<div class=\"clear-block\"></div></div>";
                                html += "<h3>Usuários selecionados</h3>";
                                html += "<div id=\"box-container\" class=\"box-container\"><div class=\"no-tabs pb10 none\">";
                                html += "Nenhum usuário selecionado";
                                html += "</div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Cadastrar</button>    <a href=\"" + ApplicationVirtualPath + "admin/workflow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                contentRet.js = "iamadmin.autoCompleteText('#add_user_text', '" + ApplicationVirtualPath + "admin/users/content/search_user/', {context_id: '" + selectedWorkflow.result.info.context_id + "'} , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )";

                                break;
                            }
                        }
                    }
                }
                break;


            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/workflow/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo workflow</button></div>";
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":
                break;


            case "search_user":
                List <AutoCompleteItem> users = new List <AutoCompleteItem>();

                try
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.search",
                        parameters = new
                        {
                            page_size = 20,
                            page      = 1,
                            text      = Request.Form["text"],
                            filter    = new { contextid = Request.Form["context_id"] }
                        },
                        id = 1
                    });

                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    SearchResult ret2 = JSON.Deserialize <SearchResult>(jData);
                    if (ret2 == null)
                    {
                        //eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (ret2.error != null)
                    {
                        eHtml += String.Format(errorTemplate, ret2.error.data);
                    }
                    else if (ret2.result == null)
                    {
                        //eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                    }
                    else
                    {
                        foreach (UserData user in ret2.result)
                        {
                            String tHtml = "<div class=\"item\"><input type=\"hidden\" name=\"" + Request.Form["content_id"] + "\" id=\"" + Request.Form["content_id"] + "\" value=\"" + user.userid + "\"><div class=\"text\">" + user.login + "</div><div class=\"delete ico icon-close\" onclick=\"$(this).closest('.item').remove();\"></div><div class=\"clear-block\"></div></div>";
                            users.Add(new AutoCompleteItem(user.userid, "(" + user.login + ") " + user.full_name, tHtml));
                        }
                    }
                }
                catch (Exception ex)
                {
                    eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }

                if (users.Count == 0)
                {
                    users.Add(new AutoCompleteItem(0, MessageResource.GetMessage("user_not_found"), ""));
                }

                Retorno.Controls.Add(new LiteralControl(JSON.Serialize <List <AutoCompleteItem> >(users)));

                break;


            case "search_role":
                List <AutoCompleteItem> roles = new List <AutoCompleteItem>();

                try
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.search",
                        parameters = new
                        {
                            page_size = 20,
                            page      = 1,
                            text      = Request.Form["text"],
                            filter    = new { contextid = Request.Form["context_id"] }
                        },
                        id = 1
                    });

                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    RoleListResult ret2 = JSON.Deserialize <RoleListResult>(jData);
                    if (ret2 == null)
                    {
                        //eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (ret2.error != null)
                    {
                        eHtml += String.Format(errorTemplate, ret2.error.data);
                    }
                    else if (ret2.result == null)
                    {
                        //eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found"));
                    }
                    else
                    {
                        foreach (RoleData role in ret2.result)
                        {
                            String tHtml = "<div class=\"item\"><input type=\"hidden\" name=\"" + Request.Form["content_id"] + "\" id=\"" + Request.Form["content_id"] + "\" value=\"" + role.role_id + "\"><div class=\"text\">" + role.name + "</div><div class=\"delete ico icon-close\" onclick=\"$(this).closest('.item').remove();\"></div><div class=\"clear-block\"></div></div>";
                            roles.Add(new AutoCompleteItem(role.role_id, role.name, tHtml));
                        }
                    }
                }
                catch (Exception ex)
                {
                    eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }

                if (roles.Count == 0)
                {
                    roles.Add(new AutoCompleteItem(0, MessageResource.GetMessage("role_not_found"), ""));
                }

                Retorno.Controls.Add(new LiteralControl(JSON.Serialize <List <AutoCompleteItem> >(roles)));

                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Pastas", ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Pastas", ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 containerId = 0;

            try
            {
                containerId = Int64.Parse((String)RouteData.Values["id"]);

                if (containerId < 0)
                {
                    containerId = 0;
                }
            }
            catch { }

            String             error             = "";
            ContainerGetResult selectedContainer = null;
            String             filter            = "";
            HashData           hashData          = new HashData(this);

            String rData = null;
            //SqlConnection conn = null;
            String jData = "";

            Int32   page     = 1;
            Int32   pageSize = 20;
            Boolean hasNext  = true;

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((containerId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "container.get",
                        parameters = new
                        {
                            containerid = containerId
                        },
                        id = 1
                    });
                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    selectedContainer = JSON.Deserialize <ContainerGetResult>(jData);
                    if (selectedContainer == null)
                    {
                        error = MessageResource.GetMessage("container_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (selectedContainer.error != null)
                    {
                        error             = selectedContainer.error.data;
                        selectedContainer = null;
                    }
                    else if (selectedContainer.result == null || selectedContainer.result.info == null)
                    {
                        error             = MessageResource.GetMessage("container_not_found");
                        selectedContainer = null;
                    }
                    else
                    {
                        menu3.Name = selectedContainer.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedContainer = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            String infoTemplate = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    error = "";
                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.list",
                        parameters = new { },
                        id         = 1
                    });

                    jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                    if (contextList == null)
                    {
                        error = MessageResource.GetMessage("context_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (contextList.error != null)
                    {
                        error = contextList.error.data;
                    }
                    else if (contextList.result == null)
                    {
                        error = MessageResource.GetMessage("context_not_found");
                    }
                    else
                    {
                        rData = SafeTrend.Json.JSON.Serialize2(new
                        {
                            jsonrpc    = "1.0",
                            method     = "container.list",
                            parameters = new
                            {
                                page_size = Int32.MaxValue,
                                page      = 1
                            },
                            id = 1
                        });


                        jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);

                        List <ContainerData> conteinerList = new List <ContainerData>();
                        ContainerListResult  cl            = JSON.Deserialize <ContainerListResult>(jData);
                        if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
                        {
                            conteinerList.AddRange(cl.result);
                        }

                        html  = "<h3>Adição de pasta</h3>";
                        html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/action/add_container/\">";
                        html += "<div class=\"no-tabs fields\"><table><tbody>";
                        html += String.Format(infoTemplate, "Nome", "<input id=\"container_name\" name=\"container_name\" placeholder=\"Digite o nome da pasta\" type=\"text\"\">");

                        String select = "<select id=\"container_context\" name=\"container_context\" ><option value=\"\"></option>";
                        foreach (ContextData c in contextList.result)
                        {
                            select += "<option value=\"" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                        }
                        select += "</select>";

                        html += String.Format(infoTemplate, "Contexto", select);

                        Func <String, Int64, Int64, String> chields = null;
                        chields = new Func <String, long, long, string>(delegate(String padding, Int64 root, Int64 ctx)
                        {
                            String h = "";
                            foreach (ContainerData c in conteinerList)
                            {
                                if ((c.parent_id == root) && (c.context_id == ctx))
                                {
                                    h += "<option value=\"" + c.container_id + "\" " + (hashData.GetValue("container") == c.container_id.ToString() ? "selected" : "") + ">" + padding + " " + c.name + "</option>";
                                    h += chields(padding + "---", c.container_id, ctx);
                                }
                            }

                            return(h);
                        });

                        select = "<select id=\"parent_container\" name=\"parent_container\" >";
                        foreach (ContextData ctx in contextList.result)
                        {
                            select += "<option value=\"0\">Raiz no contexto " + ctx.name + "</option>";
                            select += chields("|", 0, ctx.context_id);
                        }
                        select += "</select>";
                        html   += String.Format(infoTemplate, "Pasta pai", select);

                        html += "</tbody></table><div class=\"clear-block\"></div></div>";

                        html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                        contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    }
                }
                else
                {
                    if (selectedContainer == null)
                    {
                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }

                        String containerTemplate = "<div id=\"proxy-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        containerTemplate += "<table>";
                        containerTemplate += "   <tbody>";
                        containerTemplate += "       <tr>";
                        containerTemplate += "           <td class=\"col1\">";
                        containerTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        containerTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/users/#container/{0}\">";
                        containerTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver usuários</span></div>";
                        containerTemplate += "               </a>";
                        containerTemplate += "           </td>";
                        containerTemplate += "           <td class=\"col2\">";
                        containerTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"container_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#container_name_{0}',null,containerNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        containerTemplate += "               <div class=\"description\">";
                        containerTemplate += "                   <div class=\"first\">{4}</div>";
                        containerTemplate += "               </div>";
                        containerTemplate += "               <div class=\"links\">";
                        containerTemplate += "                   <div class=\"line\">{5}</div><div class=\"clear-block\"></div>";
                        containerTemplate += "               </div>";
                        containerTemplate += "           </td>";
                        containerTemplate += "       </tr>";
                        containerTemplate += "   </tbody>";
                        containerTemplate += "</table></div>";

                        js += "containerNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            rData = "";

                            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                            {
                                query = (String)RouteData.Values["query"];
                            }

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "container.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }
                            else
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "container.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                });
                            }

                            jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);

                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            ContainerListResult ret2 = JSON.Deserialize <ContainerListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("container_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("container_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (ContainerData c in ret2.result)
                                {
                                    String text = "";
                                    if (c.path != null)
                                    {
                                        text += "<span>Path: " + c.path + "</span><br />";
                                    }

                                    if (c.context_name != null)
                                    {
                                        text += "<span>Contexto: " + c.context_name + "</span>";
                                    }

                                    String links = "";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a>";
                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários da pasta '" + c.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a>";
                                    links += (c.entity_qty > 0 ? "" : "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/container/" + c.container_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente a pasta '" + c.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>");

                                    html += String.Format(containerTemplate, c.container_id, c.name, c.entity_qty, (c.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(c.create_date), true) : ""), text, links);
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading proxy-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.proxy-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.proxy-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado o content
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                            switch (filter)
                            {
                            case "":



                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "container.list",
                                    parameters = new
                                    {
                                        page_size = Int32.MaxValue,
                                        page      = 1
                                    },
                                    id = 1
                                });


                                jData = "";
                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    jData = WebPageAPI.ExecuteLocal(database, this, rData);

                                List <ContainerData> conteinerList = new List <ContainerData>();
                                ContainerListResult  cl            = JSON.Deserialize <ContainerListResult>(jData);
                                if ((cl != null) && (cl.error == null) && (cl.result != null) && (cl.result.Count > 0))
                                {
                                    conteinerList.AddRange(cl.result);
                                }

                                html  = "<h3>Edição da pasta</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/" + selectedContainer.result.info.container_id + "/action/change/\">";
                                html += "<div class=\"no-tabs fields\"><table><tbody>";
                                html += String.Format(infoTemplate, "Nome", "<input id=\"container_name\" name=\"container_name\" placeholder=\"Digite o nome da pasta\" type=\"text\"\" value=\"" + selectedContainer.result.info.name + "\">");

                                html += String.Format(infoTemplate, "Contexto", selectedContainer.result.info.context_name);

                                Func <String, Int64, Int64, String> chields = null;
                                chields = new Func <String, long, long, string>(delegate(String padding, Int64 root, Int64 ctx)
                                {
                                    String h = "";
                                    foreach (ContainerData c in conteinerList)
                                    {
                                        if ((c.parent_id == root) && (c.context_id == ctx))
                                        {
                                            h += "<option value=\"" + c.container_id + "\" " + (selectedContainer.result.info.parent_id.ToString() == c.container_id.ToString() ? "selected" : "") + ">" + padding + " " + c.name + "</option>";
                                            h += chields(padding + "---", c.container_id, ctx);
                                        }
                                    }

                                    return(h);
                                });

                                String select = "<select id=\"parent_container\" name=\"parent_container\" >";
                                select += "<option value=\"0\">Raiz no contexto " + selectedContainer.result.info.context_name + "</option>";
                                select += chields("|", 0, selectedContainer.result.info.context_id);
                                select += "</select>";
                                html   += String.Format(infoTemplate, "Pasta pai", select);


                                html += "</tbody></table><div class=\"clear-block\"></div></div>";

                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));

                                break;


                            case "add_user":
                                html  = "<h3>Adição de usuário</h3>";
                                html += "<form id=\"form_add_user\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/container/" + containerId + "/action/add_user/\"><div class=\"no-tabs pb10\">";
                                html += "<div class=\"form-group\"  id=\"add_user\"><label>Usuário</label><input id=\"add_user_text\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"></div>";
                                html += "<div class=\"clear-block\"></div></div>";
                                html += "<h3>Usuários selecionados</h3>";
                                html += "<div id=\"box-container\" class=\"box-container\"><div class=\"no-tabs pb10 none\">";
                                html += "Nenhum usuário selecionado";
                                html += "</div></div>";
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Cadastrar</button>    <a href=\"" + ApplicationVirtualPath + "admin/container/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                                contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                contentRet.js = "iamadmin.autoCompleteText('#add_user_text', '" + ApplicationVirtualPath + "admin/users/content/search_user/', {context_id: '" + selectedContainer.result.info.context_id + "'} , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )";

                                break;
                            }
                        }
                    }
                }
                break;


            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/container/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Nova pasta</button></div>";
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"]))
            {
                area = (String)RouteData.Values["area"];
            }

            Int64 enterpriseId = 0;

            if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData))
            {
                enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id;
            }

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Requisições de acesso", ApplicationVirtualPath + "admin/access_request/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Requisições de acesso", ApplicationVirtualPath + "admin/access_request/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 requestId = 0;

            try
            {
                requestId = Int64.Parse((String)RouteData.Values["id"]);

                if (requestId < 0)
                {
                    requestId = 0;
                }
            }
            catch { }

            String error = "";
            WorkflowRequestGetResult selectedRequest = null;
            String   filter   = "";
            HashData hashData = new HashData(this);


            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"]))
            {
                filter = (String)RouteData.Values["filter"];
            }

            if ((requestId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    String rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "workflow.getrequest",
                        parameters = new
                        {
                            requestid = requestId
                        },
                        id = 1
                    });

                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    selectedRequest = JSON.Deserialize <WorkflowRequestGetResult>(jData);
                    if (selectedRequest == null)
                    {
                        error = MessageResource.GetMessage("workflow_request_not_found");
                    }
                    else if (selectedRequest.error != null)
                    {
                        error           = selectedRequest.error.data;
                        selectedRequest = null;
                    }
                    else if (selectedRequest.result == null || selectedRequest.result.info == null)
                    {
                        error           = MessageResource.GetMessage("workflow_request_not_found");
                        selectedRequest = null;
                    }
                    else
                    {
                        menu3.Name = selectedRequest.result.info.workflow.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedRequest = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (selectedRequest == null)    //Listagem
                {
                    Int32   page     = 1;
                    Int32   pageSize = 30;
                    Boolean hasNext  = true;

                    Int32.TryParse(Request.Form["page"], out page);

                    if (page < 1)
                    {
                        page = 1;
                    }

                    if (page == 1)
                    {
                        html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                        html += "    <tr>";
                        html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                        html += "        <th class=\"pointer w150 header headerSortDown\" data-column=\"name\">Data <div class=\"icomoon\"></div></th>";
                        html += "        <th class=\"pointer tHide mHide header\" data-column=\"login\">Workflow <div class=\"icomoon\"></div></th>";
                        html += "        <th class=\"pointer tHide mHide header\" data-column=\"last_login\">Usuário <div class=\"icomoon\"></div></th>";
                        html += "        <th class=\"pointer w200 tHide mHide header\" data-column=\"last_login\">Ações <div class=\"icomoon\"></div></th>";
                        html += "    </tr>";
                        html += "</thead>";

                        html += "<tbody>";
                    }

                    String trTemplate = "    <tr class=\"access_request\" id=\"request_{0}\" data-login=\"{2}\" data-request=\"{0}\" data-userid=\"{1}\" data-href=\"" + ApplicationVirtualPath + "admin/access_request/{0}/\">";
                    trTemplate += "            <td class=\"pointer select mHide\"><div class=\"checkbox\"></div></td>";
                    trTemplate += "            <td class=\"pointer\">{3}</td>";
                    trTemplate += "            <td class=\"pointer tHide mHide\">{4}</td>";
                    trTemplate += "            <td class=\"pointer tHide mHide\">{5}</td>";
                    trTemplate += "            <td class=\"pointer tHide mHide\">{6}</td>";
                    trTemplate += "    </tr>";

                    try
                    {
                        String rData = "";
                        String query = "";


                        Int32 status = (Int32)IAM.Workflow.WorkflowRequestStatus.Waiting;
                        try
                        {
                            status = Int32.Parse(hashData.GetValue("status"));
                        }
                        catch { }


                        if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"]))
                        {
                            query = (String)RouteData.Values["query"];
                        }

                        if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                        {
                            query = hashData.GetValue("query");
                        }



                        if (String.IsNullOrWhiteSpace(query))
                        {
                            rData = SafeTrend.Json.JSON.Serialize2(new
                            {
                                jsonrpc    = "1.0",
                                method     = "workflow.accessrequestlist",
                                parameters = new
                                {
                                    text      = query,
                                    page_size = pageSize,
                                    page      = page,
                                    filter    = new { status = status, contextid = hashData.GetValue("context"), workflowid = hashData.GetValue("workflow") }
                                },
                                id = 1
                            });
                        }
                        else
                        {
                            rData = SafeTrend.Json.JSON.Serialize2(new
                            {
                                jsonrpc    = "1.0",
                                method     = "role.accessrequestsearch",
                                parameters = new
                                {
                                    text      = query,
                                    page_size = pageSize,
                                    page      = page,
                                    filter    = new { status = status, contextid = hashData.GetValue("context"), workflowid = hashData.GetValue("workflow") }
                                },
                                id = 1
                            });
                        }


                        String jData = "";
                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            jData = WebPageAPI.ExecuteLocal(database, this, rData);

                        if (String.IsNullOrWhiteSpace(jData))
                        {
                            throw new Exception("");
                        }

                        WorkflowRequestListResult ret2 = JSON.Deserialize <WorkflowRequestListResult>(jData);
                        if (ret2 == null)
                        {
                            eHtml   = String.Format(errorTemplate, MessageResource.GetMessage("access_request_none"));
                            hasNext = false;
                        }
                        else if (ret2.error != null)
                        {
                            eHtml = String.Format(errorTemplate, ret2.error.data);
#if DEBUG
                            eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#endif
                            hasNext = false;
                        }
                        else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                        {
                            eHtml   = String.Format(errorTemplate, MessageResource.GetMessage("access_request_none"));
                            hasNext = false;
                        }
                        else
                        {
                            foreach (WorkflowRequestData request in ret2.result)
                            {
                                String actions = "";
                                switch ((IAM.Workflow.WorkflowRequestStatus)request.status)
                                {
                                case IAM.Workflow.WorkflowRequestStatus.Waiting:
                                case IAM.Workflow.WorkflowRequestStatus.Escalated:
                                case IAM.Workflow.WorkflowRequestStatus.Expired:
                                case IAM.Workflow.WorkflowRequestStatus.UnderReview:
                                    actions += "<div class=\"a-btn blue data-action no-reload\" data-action=\"" + ApplicationVirtualPath + "admin/access_request/" + request.access_request_id + "/action/allow/\">Aprovar</div>";
                                    actions += "&nbsp;<button href=\"" + ApplicationVirtualPath + "admin/access_request/" + request.access_request_id + "/action/deny/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"a-btn red confirm-action no-reload\" confirm-title=\"Negar acesso\" confirm-text=\"Deseja negar o acesso do usuário?\" ok=\"Negar\" cancel=\"Cancelar\">Negar</button>";
                                    break;

                                case IAM.Workflow.WorkflowRequestStatus.Approved:
                                    actions += "<button href=\"" + ApplicationVirtualPath + "admin/access_request/" + request.access_request_id + "/action/revoke/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"a-btn red confirm-action no-reload\" confirm-title=\"Revogar acesso\" confirm-text=\"Deseja revogar o acesso do usuário?\" ok=\"Revogar\" cancel=\"Cancelar\">Revogar</button>";
                                    break;
                                }

                                html += String.Format(trTemplate,
                                                      request.access_request_id,
                                                      request.entity_id,
                                                      request.entity_login,
                                                      (request.create_date > 0 ? MessageResource.FormatDate(new DateTime(1070, 1, 1).AddSeconds(request.create_date), false) : ""),
                                                      request.workflow.name,
                                                      request.entity_full_name,
                                                      actions
                                                      );
                            }

                            if (ret2.result.Count < pageSize)
                            {
                                hasNext = false;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        eHtml = String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                    }

                    if (page == 1)
                    {
                        html += "</tbody></table>";

                        html += "<span class=\"empty-results content-loading user-list-loader hide\"></span>";

                        contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("#content-wrapper tbody", (eHtml != "" ? eHtml : html), true);
                    }

                    contentRet.js = "$( document ).unbind('end_of_scroll.loader_access_request');";

                    if (hasNext)
                    {
                        contentRet.js += "$( document ).bind( 'end_of_scroll.loader_access_request', function() { $( document ).unbind('end_of_scroll.loader_access_request'); $('.user-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'' }, function(){ $('.user-list-loader').addClass('hide'); } ); });";
                    }
                }
                else    //Esta sendo selecionado a requisição
                {
                    if (error != "")
                    {
                        contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                    }
                    else
                    {
                        String infoTemplate = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";

                        switch (filter)
                        {
                        case "":
                        case "allow":
                        case "deny":
                            html += "<h3>" + selectedRequest.result.info.workflow.name + "</h3>";
                            html += "<div class=\"no-tabs fields\"><table><tbody>";

                            html += String.Format(infoTemplate, "Acesso", "<span class=\"no-edit\">" + selectedRequest.result.info.workflow.name + "<span class=\"description\">" + selectedRequest.result.info.workflow.description + "</span></span>");

                            html += String.Format(infoTemplate, "Último status", MessageResource.GetMessage("wf_" + ((IAM.Workflow.WorkflowRequestStatus)selectedRequest.result.info.status).ToString().ToLower()));

                            switch (((IAM.Workflow.WorkflowRequestStatus)selectedRequest.result.info.status))
                            {
                            case IAM.Workflow.WorkflowRequestStatus.Approved:
                            case IAM.Workflow.WorkflowRequestStatus.Deny:
                                //html += String.Format(infoTemplate, "Último status", MessageResource.GetMessage("wf_" + ((IAM.Workflow.WorkflowRequestStatus)selectedRequest.result.info.status).ToString().ToLower()));
                                break;
                            }


                            html += String.Format(infoTemplate, "Data da requisição", (new DateTime(1970, 1, 1).AddSeconds(selectedRequest.result.info.create_date)).ToString("yyyy-MM-dd HH:mm:ss"));

                            html += String.Format(infoTemplate, "Descrição da necessidade do acesso", selectedRequest.result.info.description);

                            //html += String.Format(infoTemplate, "", "<span type=\"submit\" id=\"cancel\" class=\"button secondary floatleft red\">Cancelar requisição</span>");

                            html += "</tbody></table><div class=\"clear-block\"></div></div>";

                            html += "<h3>Todos os status</h3>";

                            html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                            html += "    <tr>";
                            html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                            html += "        <th class=\"pointer w150 header headerSortDown\" data-column=\"name\">Data <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer w200 tHide mHide header\" data-column=\"status\">Status <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header {sorter: false}\" data-column=\"create_date\">Descrição <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";

                            String trTemplate = "    <tr class=\"request\" data-userid=\"{0}\">";
                            trTemplate += "            <td class=\"select mHide\"><div class=\"checkbox\"></div></td>";
                            trTemplate += "            <td class=\"\">{1}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{2}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{3}</td>";
                            trTemplate += "    </tr>";

                            /*
                             * DataTable drRequestStatus = database.ExecuteDataTable("select * from st_workflow_request_status r with(nolock) where r.workflow_request_id = " + drRequest.Rows[0]["id"] + " order by date desc");
                             * if ((drRequestStatus != null) && (drRequestStatus.Rows.Count > 0))
                             * {
                             *
                             *  foreach (DataRow dr in drRequestStatus.Rows)
                             *  {
                             *      try
                             *      {
                             *          html += String.Format(trTemplate, dr["id"], ((DateTime)dr["date"]).ToString("yyyy-MM-dd HH:mm:ss"), dr["status"], dr["description"]);
                             *      }
                             *      catch (Exception ex)
                             *      {
                             *
                             *      }
                             *  }
                             * }*/

                            break;
                        }

                        contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    }
                }


                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }


                if (selectedRequest != null)
                {
                    switch ((IAM.Workflow.WorkflowRequestStatus)selectedRequest.result.info.status)
                    {
                    case IAM.Workflow.WorkflowRequestStatus.Waiting:
                    case IAM.Workflow.WorkflowRequestStatus.Escalated:
                    case IAM.Workflow.WorkflowRequestStatus.Expired:
                    case IAM.Workflow.WorkflowRequestStatus.UnderReview:
                        html += "<div class=\"sep\"><button class=\"a-btn-big a-btn data-action\" type=\"button\" data-action=\"" + ApplicationVirtualPath + "admin/access_request/" + selectedRequest.result.info.access_request_id + "/action/allow/\">Aprovar requisição</button></div>";
                        html += "<div class=\"sep\"><button class=\"a-btn-big a-btn red confirm-action\" type=\"button\" href=\"" + ApplicationVirtualPath + "admin/access_request/" + selectedRequest.result.info.access_request_id + "/action/deny/\" confirm-title=\"Negar acesso\" confirm-text=\"Deseja negar o acesso do usuário?\" ok=\"Negar\" cancel=\"Cancelar\">Negar acesso</button></div>";
                        break;

                    case IAM.Workflow.WorkflowRequestStatus.Approved:
                        html += "<div class=\"sep\"><button class=\"a-btn-big a-btn red confirm-action\" type=\"button\" href=\"" + ApplicationVirtualPath + "admin/access_request/" + selectedRequest.result.info.access_request_id + "/action/revoke/\" confirm-title=\"Revogar acesso\" confirm-text=\"Deseja revogar o acesso do usuário?\" ok=\"Revogar\" cancel=\"Cancelar\">Revogar acesso</button></div>";
                        break;
                    }
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":

                if (selectedRequest == null)
                {
                    switch (filter)
                    {
                    case "":

                        try
                        {
                            var tmpReq = new
                            {
                                jsonrpc    = "1.0",
                                method     = "context.list",
                                parameters = new { },
                                id         = 1
                            };

                            error = "";
                            String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            String jData = "";
                            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);


                            if (String.IsNullOrWhiteSpace(jData))
                            {
                                throw new Exception("");
                            }

                            ContextListResult contextList = JSON.Deserialize <ContextListResult>(jData);
                            if (contextList == null)
                            {
                                error = MessageResource.GetMessage("context_not_found");
                                //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                            }
                            else if (contextList.error != null)
                            {
                                error           = contextList.error.data;
                                selectedRequest = null;
                            }
                            else if (contextList.result == null)
                            {
                                error           = MessageResource.GetMessage("context_not_found");
                                selectedRequest = null;
                            }
                            else
                            {
                                html += "<select id=\"filter_context\" name=\"filter_context\" ><option value=\"\">Todos os contextos</option>";
                                foreach (ContextData c in contextList.result)
                                {
                                    html += "<option value=\"context/" + c.context_id + "\" " + (hashData.GetValue("context") == c.context_id.ToString() ? "selected" : "") + ">" + c.name + "</option>";
                                }
                                html += "</select>";
                                //contentRet = new WebJsonResponse("#btnbox", html);
                                js += "$('#filter_context').change(function() { iamadmin.changeHash( $( this ).val() ); });";
                            }
                        }
                        catch (Exception ex)
                        {
                            error = MessageResource.GetMessage("api_error");
                        }

                        Int32 status = 0;
                        try
                        {
                            status = Int32.Parse(hashData.GetValue("status"));
                        }
                        catch { }

                        html += "<select id=\"filter_status\" name=\"filter_status\" >";

                        foreach (IAM.Workflow.WorkflowRequestStatus st in (IAM.Workflow.WorkflowRequestStatus[])Enum.GetValues(typeof(IAM.Workflow.WorkflowRequestStatus)))
                        {
                            html += "<option value=\"status/" + (Int32)st + "\" " + (status == (Int32)st ? "selected" : "") + ">" + MessageResource.GetMessage("wf_" + st.ToString().ToLower(), st.ToString()) + "</option>";
                        }

                        html += "</select>";

                        js += "$('#filter_status').change(function() { iamadmin.changeHash( $( this ).val() ); });";

                        contentRet    = new WebJsonResponse("#btnbox", html);
                        contentRet.js = js;

                        break;
                    }
                }
                break;
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }