public HashData(HashData from)
 {
     SourceExecutable = from.SourceExecutable;
     ModdedExecutable = from.ModdedExecutable;
     SourceLibrary = from.SourceLibrary;
     ModdedLibrary = from.ModdedLibrary;
 }
Ejemplo n.º 2
0
        public string CalculateTransactionHash()
        {
            string txnHash = ClaimNumber + SettlementAmount + SettlementDate + CarRegistration + Mileage + ClaimType;

            return(Convert.ToBase64String(HashData.ComputeHashSha256(Encoding.UTF8.GetBytes(txnHash))));
        }
 public ModEnvironmentConfiguration(ModEnvironmentConfiguration from)
 {
     mHashes = new HashData(from.Hashes);
     ModReferences = from.ModReferences;
     ClearLogsOnRebuild = from.ClearLogsOnRebuild;
     GraphicsProfile = from.GraphicsProfile;
 }
Ejemplo n.º 4
0
 private Checksum(HashData hash)
 {
     _checksum = hash;
 }
Ejemplo n.º 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()));
            }
        }
Ejemplo n.º 6
0
 public string ExportPublicAddress()
 {
     return(HashData.ComputeHashSha256Base64String(ExportPublicKey()));
 }
Ejemplo n.º 7
0
 public static Checksum ReadFrom(ObjectReader reader)
 => new Checksum(HashData.ReadFrom(reader));
