示例#1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;

            Int64 userId = 0;

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

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

            String action = "";

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

            if ((userId == 0) && (action != "add_user"))
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                action     = "";
            }

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "add_user":

                    Int64 rpId = 0;
                    try
                    {
                        rpId = Int64.Parse((String)Request.Form["resource_plugin"]);

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


                    String[] fItems = (String.IsNullOrEmpty(Request.Form["field_id"]) ? new String[0] : Request.Form["field_id"].Split(",".ToCharArray()));
                    if (fItems.Length == 0)
                    {
                        contentRet = new WebJsonResponse("", "Nenhum campo mapeado", 3000, false);
                        break;
                    }


                    List <Dictionary <String, String> > properties = new List <Dictionary <String, String> >();

                    WebJsonResponse iError = null;
                    foreach (String sfId in fItems)
                    {
                        Int64 fId = 0;
                        try
                        {
                            fId = Int64.Parse(sfId);
                            String[] values = (String.IsNullOrEmpty(Request.Form[sfId]) ? new String[0] : Request.Form[sfId].Split(",".ToCharArray()));

                            foreach (String v in values)
                            {
                                if (!String.IsNullOrWhiteSpace(v))
                                {
                                    Dictionary <String, String> newItem = new Dictionary <string, string>();
                                    newItem.Add("field_id", fId.ToString());
                                    newItem.Add("value", v.Trim());

                                    properties.Add(newItem);
                                }
                            }
                        }
                        catch
                        {
                            iError = new WebJsonResponse("", "Campo '" + fId + "' inválido", 3000, false);
                            break;
                        }
                    }

                    if (iError != null)
                    {
                        contentRet = iError;
                        break;
                    }


                    if (properties.Count == 0)
                    {
                        contentRet = new WebJsonResponse("", "Nenhum campo mapeado", 3000, false);
                        break;
                    }

                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.new",
                        parameters = new
                        {
                            resourcepluginid = rpId,
                            properties       = properties
                        },
                        id = 1
                    });


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


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

                    GetResult retNew = JSON.Deserialize <GetResult>(jData);
                    if (retNew == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retNew.error != null)
                    {
                        contentRet = new WebJsonResponse("", retNew.error.data, 3000, true);
                    }
                    else if (retNew.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + retNew.result.info.userid + "/");
                    }
                    break;


                case "deploy":

                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.deploy",
                        parameters = new
                        {
                            userid = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqD);

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


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

                    Logs retD = JSON.Deserialize <Logs>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retD.error != null)
                    {
                        contentRet = new WebJsonResponse("", retD.error.data, 3000, true);
                    }
                    else if (retD.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Dados do usuário enviados para replicação", 3000, false);
                    }
                    break;

                case "change_container":

                    String containerId = Request.Form["container"];
                    if (String.IsNullOrEmpty(containerId))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_container"), 3000, true);
                        break;
                    }

                    var reqAdd = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.changecontainer",
                        parameters = new
                        {
                            containerid = containerId,
                            userid      = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqAdd);

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

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

                    BooleanResult retCCont = JSON.Deserialize <BooleanResult>(jData);
                    if (retCCont == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retCCont.error != null)
                    {
                        contentRet = new WebJsonResponse("", retCCont.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if (!retCCont.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + userId);
                    }

                    break;

                case "change_property":

                    List <Dictionary <String, String> > prop = new List <Dictionary <String, String> >();
                    String[] findex = (String.IsNullOrEmpty(Request.Form["field_index"]) ? new String[0] : Request.Form["field_index"].Split(",".ToCharArray()));
                    foreach (String sfId in findex)
                    {
                        if ((!String.IsNullOrEmpty(Request.Form["field_id_" + sfId])) && (!String.IsNullOrEmpty(Request.Form["field_value_" + sfId])))
                        {
                            Int64 fieldId = Int64.Parse(Request.Form["field_id_" + sfId]);

                            Dictionary <String, String> newItem = new Dictionary <string, string>();
                            newItem.Add("field_id", fieldId.ToString());
                            newItem.Add("value", Request.Form["field_value_" + sfId]);

                            prop.Add(newItem);
                        }
                    }

                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.changeproperty",
                        parameters = new
                        {
                            userid     = userId,
                            properties = prop
                        },
                        id = 1
                    });

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

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

                    GetResult retChange = JSON.Deserialize <GetResult>(jData);
                    if (retChange == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retChange.error != null)
                    {
                        contentRet = new WebJsonResponse("", retChange.error.data, 3000, true);
                    }
                    else if (retChange.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + retChange.result.info.userid + "/property/");
                    }
                    break;

                case "resetpwd":

                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.resetpassword",
                        parameters = new
                        {
                            userid      = userId,
                            must_change = true
                        },
                        id = 1
                    };

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

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

                    Logs ret = JSON.Deserialize <Logs>(jData);
                    if (ret == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (ret.error != null)
                    {
                        contentRet = new WebJsonResponse("", ret.error.data, 3000, true);
                    }
                    else if (ret.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Senha do usuário redefinida para o padrão do sistema", 3000, false);
                    }

                    break;

                case "lock":
                case "unlock":

                    var unReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user." + (action == "lock" ? "lock" : "unlock"),
                        parameters = new
                        {
                            userid = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(unReq);

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

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

                    Logs unRet = JSON.Deserialize <Logs>(jData);
                    if (unRet == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (unRet.error != null)
                    {
                        contentRet = new WebJsonResponse("", unRet.error.data, 3000, true);
                    }
                    else if (unRet.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Usuário " + (action == "lock" ? "Bloqueado" : "Desbloqueado") + " com sucesso", 5000, false);
                    }

                    break;

                case "delete_identity":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.deleteidentity",
                        parameters = new
                        {
                            userid     = userId,
                            identityid = (String)RouteData.Values["filter"]
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

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

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

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "unlock_identity":

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.unlockidentity",
                        parameters = new
                        {
                            userid     = userId,
                            identityid = (String)RouteData.Values["filter"]
                        },
                        id = 1
                    });

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

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

                    RoleDeleteResult retUnlockIdentity = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retUnlockIdentity == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_not_found"), 3000, true);
                    }
                    else if (retUnlockIdentity.error != null)
                    {
                        contentRet = new WebJsonResponse("", retUnlockIdentity.error.data, 3000, true);
                    }
                    else if (!retUnlockIdentity.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
示例#2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

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

            Int64 proxyId = 0;

            if (action != "add_proxy")
            {
                try
                {
                    proxyId = Int64.Parse((String)RouteData.Values["id"]);

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

                if (proxyId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    action     = "";
                }
            }

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "proxy.delete",
                        parameters = new
                        {
                            proxyid = proxyId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

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

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

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "restart":

                    var reqDst = new
                    {
                        jsonrpc    = "1.0",
                        method     = "proxy.restart",
                        parameters = new
                        {
                            proxyid = proxyId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDst);

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

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

                    RoleDeleteResult retRst = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retRst == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retRst.error != null)
                    {
                        contentRet = new WebJsonResponse("", retRst.error.data, 3000, true);
                    }
                    else if (!retRst.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "change_name":

                    String name = Request.Form["name"];
                    if (String.IsNullOrEmpty(name))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                        break;
                    }

                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "proxy.change",
                        parameters = new
                        {
                            proxyid = proxyId,
                            name    = name
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqD);

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

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

                    ProxyGetResult retD = JSON.Deserialize <ProxyGetResult>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    }
                    else if (retD.error != null)
                    {
                        contentRet = new WebJsonResponse("", retD.error.data, 3000, true);
                    }
                    else if (retD.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    }
                    else if (retD.result == null || retD.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("#proxy_name_" + proxyId, retD.result.info.name);
                    }
                    break;

                case "add_proxy":
                    String proxyName = Request.Form["proxy_name"];
                    if (String.IsNullOrEmpty(proxyName))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("type_proxy_name"), 3000, true);
                        break;
                    }

                    var reqAddR = new
                    {
                        jsonrpc    = "1.0",
                        method     = "proxy.new",
                        parameters = new
                        {
                            name = proxyName
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqAddR);

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

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

                    ProxyGetResult retAddR = JSON.Deserialize <ProxyGetResult>(jData);
                    if (retAddR == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    }
                    else if (retAddR.error != null)
                    {
                        contentRet = new WebJsonResponse("", retAddR.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if ((retAddR.result == null) || (retAddR.result.info == null))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("proxy_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/proxy/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }

                    //

                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
示例#3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

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

            Int64 pluginId = 0;

            if ((action != "add_plugin") && (action != "upload_item_template") && (action != "upload") && (action != "add_new"))
            {
                try
                {
                    pluginId = Int64.Parse((String)RouteData.Values["id"]);

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

                if (pluginId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    action     = "";
                }
            }

            Int64 enterpriseId = 0;

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

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "upload_item_template":

                    String id    = Request.Form["id"];
                    String file  = Request.Form["file"];
                    String tSize = Request.Form["size"];

                    if (String.IsNullOrEmpty(id))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (String.IsNullOrEmpty(file))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (String.IsNullOrEmpty(tSize))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        String userHtmlTemplate = "<div id=\"file{0}\" data-id=\"{0}\" data-name=\"{1}\" class=\"app-list-item file-item\">";
                        userHtmlTemplate += "<div class=\"form-content\"><input type=\"hidden\" name=\"file_name_{0}\" value=\"{1}\">";
                        userHtmlTemplate += "<input type=\"hidden\" name=\"{1}\" value=\"{0}\"></div>";
                        userHtmlTemplate += "<table>";
                        userHtmlTemplate += "   <tbody>";
                        userHtmlTemplate += "       <tr>";
                        userHtmlTemplate += "           <td class=\"colfull\">";
                        userHtmlTemplate += "               <div class=\"title\"><span class=\"name\" id=\"file_name_{0}\" data-id=\"{0}\">{1}</span><div class=\"clear-block\"></div></div>";
                        userHtmlTemplate += "               <div class=\"description\">{2}</div></div>";
                        userHtmlTemplate += "               <div class=\"links small\">";
                        userHtmlTemplate += "                   <div class=\"last\"><div class=\"ico icon-close\" onclick=\"$('#file{0}').remove();\">Excluir plugin</div></a><div class=\"clear-block\"></div></div>";
                        userHtmlTemplate += "               </div>";
                        userHtmlTemplate += "           </td>";
                        userHtmlTemplate += "       </tr>";
                        userHtmlTemplate += "   </tbody>";
                        userHtmlTemplate += "</table></div>";

                        String infoTemplate = "<div class=\"line\">";
                        infoTemplate += "<label>{1}</label>";
                        infoTemplate += "<span class=\"no-edit {0}\">{2}</span></div>";

                        String desc = "";

                        desc += String.Format(infoTemplate, "status", "Status", "Enviando");

                        String tHtml = String.Format(userHtmlTemplate, id, file, desc);

                        contentRet = new WebJsonResponse("#" + id, tHtml);
                    }

                    break;

                case "upload":

                    MultipartFormDataParser mp  = new MultipartFormDataParser(Request.InputStream);
                    List <String>           fls = new List <String>();


                    String infoTemplate2 = "<div class=\"line\">";
                    infoTemplate2 += "<label>{1}</label>";
                    infoTemplate2 += "<span class=\"no-edit {0}\">{2}</span></div>";


                    // Loop through all the files
                    foreach (FilePart mpF in mp.Files)
                    {
                        try
                        {
                            String d = "";

                            DirectoryInfo pluginsDir = null;

                            try
                            {
                                using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                                    pluginsDir = new DirectoryInfo(Path.Combine(c.GetItem("pluginFolder"), "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id));

                                if (!pluginsDir.Exists)
                                {
                                    pluginsDir.Create();
                                }
                            }
                            catch {
                                pluginsDir = null;
                            }

                            if (pluginsDir == null)
                            {
                                d += String.Format(infoTemplate2, "", "Status", "Diretório de plugins não encontrado");
                            }
                            else
                            {
                                try
                                {
                                    if (!pluginsDir.Exists)
                                    {
                                        pluginsDir.Create();
                                    }

                                    Byte[] rawAssembly = new Byte[mpF.Data.Length];
                                    mpF.Data.Read(rawAssembly, 0, rawAssembly.Length);

                                    List <String> p2    = new List <String>();
                                    List <String> p2Uri = new List <String>();
                                    try
                                    {
                                        //Realiza teste de compatibilidade com os plugins
                                        List <PluginBase> p1 = Plugins.GetPlugins <PluginBase>(rawAssembly);
                                        if (p1.Count > 0)
                                        {
                                            d += String.Format(infoTemplate2, "", "Status", "Arquivo válido");
                                        }
                                        else
                                        {
                                            d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido");
                                        }

                                        foreach (PluginBase p in p1)
                                        {
                                            p2.Add(p.GetPluginName());
                                            p2Uri.Add(p.GetPluginId().AbsoluteUri);
                                        }
                                    }
                                    catch
                                    {
                                        d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido");
                                    }

                                    d += String.Format(infoTemplate2, "", "Nome", mpF.FileName);
                                    d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes");
                                    if (p2.Count > 0)
                                    {
                                        d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2));
                                    }
                                    else
                                    {
                                        d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado");
                                    }

                                    if (p2.Count > 0)
                                    {
                                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        {
                                            DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))");

                                            if (dt.Rows.Count > 0)
                                            {
                                                throw new Exception("Plugin/uri ja cadastrado no sistema");
                                            }
                                        }

                                        FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName));
                                        if (newFile.Exists)
                                        {
                                            newFile.Delete();
                                        }
                                        File.WriteAllBytes(newFile.FullName, rawAssembly);
                                    }
                                }
                                catch (Exception ex) {
                                    d  = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload");
                                    d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message);
                                }
                            }

                            fls.Add(JSON.Serialize2(new { name = mpF.FileName, html = d }));
                        }
                        catch {
                            fls.Add(JSON.Serialize2(new { name = mpF.FileName, error = "Erro enviando o arquivo" }));
                        }
                    }

                    Retorno.Controls.Add(new LiteralControl("{\"files\": [" + String.Join(",", fls) + "]}"));
                    contentRet = null;

                    break;

                case "add_new":
                    Dictionary <String, String> files = new Dictionary <string, string>();
                    foreach (String key in Request.Form.Keys)
                    {
                        if ((key != null) && (key.ToLower().IndexOf("file_name") == 0))
                        {
                            if (!files.ContainsKey(Request.Form[key].ToLower()))
                            {
                                files.Add(Request.Form[key].ToLower(), Request.Form[Request.Form[key]]);
                            }
                        }
                    }

                    if (files.Count == 0)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                        break;
                    }

                    DirectoryInfo pluginsBase = null;
                    DirectoryInfo pluginsTemp = null;
                    try
                    {
                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            pluginsBase = new DirectoryInfo(c.GetItem("pluginFolder"));

                        pluginsTemp = new DirectoryInfo(Path.Combine(pluginsBase.FullName, "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id));

                        if (!pluginsTemp.Exists)
                        {
                            pluginsTemp.Create();
                        }
                    }
                    catch
                    {
                        pluginsTemp = null;
                    }

                    if (pluginsTemp == null)
                    {
                        contentRet = new WebJsonResponse("", "Diretório de plugins não encontrado", 3000, true);
                        break;
                    }

                    List <WebJsonResponse> multRet = new List <WebJsonResponse>();

                    String infoTemplate3 = "<div class=\"line {0}\">";
                    infoTemplate3 += "<label>{1}</label>";
                    infoTemplate3 += "<span class=\"no-edit\">{2}</span></div>";

                    Boolean hasError = false;
                    foreach (String f in files.Keys)
                    {
                        try
                        {
                            FileInfo assemblyFile = new FileInfo(Path.Combine(pluginsTemp.FullName, f));

                            if (!assemblyFile.Exists)
                            {
                                throw new Exception("Arquivo temporário não encontrado, refaça o upload");
                            }

                            Byte[]            rawAssembly = File.ReadAllBytes(assemblyFile.FullName);
                            List <PluginBase> p1          = Plugins.GetPlugins <PluginBase>(rawAssembly);
                            if (p1.Count == 0)
                            {
                                throw new Exception("Arquivo de plugin inválido");
                            }

                            foreach (PluginBase p in p1)
                            {
                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                {
                                    DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly = '" + p.GetPluginName() + "' or uri = '" + p.GetPluginId().AbsoluteUri + "')", null);

                                    if (dt.Rows.Count > 0)
                                    {
                                        throw new Exception("Plugin/uri ja cadastrado no sistema");
                                    }
                                }

                                FileInfo newF = new FileInfo(Path.Combine(pluginsBase.FullName, enterpriseId + "-" + assemblyFile.Name));
                                try
                                {
                                    assemblyFile.CopyTo(newF.FullName);

                                    DbParameterCollection par = new DbParameterCollection();
                                    par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                                    par.Add("@name", typeof(String)).Value         = p.GetPluginName();
                                    par.Add("@scheme", typeof(String)).Value       = p.GetPluginId().Scheme;
                                    par.Add("@uri", typeof(String)).Value          = p.GetPluginId().AbsoluteUri;
                                    par.Add("@assembly", typeof(String)).Value     = newF.Name;

                                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        database.ExecuteNonQuery("INSERT INTO plugin ([enterprise_id],[name],[scheme],[uri],[assembly],[create_date]) VALUES(@enterprise_id, @name, @scheme, @uri, @assembly, getdate())", CommandType.Text, par);

                                    try
                                    {
                                        assemblyFile.Delete();
                                    }
                                    catch { }
                                }
                                catch (Exception ex) {
                                    try
                                    {
                                        newF.Delete();
                                    }
                                    catch { }



                                    throw ex;
                                }
                            }

                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "", "Status", "Plugin inserido com sucesso")));
                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .form-content", "<input type=\"hidden\" />"));
                        }
                        catch (Exception ex)
                        {
                            hasError = true;
                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "error", "Error", ex.Message)));
                        }
                    }

                    if (!hasError)
                    {
                        multRet.Clear();
                        multRet.Add(new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/plugin/"));
                    }

                    Retorno.Controls.Add(new LiteralControl(JSON.Serialize <List <WebJsonResponse> >(multRet)));
                    contentRet = null;

                    break;

                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "plugin.delete",
                        parameters = new
                        {
                            pluginid = pluginId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

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

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

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
示例#4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

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

            Int64 roleId = 0;

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

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

                if (roleId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    action     = "";
                }
            }

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.delete",
                        parameters = new
                        {
                            roleid = roleId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

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

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

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "delete_all_users":
                    var reqDelUsr = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.deleteallusers",
                        parameters = new
                        {
                            roleid = roleId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDelUsr);

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

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

                    RoleDeleteResult retDelUsr = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDelUsr == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retDelUsr.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDelUsr.error.data, 3000, true);
                    }
                    else if (!retDelUsr.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "delete_user":
                    var reqDelUsr2 = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.deleteuser",
                        parameters = new
                        {
                            roleid = roleId,
                            userid = (String)RouteData.Values["filter"]
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDelUsr2);

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

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

                    RoleDeleteResult retDelUsr2 = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDelUsr2 == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retDelUsr2.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDelUsr2.error.data, 3000, true);
                    }
                    else if (!retDelUsr2.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;


                case "change_name":

                    String name = Request.Form["name"];
                    if (String.IsNullOrEmpty(name))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                        break;
                    }

                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.change",
                        parameters = new
                        {
                            roleid = roleId,
                            name   = name
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqD);

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

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

                    RoleGetResult retD = JSON.Deserialize <RoleGetResult>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retD.error != null)
                    {
                        contentRet = new WebJsonResponse("", retD.error.data, 3000, true);
                    }
                    else if (retD.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retD.result == null || retD.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("#role_name_" + roleId, retD.result.info.name);
                    }
                    break;


                case "add_user":
                    String user_id = Request.Form["user_id"];
                    if (String.IsNullOrEmpty(user_id))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_username"), 3000, true);
                        break;
                    }


                    var reqAdd = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.adduser",
                        parameters = new
                        {
                            roleid = roleId,
                            userid = user_id
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqAdd);

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

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

                    RoleDeleteResult retAdd = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retAdd == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retAdd.error != null)
                    {
                        contentRet = new WebJsonResponse("", retAdd.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if (!retAdd.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }

                    //

                    break;


                case "add_role":
                    String roleName = Request.Form["add_role_name"];
                    if (String.IsNullOrEmpty(roleName))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("type_role_name"), 3000, true);
                        break;
                    }

                    String context_id = Request.Form["add_role_context"];
                    if (String.IsNullOrEmpty(context_id))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_context"), 3000, true);
                        break;
                    }

                    var reqAddR = new
                    {
                        jsonrpc    = "1.0",
                        method     = "role.new",
                        parameters = new
                        {
                            name      = roleName,
                            contextid = context_id,
                            parentid  = 0
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqAddR);

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

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

                    RoleGetResult retAddR = JSON.Deserialize <RoleGetResult>(jData);
                    if (retAddR == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (retAddR.error != null)
                    {
                        contentRet = new WebJsonResponse("", retAddR.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if ((retAddR.result == null) || (retAddR.result.info == null))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/roles/" + retAddR.result.info.role_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }

                    //

                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

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

            Int64 contextId = 0;

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

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

                if (contextId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    action     = "";
                }
            }

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.delete",
                        parameters = new
                        {
                            contextid = contextId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

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

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

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "change_name":

                    String name = Request.Form["name"];
                    if (String.IsNullOrEmpty(name))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                        break;
                    }

                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.change",
                        parameters = new
                        {
                            contextid = contextId,
                            name      = name
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqD);

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

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

                    RoleGetResult retD = JSON.Deserialize <RoleGetResult>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (retD.error != null)
                    {
                        contentRet = new WebJsonResponse("", retD.error.data, 3000, true);
                    }
                    else if (retD.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (retD.result == null || retD.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("#context_name_" + contextId, retD.result.info.name);
                    }
                    break;


                case "change_login_rules":

                    List <loginRule> items = new List <loginRule>();

                    //rule_R1410734460301_group
                    String[] rIds = Request.Form["rule_id"].Split(",".ToCharArray());
                    foreach (String rid in rIds)
                    {
                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_group"]))
                        {
                            contentRet = new WebJsonResponse("", "Grupo não localizado na condição " + rid, 3000, true);
                            break;
                        }

                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_field"]))
                        {
                            contentRet = new WebJsonResponse("", "Campo não localizado na condição " + rid, 3000, true);
                            break;
                        }

                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_order"]))
                        {
                            contentRet = new WebJsonResponse("", "Ordem do campo não localizado na condição " + rid, 3000, true);
                            break;
                        }


                        loginRule newItem = new loginRule();
                        newItem.group = Request.Form["rule_" + rid + "_group"].Split(",".ToCharArray())[0];
                        newItem.order = Int32.Parse(Request.Form["rule_" + rid + "_order"].Split(",".ToCharArray())[0]);

                        try
                        {
                            switch (Request.Form["rule_" + rid + "_field"].Split(",".ToCharArray())[0].ToLower())
                            {
                            case "first_name":
                            case "second_name":
                            case "last_name":
                            case "char_first_name":
                            case "char_second_name":
                            case "char_last_name":
                            case "index":
                            case "dot":
                            case "hyphen":
                                newItem.field = Request.Form["rule_" + rid + "_field"].Split(",".ToCharArray())[0].ToLower();
                                break;

                            default:
                                throw new Exception("");
                                break;
                            }
                        }
                        catch
                        {
                            contentRet = new WebJsonResponse("", "ID do campo inválido na condição " + rid, 3000, true);
                            break;
                        }


                        items.Add(newItem);
                    }

                    //Ordena os ítems
                    items.Sort(delegate(loginRule r1, loginRule r2) { return(r1.order.CompareTo(r2.order)); });

                    List <loginRule> finalRules = new List <loginRule>();
                    foreach (loginRule li in items)
                    {
                        loginRule gi = finalRules.Find(g => (g.group == li.group));
                        if (gi == null)
                        {
                            finalRules.Add(li);
                        }
                        else
                        {
                            gi.field += "," + li.field;
                        }
                    }

                    finalRules.Sort(delegate(loginRule r1, loginRule r2) { return(r1.order.CompareTo(r2.order)); });

                    for (Int32 i = 0; i < finalRules.Count; i++)
                    {
                        finalRules[i].order = i;
                    }

                    List <Dictionary <String, Object> > sItems = new List <Dictionary <string, object> >();
                    foreach (loginRule li in finalRules)
                    {
                        Dictionary <String, Object> ni = new Dictionary <string, object>();
                        ni.Add("name", li.field);
                        ni.Add("rule", li.field);
                        ni.Add("order", li.order);

                        sItems.Add(ni);
                    }

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.changeloginrules",
                        parameters = new
                        {
                            contextid = contextId,
                            rules     = sItems
                        },
                        id = 1
                    });

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

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

                    BooleanResult retCL = JSON.Deserialize <BooleanResult>(jData);
                    if (retCL == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (retCL.error != null)
                    {
                        contentRet = new WebJsonResponse("", retCL.error.data, 3000, true);
                    }
                    else if (!retCL.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }
                    break;

                case "change_mail_rules":

                    List <loginRule> mItems = new List <loginRule>();

                    //rule_R1410734460301_group
                    String[] mrIds = Request.Form["rule_id"].Split(",".ToCharArray());
                    foreach (String rid in mrIds)
                    {
                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_group"]))
                        {
                            contentRet = new WebJsonResponse("", "Grupo não localizado na condição " + rid, 3000, true);
                            break;
                        }

                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_field"]))
                        {
                            contentRet = new WebJsonResponse("", "Campo não localizado na condição " + rid, 3000, true);
                            break;
                        }

                        if (String.IsNullOrEmpty(Request.Form["rule_" + rid + "_order"]))
                        {
                            contentRet = new WebJsonResponse("", "Ordem do campo não localizado na condição " + rid, 3000, true);
                            break;
                        }


                        loginRule newItem = new loginRule();
                        newItem.group = Request.Form["rule_" + rid + "_group"].Split(",".ToCharArray())[0];
                        newItem.order = Int32.Parse(Request.Form["rule_" + rid + "_order"].Split(",".ToCharArray())[0]);

                        try
                        {
                            switch (Request.Form["rule_" + rid + "_field"].Split(",".ToCharArray())[0].ToLower())
                            {
                            case "first_name":
                            case "second_name":
                            case "last_name":
                            case "char_first_name":
                            case "char_second_name":
                            case "char_last_name":
                            case "index":
                            case "dot":
                            case "hyphen":
                                newItem.field = Request.Form["rule_" + rid + "_field"].Split(",".ToCharArray())[0].ToLower();
                                break;

                            default:
                                throw new Exception("");
                                break;
                            }
                        }
                        catch
                        {
                            contentRet = new WebJsonResponse("", "ID do campo inválido na condição " + rid, 3000, true);
                            break;
                        }


                        mItems.Add(newItem);
                    }

                    //Ordena os ítems
                    mItems.Sort(delegate(loginRule r1, loginRule r2) { return(r1.order.CompareTo(r2.order)); });

                    List <loginRule> mFinalRules = new List <loginRule>();
                    foreach (loginRule li in mItems)
                    {
                        loginRule gi = mFinalRules.Find(g => (g.group == li.group));
                        if (gi == null)
                        {
                            mFinalRules.Add(li);
                        }
                        else
                        {
                            gi.field += "," + li.field;
                        }
                    }

                    mFinalRules.Sort(delegate(loginRule r1, loginRule r2) { return(r1.order.CompareTo(r2.order)); });

                    for (Int32 i = 0; i < mFinalRules.Count; i++)
                    {
                        mFinalRules[i].order = i;
                    }

                    List <Dictionary <String, Object> > msItems = new List <Dictionary <string, object> >();
                    foreach (loginRule li in mFinalRules)
                    {
                        Dictionary <String, Object> ni = new Dictionary <string, object>();
                        ni.Add("name", li.field);
                        ni.Add("rule", li.field);
                        ni.Add("order", li.order);

                        msItems.Add(ni);
                    }

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "context.changemailrules",
                        parameters = new
                        {
                            contextid = contextId,
                            rules     = msItems
                        },
                        id = 1
                    });

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

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

                    BooleanResult mRetCL = JSON.Deserialize <BooleanResult>(jData);
                    if (mRetCL == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (mRetCL.error != null)
                    {
                        contentRet = new WebJsonResponse("", mRetCL.error.data, 3000, true);
                    }
                    else if (!mRetCL.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }
                    break;


                case "add_context":
                case "change":

                    Boolean change = false;
                    if (action == "change")
                    {
                        change = true;
                    }

                    String contextName = Request.Form["add_context_name"];
                    if (String.IsNullOrEmpty(contextName))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("type_context_name"), 3000, true);
                        break;
                    }

                    String passwordRule = Request.Form["pwd_rule"];
                    if (String.IsNullOrEmpty(passwordRule))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("type_pwd_rule"), 3000, true);
                        break;
                    }

                    String pwd_length = Request.Form["pwd_length"];
                    if (String.IsNullOrEmpty(pwd_length))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("pwd_len_size"), 3000, true);
                        break;
                    }

                    try
                    {
                        Int32 tmp = Int32.Parse(Request.Form["pwd_length"]);
                        if ((tmp < 4) || (tmp > 20))
                        {
                            contentRet = new WebJsonResponse("", MessageResource.GetMessage("pwd_len_size"), 3000, true);
                            break;
                        }
                    }
                    catch {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("pwd_len_size"), 3000, true);
                        break;
                    }

                    if (!change)
                    {
                        var reqAddR = new
                        {
                            jsonrpc    = "1.0",
                            method     = "context.new",
                            parameters = new
                            {
                                name                = contextName,
                                parentid            = 0,
                                password_rule       = passwordRule,
                                password_length     = pwd_length,
                                password_upper_case = (!String.IsNullOrEmpty(Request.Form["pwd_upper_case"]) ? true : false),
                                password_lower_case = (!String.IsNullOrEmpty(Request.Form["pwd_lower_case"]) ? true : false),
                                password_digit      = (!String.IsNullOrEmpty(Request.Form["pwd_digit"]) ? true : false),
                                password_symbol     = (!String.IsNullOrEmpty(Request.Form["pwd_symbol"]) ? true : false),
                                password_no_name    = (!String.IsNullOrEmpty(Request.Form["pwd_no_name"]) ? true : false)
                            },
                            id = 1
                        };

                        rData = JSON.Serialize2(reqAddR);
                    }
                    else
                    {
                        var reqAddR = new
                        {
                            jsonrpc    = "1.0",
                            method     = "context.change",
                            parameters = new
                            {
                                contextid           = contextId,
                                name                = contextName,
                                parentid            = 0,
                                password_rule       = passwordRule,
                                password_length     = pwd_length,
                                password_upper_case = (!String.IsNullOrEmpty(Request.Form["pwd_upper_case"]) ? true : false),
                                password_lower_case = (!String.IsNullOrEmpty(Request.Form["pwd_lower_case"]) ? true : false),
                                password_digit      = (!String.IsNullOrEmpty(Request.Form["pwd_digit"]) ? true : false),
                                password_symbol     = (!String.IsNullOrEmpty(Request.Form["pwd_symbol"]) ? true : false),
                                password_no_name    = (!String.IsNullOrEmpty(Request.Form["pwd_no_name"]) ? true : false)
                            },
                            id = 1
                        };

                        rData = JSON.Serialize2(reqAddR);
                    }

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

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

                    ContextGetResult retAddR = JSON.Deserialize <ContextGetResult>(jData);
                    if (retAddR == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else if (retAddR.error != null)
                    {
                        contentRet = new WebJsonResponse("", retAddR.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if ((retAddR.result == null) || (retAddR.result.info == null))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("context_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/context/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


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