Ejemplo n.º 8
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"];
            }

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


            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Logs", ApplicationVirtualPath + "admin/logs/");
            LMenu menu3 = new LMenu("Logs de sistema", ApplicationVirtualPath + "admin/logs/");

            WebJsonResponse contentRet = null;

            String   html     = "";
            String   eHtml    = "";
            HashData hashData = new HashData(this);

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

            //Verifica se está selecionado o usuário

            Int64 userId = 0;

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

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

            switch (area)
            {
            case "":
            case "search":
            case "content":

                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 class=\"sorter\"><thead>";
                    html += "    <tr>";
                    html += "        <th class=\"w50 tHide mHide {sorter: false}\"></th>";
                    html += "        <th class=\"pointer w150 tHide mHide header headerSortDown\" data-column=\"date\">Data <div class=\"icomoon\"></div></th>";
                    html += "        <th class=\"pointer w80 tHide mHide header\" data-column=\"source\">Fonte <div class=\"icomoon\"></div></th>";
                    html += "        <th class=\"pointer w100 tHide mHide header\" data-column=\"resource\">Recurso <div class=\"icomoon\"></div></th>";
                    html += "        <th class=\"{sorter: false} header\" data-column=\"text\">Texto <div class=\"icomoon\"></div></th>";
                    html += "    </tr>";
                    html += "</thead>";

                    html += "<tbody>";
                }

                String trTemplate = "    <tr class=\"system-log\" data-uri=\"/admin/logs/{0}/content/modal/\" data-title=\"{5}\" onclick=\"iamadmin.openLog(this);\">";
                trTemplate += "            <td class=\"select tHide mHide\"><div class=\"level-icon level-{1}\"></div></td>";
                trTemplate += "            <td class=\"tHide mHide\">{2}</td>";
                trTemplate += "            <td class=\"tHide mHide\">{3}</td>";
                trTemplate += "            <td class=\"tHide mHide\">{4}</td>";
                trTemplate += "            <td class=\"ident10\">{5}</td>";
                trTemplate += "    </tr>";

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


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

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

                        rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                    }
                    else
                    {
                        var tmpReq = new
                        {
                            jsonrpc    = "1.0",
                            method     = "logs.search",
                            parameters = new
                            {
                                text      = query,
                                page_size = pageSize,
                                page      = page,
                                filter    = new { source = hashData.GetValue("source") }
                            },
                            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("");
                    }

                    SystemLogs ret2 = JSON.Deserialize <SystemLogs>(jData);
                    if (ret2 == null)
                    {
                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("log_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)
                    {
                        eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("log_not_found"));
                        hasNext = false;
                    }
                    else
                    {
                        foreach (LogItem l in ret2.result)
                        {
                            html += String.Format(trTemplate, l.log_id, l.level.ToString().ToLower(), ((DateTime) new DateTime(1970, 1, 1)).AddSeconds(l.date).ToString("yyyy-MM-dd HH:mm:ss"), l.source, l.resource_name, l.text);
                        }

                        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 system-logs-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.systemLogLoader');";

                if (hasNext)
                {
                    contentRet.js += "$( document ).bind( 'end_of_scroll.systemLogLoader', function() { $( document ).unbind('end_of_scroll.systemLogLoader'); $('.system-logs-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.system-logs-loader').addClass('hide'); } ); });";
                }

                break;

            case "modal":

                String logId = "";
                try
                {
                    logId = (String)RouteData.Values["id"];
                }
                catch { }


                try
                {
                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "logs.get",
                        parameters = new
                        {
                            logid = logId
                        },
                        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("");
                    }

                    LogData retLog = JSON.Deserialize <LogData>(jData);
                    if (retLog == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("log_not_found"), 3000, true);
                    }
                    else if (retLog.error != null)
                    {
                        contentRet = new WebJsonResponse("", retLog.error.data, 3000, true);
                    }
                    else if (retLog.result == null || retLog.result.log_id == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("log_not_found"), 3000, true);
                    }
                    else
                    {
                        html  = "<div class=\"log-info\">";
                        html += "<div class=\"item\">Data:</div>";
                        html += "<div class=\"description\">" + MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(retLog.result.date), false) + "</div>";
                        html += "<div class=\"item\">Fonte:</div>";
                        html += "<div class=\"description\">" + retLog.result.source + "</div>";

                        if (!String.IsNullOrEmpty(retLog.result.resource_name))
                        {
                            html += "<div class=\"item\">Recurso:</div>";
                            html += "<div class=\"description\">" + retLog.result.resource_name + "</div>";
                        }

                        if (!String.IsNullOrEmpty(retLog.result.plugin_name))
                        {
                            html += "<div class=\"item\">Plugin:</div>";
                            html += "<div class=\"description\">" + retLog.result.plugin_name + "</div>";
                        }

                        html += "<div class=\"item\">Executado por:</div>";
                        html += "<div class=\"description\">" + retLog.result.executed_by_name + "</div>";
                        html += "<div class=\"item\">Texto:</div>";
                        html += "<div class=\"description\">" + retLog.result.text + "</div>";
                        html += "<div class=\"item\">Informações adicionais:</div>";
                        html += "<div class=\"description\">";
                        //verifica se é um dado Json para fazer o parse
                        try
                        {
                            html += JSON.Dump(retLog.result.additional_data, true);
                        }
                        catch
                        {
                            html += HttpUtility.HtmlEncode(retLog.result.additional_data);
                        }
                        html      += "</div>";
                        html      += "</div>";
                        contentRet = new WebJsonResponse("#modal-box .alert-box-content", html);
                    }
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex, this);
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }

                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<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>";
                }

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

            case "mobilebar":
                break;


            case "buttonbox":

                html += "<select id=\"filter_source\" name=\"filter_source\" ><option value=\"\">Todas as origens</option>";
                html += "<option value=\"source/adminapi\" " + (hashData.GetValue("source") == "adminapi" ? "selected" : "") + ">adminapi</option>";
                html += "<option value=\"source/api\" " + (hashData.GetValue("source") == "api" ? "selected" : "") + ">api</option>";
                html += "<option value=\"source/autoservice\" " + (hashData.GetValue("source") == "autoservice" ? "selected" : "") + ">autoservice</option>";
                html += "<option value=\"source/cas\" " + (hashData.GetValue("source") == "cas" ? "selected" : "") + ">cas</option>";
                html += "<option value=\"source/deploy\" " + (hashData.GetValue("source") == "deploy" ? "selected" : "") + ">deploy</option>";
                html += "<option value=\"source/engine\" " + (hashData.GetValue("source") == "engine" ? "selected" : "") + ">engine</option>";
                html += "<option value=\"source/inbound\" " + (hashData.GetValue("source") == "inbound" ? "selected" : "") + ">inbound</option>";
                html += "<option value=\"source/proxy\" " + (hashData.GetValue("source") == "proxy" ? "selected" : "") + ">proxy</option>";
                html += "<option value=\"source/proxyapi\" " + (hashData.GetValue("source") == "proxyapi" ? "selected" : "") + ">proxyapi</option>";
                html += "</select>";

                contentRet    = new WebJsonResponse("#btnbox", html);
                contentRet.js = "$('#filter_source').change(function() { iamadmin.changeHash( $( this ).val() ); });";
                break;
            }

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

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Ejemplo n.º 9
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 = null;
            LMenu menu2 = null;
            LMenu menu3 = null;

            WebJsonResponse contentRet = null;
            HashData        hashData   = new HashData(this);

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



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

            switch (area)
            {
            case "":
            case "content":

                if (newItem)
                {
                    html += "<div id=\"upload-box\" class=\"upload-box\"><input type=\"file\" name=\"files[]\" multiple=\"\"><div class=\"drag-content\"><span class=\"upload-button-text\">Selecione arquivos para enviar</span><span class=\"upload-drag-drop-description\">Ou arraste e solte aqui</span></div><div class=\"dragDrop-content\"><span class=\"label l1\">Arraste a licença até aqui</span><span class=\"label l2\">Solte a licença</span></div></div>";

                    html += "<h3>Informações da licença</h3>";
                    html += "<form  id=\"form_plugin_add\"  method=\"POST\" action=\"" + ApplicationVirtualPath + "admin/license/action/add_new/\">";
                    html += "<div id=\"files\" class=\"box-container\"><div class=\"no-tabs pb10 none\">Nenhum upload realizado</div></div>";

                    html += "<button type=\"submit\" id=\"upload-save\" class=\"button secondary floatleft\">Aplicar licença</button>    <a href=\"" + ApplicationVirtualPath + "admin/license/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";
                    html += "</form>";

                    contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    contentRet.js = "iamadmin.licenseUploader($('#upload-box'), '" + ApplicationVirtualPath + "admin/license/action/upload/','" + ApplicationVirtualPath + "admin/license/action/upload_item_template/')";
                }
                else
                {
                    html += "<h3>" + MessageResource.GetMessage("licensing");

                    if (hashData.GetValue("edit") != "1")
                    {
                        html += "<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/license/new/'\">Carregar nova licença</div></div>";
                    }

                    html += "</h3>";

                    LicenseControl lic = null;

                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId);

                    //Carrega o certificado licenciado
                    if (lic != null)
                    {
                        html += "<div class=\"no-tabs fields\"><table><tbody>";

                        html += String.Format(infoTemplate, "Chave de instalação", lic.InstallationKey);
                        html += String.Format(infoTemplate, "Status da licença", (lic.Valid ? "Válida" : lic.Error));

                        html += "</tbody></table><div class=\"clear-block\"></div></div>";
                    }
                    else
                    {
                        eHtml += String.Format(errorTemplate, "Falha ao carregar a licença");
                    }
                    contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                }
                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<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>";
                }


                DbParameterCollection par = new DbParameterCollection();;
                par.Add("@enterpriseId", typeof(Int64)).Value = enterpriseId;

                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    DataTable dtUsers = db.ExecuteDataTable("sp_user_statistics", System.Data.CommandType.StoredProcedure, par);
                    if ((dtUsers != null) && (dtUsers.Rows.Count > 0))
                    {
                        Int64 total  = (Int64)dtUsers.Rows[0]["total"];
                        Int64 locked = (Int64)dtUsers.Rows[0]["locked"];
                        Int64 logged = (Int64)dtUsers.Rows[0]["logged"];

                        Int32 pLocked = 0;
                        Int32 pLogged = 0;

                        try
                        {
                            pLocked = (Int32)(((Double)locked / (Double)total) * 100F);
                        }
                        catch { }

                        try
                        {
                            pLogged = (Int32)(((Double)logged / (Double)total) * 100F);
                        }
                        catch { }

                        html += "<div class=\"ds1\">";
                        html += "<div class=\"center\">" + MessageResource.GetMessage("entity") + "</div>";
                        html += "<div class=\"center\"><span class=\"big\">" + total + "</span><span class=\"small\"> " + MessageResource.GetMessage("total") + "</span></div>";

                        html += "<div class=\"center\"><canvas id=\"usrLockChart\" width=\"30\" height=\"30\"></canvas><span class=\"big txt1\">" + locked + "<span> <span class=\"small\">" + MessageResource.GetMessage("locked") + "<span></div>";
                        html += "<div class=\"center\"><canvas id=\"usrLoggedChart\" width=\"30\" height=\"30\"></canvas><span class=\"big txt1\">" + logged + "<span> <span class=\"small\">" + MessageResource.GetMessage("logged") + "<span></div>";
                        //html += "<div class=\"center\"><canvas id=\"usrTotalChart\" width=\"30\" height=\"30\"></canvas><span class=\"big txt1\">" + total + "<span> <span class=\"small\">Total<span></div>";

                        html += "</div>";


                        //js += "iamadmin.buildPercentChart('#usrTotalChart',100,{color:'#2d88b4',showText:false});";
                        js += "iamadmin.buildPercentChart('#usrLockChart'," + pLocked + ",{color:'#f5663a',showText:false});";
                        js += "iamadmin.buildPercentChart('#usrLoggedChart'," + pLogged + ",{color:'#76c558',showText:false});";
                    }

                    html += "<div class=\"ds2\">";
                    html += "<div class=\"center\">" + MessageResource.GetMessage("licensing") + "</div>";


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

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

                        var tmpReq = new
                        {
                            jsonrpc    = "1.0",
                            method     = "license.info",
                            parameters = new String[0],
                            id         = 1
                        };

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

                        String jData = "";
                        try
                        {
                            jData = WebPageAPI.ExecuteLocal(db, this, rData);
                        }
                        finally
                        {
                        }

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

                        License ret2 = JSON.Deserialize <License>(jData);
                        if (ret2 == null)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }
                        else if (ret2.error != null)
                        {
                            eHtml += String.Format(errorTemplate, ret2.error.data);
                        }
                        else if (ret2.result == null)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }
                        else
                        {
                            Int32 percent = 0;
                            if (ret2.result.hasLicense)
                            {
                                if (ret2.result.available == 0)    //Licença ilimitada
                                {
                                    percent = 0;
                                }
                                else if (ret2.result.used > ret2.result.available)
                                {
                                    percent = 100;
                                }
                                else
                                {
                                    percent = (ret2.result.used / ret2.result.available) * 100;
                                }
                            }
                            else
                            {
                                percent = 100;
                            }


                            String color = "#76c558";
                            if (percent < 70)
                            {
                                color = "#76c558";
                            }
                            else if (percent < 85)
                            {
                                color = "#f5663a";
                            }
                            else
                            {
                                color = "rgb(202, 52, 56)";
                            }

                            js += "iamadmin.buildPercentChart('#licChart'," + percent + ",{color:'" + color + "',showText:true});";

                            html += "<canvas id=\"licChart\" width=\"100\" height=\"100\" class=\"big-center\"></canvas>";
                            if (ret2.result.hasLicense)
                            {
                                html += "<div class=\"center\">" + MessageResource.GetMessage("licensing_total") + "</div>";
                                html += "<div class=\"center\"><span class=\"big\">" + ret2.result.used + "</span><span class=\"small\"> " + MessageResource.GetMessage("of") + " " + (ret2.result.available == 0 ? MessageResource.GetMessage("unlimited") : ret2.result.available.ToString()) + "</span></div>";
                            }
                            else
                            {
                                html += "<div class=\"center\"><span class=\"big\">" + MessageResource.GetMessage("no_licecse") + "</span></div>";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                    }


                    html += "</div>";
                }

                contentRet    = new WebJsonResponse("#main aside", (eHtml != "" ? eHtml : html));
                contentRet.js = js;

                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()));
            }
        }
Ejemplo n.º 10
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("Plugins", ApplicationVirtualPath + "admin/plugin/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Plugins do sistema", ApplicationVirtualPath + "admin/plugin/" + (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 pluginId = 0;

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

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

            String          error     = "";
            PluginGetResult retPlugin = null;
            String          filter    = "";
            HashData        hashData  = new HashData(this);


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

            if ((pluginId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "plugin.get",
                        parameters = new
                        {
                            pluginid = pluginId
                        },
                        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("");
                    }

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

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    html += "<div id=\"upload-box\" class=\"upload-box\"><input type=\"file\" name=\"files[]\" multiple=\"\"><div class=\"drag-content\"><span class=\"upload-button-text\">Selecione arquivos para enviar</span><span class=\"upload-drag-drop-description\">Ou arraste e solte aqui</span></div><div class=\"dragDrop-content\"><span class=\"label l1\">Arraste o plugin até aqui</span><span class=\"label l2\">Solte o plugin</span></div></div>";

                    html += "<h3>Uploads</h3>";
                    html += "<form  id=\"form_plugin_add\"  method=\"POST\" action=\"" + ApplicationVirtualPath + "admin/plugin/action/add_new/\">";
                    html += "<div id=\"files\" class=\"box-container\"><div class=\"no-tabs pb10 none\">Nenhum upload realizado</div></div>";

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

                    contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                    contentRet.js = "iamadmin.pluginUploader($('#upload-box'), '" + ApplicationVirtualPath + "admin/plugin/action/upload/','" + ApplicationVirtualPath + "admin/plugin/action/upload_item_template/')";
                }
                else
                {
                    if (retPlugin == null)
                    {
                        Int32   page     = 1;
                        Int32   pageSize = 20;
                        Boolean hasNext  = true;

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

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

                        String pluginTemplate = "<div id=\"role-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        pluginTemplate += "<table>";
                        pluginTemplate += "   <tbody>";
                        pluginTemplate += "       <tr>";
                        pluginTemplate += "           <td class=\"col1\">";
                        pluginTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        pluginTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/resource_plugin/#plugin/{0}\">";
                        pluginTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver vínculos</span></div>";
                        pluginTemplate += "               </a>";
                        pluginTemplate += "           </td>";
                        pluginTemplate += "           <td class=\"col2\">";
                        pluginTemplate += "               <div class=\"title\"><span class=\"name field-editor\">{1}</span><span class=\"date\">{4}</span><div class=\"clear-block\"></div></div>";
                        pluginTemplate += "               <div class=\"links no-bg\">";
                        pluginTemplate += "                   <div class=\"first\">Uri: {3}<br clear=\"all\"></div>";
                        pluginTemplate += "                   <div class=\"\"><a href=\"" + ApplicationVirtualPath + "admin/plugin/{0}/flow/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-sitemap\">Fluxo de dados</div></a></div>";
                        pluginTemplate += "                   <div class=\"last\">{5}<br clear=\"all\"></div>";
                        pluginTemplate += "               </div><br clear=\"all\">";
                        pluginTemplate += "           </td>";
                        pluginTemplate += "       </tr>";
                        pluginTemplate += "   </tbody>";
                        pluginTemplate += "</table></div>";

                        html += "<div id=\"plugin-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     = "plugin.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }
                            else
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "plugin.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("");
                            }

                            PluginListResult ret2 = JSON.Deserialize <PluginListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("plugin_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("plugin_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (PluginData plugin in ret2.result)
                                {
                                    html += String.Format(pluginTemplate, plugin.plugin_id, plugin.name, plugin.resource_plugin_qty, plugin.uri, (plugin.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(plugin.create_date), true) : ""), (plugin.enterprise_id > 0 ? "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/plugin/" + plugin.plugin_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o plugin '" + plugin.uri + "'?\" 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 plugin-list-loader hide\"></span>";

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

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

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

                                String js2 = "";
                                if (filter == "" || filter == "flow")
                                {
                                    html += "<h3>Fluxo de dados</h3>";
                                    html += "<div id=\"pluginChart\"></div>";
                                    js2   = "$('#pluginChart').flowchart({load_uri: '" + ApplicationVirtualPath + "admin/chartdata/flow/plugin/" + retPlugin.result.info.plugin_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/plugin/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo plugin</button></div>";
                }

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

            case "mobilebar":
                break;


            case "buttonbox":

                switch (filter)
                {
                case "":


                    break;
                }
                break;
            }

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

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Ejemplo n.º 11
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()));
            }
        }
Ejemplo n.º 12
0
        public byte[] CalculateTransactionHash()
        {
            string txnHash = ID + Name + Type + Timestamp;

            return(HashData.ComputeHashSha256(Encoding.UTF8.GetBytes(txnHash)));
        }
Ejemplo n.º 13
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/system_roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Perfis do sistema", ApplicationVirtualPath + "admin/system_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>";
            String infoTemplate  = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";


            //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 = "";
            SystemRoleGetResult selectedRole = 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
                {
                    String rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "systemrole.get",
                        parameters = new
                        {
                            roleid      = roleId,
                            permissions = true
                        },
                        id = 1
                    });
                    IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString());
                    String      jData    = "";
                    try
                    {
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);
                    }
                    finally
                    {
                        if (database != null)
                        {
                            database.Dispose();
                        }
                    }

                    selectedRole = JSON.Deserialize <SystemRoleGetResult>(jData);
                    if (selectedRole == null)
                    {
                        error = MessageResource.GetMessage("system_role_not_found");
                    }
                    else if (selectedRole.error != null)
                    {
                        error        = selectedRole.error.data;
                        selectedRole = null;
                    }
                    else if (selectedRole.result == null || selectedRole.result.info == null)
                    {
                        error        = MessageResource.GetMessage("system_role_not_found");
                        selectedRole = null;
                    }
                    else
                    {
                        menu3.Name = selectedRole.result.info.name;
                        menu3.HRef = ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "");
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedRole = null;
                }
            }

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    html  = "<h3>Adição de perfil</h3>";
                    html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/action/add_role/\">";
                    html += "<div class=\"no-tabs fields\"><table><tbody>";
                    html += String.Format(infoTemplate, "Nome", "<input id=\"add_role_name\" name=\"add_role_name\" placeholder=\"Digite o nome do perfil\" type=\"text\">");
                    html += String.Format(infoTemplate, "Admin", "<input id=\"enterprise_admin\" name=\"enterprise_admin\" type=\"checkbox\"><span class=\"description\">Perfil com direitos em todas as operações desta empresa</span>");
                    html += "</select></div>";
                    html += "</tbody></table></div>";
                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button>    <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + (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 (selectedRole == 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/system_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=\"description\">Permissões atribuidas: {4}";
                        roleTemplate += "               </div>";
                        roleTemplate += "               <div class=\"links\">";
                        roleTemplate += "                   <div class=\"line\">";
                        roleTemplate += "                       <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>";
                        roleTemplate += "                       <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/permissions/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-checkmark\">Permissões</div></a>";
                        roleTemplate += "                       <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a>";
                        roleTemplate += "                       <a href=\"" + ApplicationVirtualPath + "admin/system_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>";
                        roleTemplate += "                       <a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/system_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>";
                        roleTemplate += "                   </div><div class=\"clear-block\"></div>";
                        roleTemplate += "               </div>";
                        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))
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "systemrole.list",
                                    parameters = new
                                    {
                                        page_size   = pageSize,
                                        page        = page,
                                        permissions = true
                                    },
                                    id = 1
                                });
                            }
                            else
                            {
                                rData = SafeTrend.Json.JSON.Serialize2(new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "systemrole.search",
                                    parameters = new
                                    {
                                        text        = query,
                                        page_size   = pageSize,
                                        page        = page,
                                        permissions = true
                                    },
                                    id = 1
                                });
                            }

                            IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString());
                            String      jData    = "";
                            try
                            {
                                jData = WebPageAPI.ExecuteLocal(database, this, rData);
                            }
                            finally
                            {
                                if (database != null)
                                {
                                    database.Dispose();
                                }
                            }

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

                            SystemRoleListResult ret2 = JSON.Deserialize <SystemRoleListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("system_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("system_role_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (SystemRoleData role in ret2.result)
                                {
                                    List <String> perm = new List <string>();

                                    if (!role.enterprise_admin && (role.permissions != null) && (role.permissions.Count > 0))
                                    {
                                        foreach (SystemRolePermission p in role.permissions)
                                        {
                                            perm.Add(p.module_name + "/" + p.sub_module_name + "/" + p.name);
                                        }
                                    }

                                    if (role.enterprise_admin)
                                    {
                                        perm.Add("Administração da empresa - todas as permissões");
                                    }

                                    if (perm.Count == 0)
                                    {
                                        perm.Add("Nenhuma permissão atribuida");
                                    }

                                    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) : ""), String.Join(", ", perm));
                                }

                                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 "":

                                html += "<h3>Configurações gerais";
                                if (hashData.GetValue("edit") != "1")
                                {
                                    html += "<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div>";
                                }
                                html += "</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/action/change_role/\">";
                                html += "<div class=\"no-tabs fields\"><table><tbody>";

                                if (hashData.GetValue("edit") == "1")
                                {
                                    html += String.Format(infoTemplate, "Nome", "<input id=\"name\" name=\"name\" placeholder=\"Digite o nome do perfil\" type=\"text\" value=\"" + selectedRole.result.info.name + "\">");
                                    html += String.Format(infoTemplate, "Admin", "<input id=\"enterprise_admin\" name=\"enterprise_admin\" type=\"checkbox\" " + (selectedRole.result.info.enterprise_admin ? "checked" : "") + "><span class=\"description\">Perfil com direitos em todas as operações desta empresa</span>");
                                }
                                else
                                {
                                    html += String.Format(infoTemplate, "Nome", selectedRole.result.info.name);
                                    html += String.Format(infoTemplate, "Admin", (selectedRole.result.info.enterprise_admin ? MessageResource.GetMessage("yes") : MessageResource.GetMessage("no")));
                                }

                                html += "</tbody></table></div>";

                                if (hashData.GetValue("edit") == "1")
                                {
                                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/\" class=\"button link floatleft\">Cancelar</a></form>";
                                }

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

                            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/system_roles/" + selectedRole.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 de sistema '" + selectedRole.result.info.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\">Excluir</button></td>";
                                trTemplate += "    </tr>";

                                try
                                {
                                    String rData = "";
                                    rData = SafeTrend.Json.JSON.Serialize2(new
                                    {
                                        jsonrpc    = "1.0",
                                        method     = "systemrole.users",
                                        parameters = new
                                        {
                                            page_size = pageSize,
                                            page      = page,
                                            roleid    = roleId
                                        },
                                        id = 1
                                    });


                                    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/system_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/system_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/', null , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )";

                                break;


                            case "permissions":

                                html += "<h3>Permissões";
                                if ((hashData.GetValue("edit") != "1") && (!selectedRole.result.info.enterprise_admin))
                                {
                                    html += "<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div>";
                                }
                                html += "</h3>";
                                html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/action/change_permissions/\">";
                                html += "<div class=\"no-tabs fields\"><table><tbody>";

                                String infoTemplate2 = "<tr><td class=\"colfull\">{0}</td></tr>";

                                if (selectedRole.result.info.enterprise_admin)
                                {
                                    html += String.Format(infoTemplate2, "<span style=\"text-align: center; width: 100%; display:block;\">Esto perfil tem permissão de administração total nesta empresa, desta forma não necessita configurar permissões específicas</span>");
                                }
                                else
                                {
                                    String rData = SafeTrend.Json.JSON.Serialize2(new
                                    {
                                        jsonrpc    = "1.0",
                                        method     = "systemrole.permissionstree",
                                        parameters = new { },
                                        id         = 1
                                    });

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


                                    SystemRolePermissionsTree retPTree = JSON.Deserialize <SystemRolePermissionsTree>(jData);
                                    if (retPTree == null)
                                    {
                                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("permissions_not_found"));
                                    }
                                    else if (retPTree.error != null)
                                    {
                                        eHtml += String.Format(errorTemplate, retPTree.error.data);
                                    }
                                    else if (retPTree.result == null)
                                    {
                                        eHtml += String.Format(errorTemplate, MessageResource.GetMessage("permissions_not_found"));
                                    }
                                    else
                                    {
                                        if (hashData.GetValue("edit") == "1")
                                        {
                                            String field = "";

                                            field += "<div id=\"tree\">";

                                            field += "<ul>";
                                            foreach (SystemRolePermissionModule module in retPTree.result)
                                            {
                                                if (module.submodules.Count > 0)
                                                {
                                                    field += "  <li class=\"" + (module.submodules.Count == 0 ? "no-chield" : "") + "\"><input type=\"checkbox\"><span>" + module.name + "</span>";
                                                    field += "      <ul>";
                                                    foreach (SystemRolePermissionSubModule subModule in module.submodules)
                                                    {
                                                        if (subModule.permissions.Count > 0)
                                                        {
                                                            field += "  <li class=\"" + (subModule.permissions.Count == 0 ? "no-chield" : "") + "\"><input type=\"checkbox\"><span>" + subModule.name + "</span>";
                                                            field += "      <ul>";

                                                            foreach (SystemRolePermissionItem permission in subModule.permissions)
                                                            {
                                                                field += "  <li class=\"no-chield\"><input type=\"checkbox\" name=\"permission_id\" value=\"" + permission.permission_id + "\" " + (selectedRole.result.info.permissions != null && selectedRole.result.info.permissions.Exists(p => (p.permission_id == permission.permission_id)) ? "checked" : "") + "><span>" + permission.name + "</span></li>";
                                                            }

                                                            field += "      </ul>";
                                                            field += "</li>";
                                                        }
                                                    }
                                                    field += "      </ul>";
                                                    field += "</li>";
                                                }
                                            }
                                            field += "</ul>";

                                            field += "</div>";

                                            html += String.Format(infoTemplate2, field);
                                            js    = "$('#tree').tree({ dnd: false  });";
                                        }
                                        else
                                        {
                                            foreach (SystemRolePermissionModule module in retPTree.result)
                                            {
                                                if (module.submodules.Count > 0)
                                                {
                                                    foreach (SystemRolePermissionSubModule subModule in module.submodules)
                                                    {
                                                        if (subModule.permissions.Count > 0)
                                                        {
                                                            List <String> per = new List <string>();

                                                            foreach (SystemRolePermissionItem permission in subModule.permissions)
                                                            {
                                                                if (selectedRole.result.info.permissions != null && selectedRole.result.info.permissions.Exists(p => (p.permission_id == permission.permission_id)))
                                                                {
                                                                    per.Add(permission.name);
                                                                }
                                                            }

                                                            if (per.Count == 0)
                                                            {
                                                                per.Add("Nenhuma permissão definida");
                                                            }

                                                            html += String.Format(infoTemplate, module.name + "/" + subModule.name, String.Join(", ", per));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                html += "</tbody></table></div>";

                                if (hashData.GetValue("edit") == "1")
                                {
                                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/permissions/\" class=\"button link floatleft\">Cancelar</a></form>";
                                }

                                contentRet    = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                                contentRet.js = js;
                                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\"><a href=\"" + menu3.HRef + "\">" + menu3.Name + "</a></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/system_roles/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo perfil</button></div>";

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

                        if (filter != "permissions")
                        {
                            html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/permissions/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Alterar permissões</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()));
            }
        }
Ejemplo n.º 14
0
 public bool TryGet(ulong guid, out HashData hashData)
 {
     return(_map.TryGetValue(guid, out hashData));
 }
Ejemplo n.º 15
0
        private void EnhanceRun(
            IEnumerable <string> analysisTargets,
            OptionallyEmittedData dataToInsert,
            OptionallyEmittedData dataToRemove,
            IEnumerable <string> invocationTokensToRedact,
            IEnumerable <string> invocationPropertiesToLog,
            string defaultFileEncoding = null,
            IDictionary <string, HashData> filePathToHashDataMap = null)
        {
            _run.Invocations ??= new List <Invocation>();
            if (defaultFileEncoding != null)
            {
                _run.DefaultEncoding = defaultFileEncoding;
            }

            Encoding encoding = SarifUtilities.GetEncodingFromName(_run.DefaultEncoding);

            if (analysisTargets != null)
            {
                _run.Artifacts ??= new List <Artifact>();

                foreach (string target in analysisTargets)
                {
                    Uri uri = new Uri(UriHelper.MakeValidUri(target), UriKind.RelativeOrAbsolute);

                    HashData hashData = null;
                    if (dataToInsert.HasFlag(OptionallyEmittedData.Hashes))
                    {
                        filePathToHashDataMap?.TryGetValue(target, out hashData);
                    }

                    var artifact = Artifact.Create(
                        new Uri(target, UriKind.RelativeOrAbsolute),
                        dataToInsert,
                        encoding,
                        hashData: hashData);

                    var fileLocation = new ArtifactLocation
                    {
                        Uri = uri
                    };

                    artifact.Location = fileLocation;

                    // This call will insert the file object into run.Files if not already present
                    artifact.Location.Index = _run.GetFileIndex(
                        artifact.Location,
                        addToFilesTableIfNotPresent: true,
                        dataToInsert: dataToInsert,
                        encoding: encoding,
                        hashData: hashData);
                }
            }

            var invocation = Invocation.Create(
                emitMachineEnvironment: dataToInsert.HasFlag(OptionallyEmittedData.EnvironmentVariables),
                emitTimestamps: !dataToRemove.HasFlag(OptionallyEmittedData.NondeterministicProperties),
                invocationPropertiesToLog);

            // TODO we should actually redact across the complete log file context
            // by a dedicated rewriting visitor or some other approach.

            if (invocationTokensToRedact != null)
            {
                invocation.CommandLine = Redact(invocation.CommandLine, invocationTokensToRedact);
                invocation.Machine     = Redact(invocation.Machine, invocationTokensToRedact);
                invocation.Account     = Redact(invocation.Account, invocationTokensToRedact);

                if (invocation.WorkingDirectory != null)
                {
                    invocation.WorkingDirectory.Uri = Redact(invocation.WorkingDirectory.Uri, invocationTokensToRedact);
                }

                if (invocation.EnvironmentVariables != null)
                {
                    string[] keys = invocation.EnvironmentVariables.Keys.ToArray();

                    foreach (string key in keys)
                    {
                        string value = invocation.EnvironmentVariables[key];
                        invocation.EnvironmentVariables[key] = Redact(value, invocationTokensToRedact);
                    }
                }
            }

            _run.Invocations.Add(invocation);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Generates the encrypted signature which is required for the <see cref="RequestEnvelope"/>.
        /// </summary>
        /// <returns>The encrypted <see cref="PlatformRequest"/>.</returns>
        internal async Task <PlatformRequest> GenerateSignatureAsync(RequestEnvelope requestEnvelope)
        {
            if (Configuration.Hasher == null)
            {
                throw new PokeHashException($"{nameof(Configuration.Hasher)} is not set, which is required to send valid calls to PokemonGo.");
            }

            var timestampSinceStart = TimestampSinceStartMs;
            var locationFixes       = BuildLocationFixes(requestEnvelope, timestampSinceStart);
            var locationFix         = locationFixes.Last();

            _session.Player.Coordinate.HorizontalAccuracy = locationFix.HorizontalAccuracy;
            _session.Player.Coordinate.VerticalAccuracy   = locationFix.VerticalAccuracy;
            _session.Player.Coordinate.Altitude           = locationFix.Altitude;

            requestEnvelope.Accuracy = _session.Player.Coordinate.Altitude; // _session.Player.Coordinate.HorizontalAccuracy;
            requestEnvelope.MsSinceLastLocationfix = timestampSinceStart - (long)locationFix.TimestampSnapshot;

            var signature = new Signature
            {
                TimestampSinceStart = (ulong)timestampSinceStart,
                Timestamp           = (ulong)TimeUtil.GetCurrentTimestampInMilliseconds(),
                SensorInfo          =
                {
                    new SensorInfo
                    {
                        TimestampSnapshot     = (ulong)(timestampSinceStart + _session.Random.Next(100, 250)),
                        LinearAccelerationX   = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationY   = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationZ   = -0.7 + _session.Random.NextDouble() * 1.4,
                        RotationRateX         = 0.7 * _session.Random.NextDouble(),
                        RotationRateY         = 0.8 * _session.Random.NextDouble(),
                        RotationRateZ         = 0.8 * _session.Random.NextDouble(),
                        AttitudePitch         = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeRoll          = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeYaw           = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityX              = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityY              = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityZ              = -1.0 + _session.Random.NextDouble() * 2.0,
                        MagneticFieldAccuracy = -1,
                        Status = 3
                    }
                },
                DeviceInfo     = _session.Device.DeviceInfo,
                LocationFix    = { locationFixes },
                ActivityStatus = new ActivityStatus
                {
                    Stationary = true
                }
            };

            // Hashing
            signature.SessionHash = _sessionHash;
            signature.Unknown25   = Configuration.Hasher.Unknown25;
            signature.Unknown27   = uk27IdGenerator.Next();

            var serializedTicket = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray();

            var locationBytes = BitConverter.GetBytes(_session.Player.Coordinate.Latitude).Reverse()
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Longitude).Reverse())
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Altitude).Reverse()).ToArray();

            var requestsBytes = requestEnvelope.Requests.Select(x => x.ToByteArray()).ToArray();

            HashData hashData = null;

            try
            {
                hashData = await Configuration.Hasher.GetHashDataAsync(requestEnvelope, signature, locationBytes, requestsBytes, serializedTicket);
            }
            catch (TimeoutException)
            {
                throw new PokeHashException("Hasher server might down - timeout out");
            }
            catch (PokeHashException ex1)
            {
                throw new PokeHashException(ex1.Message);
            }
            catch (SessionStateException ex1)
            {
                throw new SessionStateException(ex1.Message);
            }
            catch (Exception ex1)
            {
                throw new Exception(ex1.Message);
            }

            if (hashData == null)
            {
                throw new PokeHashException("Missed Hash Data");
            }

            signature.LocationHash1 = (int)hashData.LocationAuthHash;
            signature.LocationHash2 = (int)hashData.LocationHash;
            signature.RequestHash.AddRange(hashData.RequestHashes);

            var encryptedSignature = new PlatformRequest
            {
                Type           = PlatformRequestType.SendEncryptedSignature,
                RequestMessage = new SendEncryptedSignatureRequest
                {
                    EncryptedSignature = ByteString.CopyFrom(Configuration.Hasher.GetEncryptedSignature(signature.ToByteArray(), (uint)timestampSinceStart))
                }.ToByteString()
            };

            return(encryptedSignature);
        }
Ejemplo n.º 17
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()));
            }
        }
Ejemplo n.º 18
0
 private string GenerateHash(Transaction t, string pH)
 {
     return(HashData.Hash(t, pH));
 }