コード例 #1
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private List <Object> accessrequestlist(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            List <Object> result = new List <Object>();

            DbParameterCollection par = new DbParameterCollection();

            par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;

            Int32 page     = 1;
            Int32 pageSize = 10;

            if (parameters.ContainsKey("page"))
            {
                Int32.TryParse(parameters["page"].ToString(), out page);
            }

            if (parameters.ContainsKey("page_size"))
            {
                Int32.TryParse(parameters["page_size"].ToString(), out pageSize);
            }

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

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

            Int32 rStart = ((page - 1) * pageSize) + 1;
            Int32 rEnd   = rStart + (pageSize - 1);

            /*
             * select * from st_workflow_request r with(nolock)
             * inner join entity e  with(nolock) on e.id = r.entity_id
             * inner join context c  with(nolock) on c.id = e.context_id
             * */
            String sql = "";

            sql += "WITH result_set AS (";
            sql += "  SELECT ";
            sql += "    ROW_NUMBER() OVER (ORDER BY r.create_date) AS [row_number], r.*, e.context_id, c.enterprise_id, e.full_name, e.login";
            sql += "     from st_workflow_request r with(nolock)  ";
            sql += "     inner join entity e  with(nolock) on e.id = r.entity_id   ";
            sql += "     inner join context c  with(nolock) on c.id = e.context_id  ";
            sql += "     where (c.enterprise_id = @enterprise_id ";

            if ((parameters.ContainsKey("filter")) && (parameters["filter"] is Dictionary <String, Object>))
            {
                Dictionary <String, Object> filter = (Dictionary <String, Object>)parameters["filter"];
                foreach (String k in filter.Keys)
                {
                    switch (k.ToLower())
                    {
                    case "text":
                        if (!String.IsNullOrWhiteSpace(filter["text"].ToString()))
                        {
                            par.Add("@text", typeof(String)).Value = filter["text"].ToString();
                            sql += " and (e.full_name like '%'+@text+'%' or e.login like '%'+@text+'%' or r.description like '%'+@text+'%')";
                        }
                        break;

                    case "contextid":
                        if (!String.IsNullOrWhiteSpace(filter["contextid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["contextid"].ToString());
                                par.Add("@context_id", typeof(Int64)).Value = tmp;
                                sql += " and c.id = @context_id";
                            }
                            catch { }
                        }
                        break;

                    case "workflowid":
                        if (!String.IsNullOrWhiteSpace(filter["workflowid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["workflowid"].ToString());
                                par.Add("@workflow_id", typeof(Int64)).Value = tmp;
                                sql += " and r.workflow_id = @workflow_id";
                            }
                            catch { }
                        }
                        break;

                    case "status":
                        if (!String.IsNullOrWhiteSpace(filter["status"].ToString()))
                        {
                            try
                            {
                                WorkflowRequestStatus tmp = (WorkflowRequestStatus)Int32.Parse(filter["status"].ToString());
                                par.Add("@status", typeof(Int32)).Value = (Int32)tmp;
                                sql += " and r.status = @status";
                            }
                            catch { }
                        }
                        break;
                    }
                }
            }

            sql += "     )";
            sql += ") SELECT";
            sql += "  *";
            sql += " FROM";
            sql += "  result_set";
            sql += " WHERE";
            sql += "  [row_number] BETWEEN " + rStart + " AND " + rEnd;

            DataTable dtRequest = database.ExecuteDataTable(sql, CommandType.Text, par, null);

            if ((dtRequest != null) && (dtRequest.Rows.Count > 0))
            {
                foreach (DataRow dr1 in dtRequest.Rows)
                {
                    using (IAMRBAC rbac = new IAMRBAC())
                        if (!rbac.UserAdmin(database, Acl.EntityId, this._enterpriseId))
                        {
                            using (WorkflowRequest request = new WorkflowRequest((Int64)dr1["id"]))
                            {
                                WorkflowRequestProccess proc = request.GetInicialData(database);
                                if (!proc.Success)
                                {
                                    Error(ErrorType.InternalError, proc.Message, proc.Debug, null);
                                    return(null);
                                }

                                if (!database.ExecuteScalar <Boolean>("select case when COUNT(*) > 0 then CAST(1 as bit) else CAST(0 as bit) end from entity e with(nolock) where e.id = " + Acl.EntityId + " and (e.id in (" + request.Workflow.Owner + "," + request.Activity.ManualApproval.EntityApprover + ") or e.id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + request.Activity.ManualApproval.RoleApprover + "))", CommandType.Text, null))
                                {
                                    continue;
                                }
                            }
                        }

                    Dictionary <string, object> newItem = new Dictionary <string, object>();
                    newItem.Add("access_request_id", dr1["id"]);
                    newItem.Add("userid", dr1["entity_id"]);
                    newItem.Add("context_id", dr1["context_id"]);
                    newItem.Add("enterprise_id", dr1["enterprise_id"]);
                    newItem.Add("workflow_id", dr1["workflow_id"]);
                    newItem.Add("status", dr1["status"]);
                    newItem.Add("description", dr1["description"]);
                    newItem.Add("entity_full_name", dr1["full_name"]);
                    newItem.Add("entity_login", dr1["login"]);
                    newItem.Add("deployed", dr1["deployed"]);
                    newItem.Add("start_date", (dr1["start_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["start_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("end_date", (dr1["end_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["end_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));

                    WorkflowConfig wk = new WorkflowConfig();
                    wk.GetDatabaseData(database, (Int64)dr1["workflow_id"]);

                    newItem.Add("workflow", wk.ToJsonObject());

                    result.Add(newItem);
                }
            }

            return(result);
        }
コード例 #2
0
        public WorkflowRequestProccess GetInicialData(IAMDatabase database)
        {
            DbParameterCollection par = new DbParameterCollection();

            par.Add("@enterprise_id", typeof(Int64)).Value = this.enterprise_id;
            par.Add("@request_id", typeof(Int64)).Value    = this.workflow_request_id;

            DataTable dtWorkflowRequest = database.ExecuteDataTable("select r.*, e.full_name, e.id entity_id, e.login, w.name workflow_name, c.enterprise_id from st_workflow_request r with(nolock) inner join st_workflow w with(nolock) on w.id = r.workflow_id inner join entity e  with(nolock) on e.id = r.entity_id inner join context c  with(nolock) on c.id = e.context_id where r.id = @request_id", CommandType.Text, par, null);

            if ((dtWorkflowRequest == null) || (dtWorkflowRequest.Rows.Count == 0))
            {
                return(new WorkflowRequestProccess(false, "Access request not found"));
            }

            this.status        = (WorkflowRequestStatus)((Int32)dtWorkflowRequest.Rows[0]["status"]);
            this.enterprise_id = (Int64)dtWorkflowRequest.Rows[0]["enterprise_id"];

            this.user_name  = dtWorkflowRequest.Rows[0]["full_name"].ToString();
            this.user_login = dtWorkflowRequest.Rows[0]["login"].ToString();
            this.user_id    = (Int64)dtWorkflowRequest.Rows[0]["entity_id"];

            try
            {
                workflow = new WorkflowConfig();
                workflow.GetDatabaseData(database, (Int64)dtWorkflowRequest.Rows[0]["workflow_id"]);

                if (workflow == null)
                {
                    throw new Exception("");
                }
            }
            catch (Exception ex)
            {
                return(new WorkflowRequestProccess(false, "Fail on get workflow config", ex.Message));
            }

            if ((workflow.Activities == null) || (workflow.Activities.Count == 0))
            {
                return(new WorkflowRequestProccess(false, "Activity list is empty on workflow " + workflow.Name));
            }


            //Verifica o último status para chegar em que activity esta requisição está
            DataTable dtLogs = database.ExecuteDataTable("select * from st_workflow_request_status where workflow_request_id = @request_id order by date", CommandType.Text, par, null);

            if ((dtLogs == null) || (dtLogs.Rows.Count == 0))
            {
                return(new WorkflowRequestProccess(false, "Access request status list not found"));
            }

            //Resgata a maior activity
            try
            {
                List <Int64> actList = new List <Int64>();
                foreach (DataRow dr in dtLogs.Rows)
                {
                    if (!actList.Contains((Int64)dr["activity_id"]))
                    {
                        actList.Add((Int64)dr["activity_id"]);
                    }
                }


                //Ordena de forma descrecente
                workflow.Activities.Sort(delegate(WorkflowActivity a1, WorkflowActivity a2) { return(a2.ExeutionOrder.CompareTo(a1.ExeutionOrder)); });


                //Remove da lista todas as atividades ja aprovadas
                foreach (WorkflowActivity act in workflow.Activities)
                {
                    DateTime last            = new DateTime(1970, 1, 1);
                    WorkflowRequestStatus st = WorkflowRequestStatus.Waiting;

                    foreach (DataRow drSt in dtLogs.Rows)
                    {
                        if (drSt["activity_id"].ToString() == act.ActivityId.ToString())
                        {
                            if (last.CompareTo((DateTime)drSt["date"]) < 0)
                            {
                                last = (DateTime)drSt["date"];
                                st   = (WorkflowRequestStatus)((Int32)drSt["status"]);
                            }
                        }
                    }

                    if (st == WorkflowRequestStatus.Approved)
                    {
                        actList.Remove(act.ActivityId);
                    }
                }


                //Primeiro busca a menor atividade
                foreach (WorkflowActivity act in workflow.Activities)
                {
                    if (activity == null)//Como esta ordenado de forma decrescente, pegará a última atividade do array
                    {
                        activity = act;
                    }

                    if ((actList.Contains(act.ActivityId)) && (act.ExeutionOrder < activity.ExeutionOrder))
                    {
                        activity = act;
                    }
                }


                if (activity == null)
                {
                    throw new Exception("Activity is empty");
                }

                foreach (DataRow dr in dtLogs.Rows)
                {
                    if ((Int64)dr["activity_id"] == activity.ActivityId)
                    {
                        if (this.activity_created.Year == 1970)
                        {
                            this.activity_created = (DateTime)dr["date"];
                            this.last_executed_by = (Int64)dr["executed_by_entity_id"];
                        }

                        if (this.activity_created.CompareTo((DateTime)dr["date"]) < 0)
                        {
                            this.activity_created = (DateTime)dr["date"];
                            this.last_executed_by = (Int64)dr["executed_by_entity_id"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new WorkflowRequestProccess(false, "Error on proccess activities"));
            }

            //Verifica se essa é a última activity
            //Se sim irá realizar a ação final
            this.nextActivity = null;
            foreach (WorkflowActivity act in workflow.Activities)
            {
                if (act.ExeutionOrder > activity.ExeutionOrder)
                {
                    this.nextActivity = act;
                }
            }

            return(new WorkflowRequestProccess(true, ""));
        }
コード例 #3
0
        public WorkflowRequestProccess SetStatus(IAMDatabase database, WorkflowRequestStatus status, Int64 executing_user)
        {
            WorkflowRequestProccess initial = GetInicialData(database);

            if (!initial.Success)
            {
                return(initial);
            }

            //Verifica se o usuário atual faz parte do grupo de aprovadores
            if (!database.ExecuteScalar <Boolean>("select case when COUNT(*) > 0 then CAST(1 as bit) else CAST(0 as bit) end from entity e with(nolock) where e.id in (" + workflow.Owner + "," + activity.ManualApproval.EntityApprover + ") or e.id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + activity.ManualApproval.RoleApprover + ")", CommandType.Text, null))
            {
                return(new WorkflowRequestProccess(false, "Access denied. You are not part of the group of approvers users"));
            }

            Object trans = database.BeginTransaction();

            try
            {
                String changeTextAdmin = "";
                String changeText      = "";

                changeText = activity.Name + " " + MessageResource.GetMessage("wf_" + status.ToString().ToLower(), status.ToString());

                using (DbParameterCollection par2 = new DbParameterCollection())
                {
                    //Só altera o status do ítem ptincipal quando a aprovação for da última activity
                    if ((status == WorkflowRequestStatus.Approved) && (nextActivity == null))
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        par2.Add("@status", typeof(Int32)).Value     = (Int32)status;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET [status] = @status, deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }
                    else if (status == WorkflowRequestStatus.Approved)
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }
                    else
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        par2.Add("@status", typeof(Int32)).Value     = (Int32)status;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET [status] = @status, deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }

                    //Adiciona o status da activity atual
                    par2.Clear();
                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = this.workflow_request_id;
                    par2.Add("@status", typeof(String)).Value               = (Int32)status;
                    par2.Add("@description", typeof(String)).Value          = changeText;
                    par2.Add("@activity_id", typeof(Int64)).Value           = activity.ActivityId;
                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = executing_user;
                    par2.Add("@date", typeof(DateTime)).Value               = DateTime.Now;

                    database.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[date],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@date,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, trans);

                    //Adiciona o status da próxima atividade
                    if ((status == WorkflowRequestStatus.Approved) && (nextActivity != null))
                    {
                        par2.Clear();
                        par2.Add("@workflow_request_id", typeof(Int64)).Value   = this.workflow_request_id;
                        par2.Add("@status", typeof(String)).Value               = (Int32)WorkflowRequestStatus.Waiting;
                        par2.Add("@description", typeof(String)).Value          = "Aguardando análise";
                        par2.Add("@activity_id", typeof(Int64)).Value           = nextActivity.ActivityId;
                        par2.Add("@executed_by_entity_id", typeof(Int64)).Value = executing_user;
                        par2.Add("@date", typeof(DateTime)).Value               = DateTime.Now.AddSeconds(1);

                        database.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[date],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@date,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, trans);
                    }
                }


                //E-mails para os próximos aprovadores, se houver
                if ((status == WorkflowRequestStatus.Approved) && (nextActivity != null))
                {
                    try
                    {
                        Dictionary <Int64, List <String> > mails = new Dictionary <long, List <string> >();

                        if ((nextActivity.ManualApproval != null) && ((nextActivity.ManualApproval.EntityApprover > 0) || (nextActivity.ManualApproval.RoleApprover > 0)))
                        {
                            DataTable dtUserMails = database.ExecuteDataTable("select distinct entity_id, mail, full_name from vw_entity_mails where entity_id in (" + activity.ManualApproval.EntityApprover + ") or entity_id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + activity.ManualApproval.RoleApprover + ")", CommandType.Text, null, trans);
                            if ((dtUserMails != null) && (dtUserMails.Rows.Count > 0))
                            {
                                foreach (DataRow dr in dtUserMails.Rows)
                                {
                                    try
                                    {
                                        MailAddress m = new MailAddress(dr["mail"].ToString());

                                        if (!mails.ContainsKey((Int64)dr["entity_id"]))
                                        {
                                            mails.Add((Int64)dr["entity_id"], new List <string>());
                                        }

                                        mails[(Int64)dr["entity_id"]].Add(m.Address);
                                    }
                                    catch { }
                                }
                            }
                        }

                        if (mails.Count > 0)
                        {
                            foreach (Int64 admin_id in mails.Keys)
                            {
                                try
                                {
                                    Dictionary <String, String> vars = new Dictionary <string, string>();
                                    vars.Add("workflow_name", workflow.Name);
                                    vars.Add("user_name", this.user_name);
                                    vars.Add("user_login", this.user_login);
                                    vars.Add("user_id", this.user_id.ToString());
                                    vars.Add("admin_id", admin_id.ToString());
                                    vars.Add("description", workflow.Description);
                                    vars.Add("approval_link", "%enterprise_uri%/admin/access_request/" + this.workflow_request_id + "/allow/");
                                    vars.Add("deny_link", "%enterprise_uri%/admin/access_request/" + this.workflow_request_id + "/deny/");



                                    MessageBuilder msgAdm = MessageBuilder.BuildFromTemplate(database, this.enterprise_id, "access_request_admin", String.Join(",", mails[admin_id]), vars, trans);
                                    msgAdm.SaveToDb(database, trans);
                                }
                                catch { }
                            }
                        }
                    }
                    catch { }
                }

                try
                {
                    //E-mail para o usuário
                    DataTable dtUserMails = database.ExecuteDataTable("select distinct mail from vw_entity_mails where entity_id = " + this.user_id, CommandType.Text, null, trans);
                    if ((dtUserMails != null) && (dtUserMails.Rows.Count > 0))
                    {
                        List <String> mails = new List <string>();

                        foreach (DataRow dr in dtUserMails.Rows)
                        {
                            try
                            {
                                MailAddress m = new MailAddress(dr["mail"].ToString());
                                mails.Add(m.Address);
                            }
                            catch { }
                        }

                        if (mails.Count > 0)
                        {
                            Dictionary <String, String> vars = new Dictionary <string, string>();
                            vars.Add("workflow_name", this.workflow.Name);
                            vars.Add("user_name", this.user_name);
                            vars.Add("user_login", this.user_login);
                            vars.Add("user_id", this.user_id.ToString());
                            vars.Add("change", changeText);

                            MessageBuilder msg1 = MessageBuilder.BuildFromTemplate(database, this.enterprise_id, "access_request_changed", String.Join(",", mails), vars, trans);
                            msg1.SaveToDb(database, trans);
                        }
                    }
                }
                catch { }

                database.Commit();

                return(new WorkflowRequestProccess(true, ""));
            }
            catch (Exception ex)
            {
                database.Rollback();

                return(new WorkflowRequestProccess(false, "Erro on deny access.", ex.Message));
            }
        }
コード例 #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            MAutoservice mClass = ((MAutoservice)this.Master);

            menu1 = menu2 = menu3 = null;

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

            menu1 = new LMenu("Home", ApplicationVirtualPath + "autoservice/");
            menu3 = new LMenu("Requisição de acesso", ApplicationVirtualPath + "autoservice/access_request/");

            login = LoginUser.LogedUser(this.Page);

            if (login == null)
            {
                Session["last_page"] = Request.ServerVariables["PATH_INFO"];
                Response.Redirect("/login/");
            }

            String action = "";

            if (RouteData.Values["action"] != null)
            {
                action = RouteData.Values["action"].ToString().ToLower();
            }

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


            String html  = "";
            String eHtml = "";
            String js    = "";
            String rData = "";
            String jData = "";


            String sideHTML = "";


            if (action != "new")
            {
                sideHTML += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "autoservice/access_request/new/'\">Nova requisição</button></div>";
            }


            //Verifica se está selecionado o usuário

            switch (action)
            {
            case "new":
                subtitle = "Nova requisição de acesso";

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    //Busca todos os workflows disponíveis no mesmo contexto do usuário atual que esteja habilitado
                    DataTable dtWorkflow = database.ExecuteDataTable("select w.* from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id inner join entity e with(nolock) on e.context_id = c.id where w.enabled = 1 and w.deprecated = 0 and e.id = " + login.Id + " order by w.name");
                    if ((dtWorkflow == null) || (dtWorkflow.Rows.Count == 0))
                    {
                        eHtml += String.Format(errorTemplate, "Nenhuma acesso disponível para solicitação");
                    }
                    else
                    {
                        js += "<script type=\"text/javascript\">";
                        js += "$( document ).ready(function() {";
                        js += "     $('#workflow').change(function() {";
                        js += "        $('#desc_text').html('');";
                        js += "        $('#desc_text').html( $('option:selected', this ).attr('description') );";
                        js += "     });";
                        js += "});";
                        js += "</script>";


                        html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "autoservice/access_request/action/add_request/\">";
                        html += "<div class=\"no-tabs fields\"><table><tbody>";

                        String select = "<select id=\"workflow\" name=\"workflow\" ><option value=\"\"></option>";
                        foreach (DataRow dr in dtWorkflow.Rows)
                        {
                            select += "<option value=\"" + dr["id"] + "\" description=\"" + HttpUtility.HtmlEncode(dr["description"]) + "\">" + dr["name"] + "</option>";
                        }
                        select += "</select><span id=\"desc_text\" class=\"description\" style=\"padding: 5px 0 0 0;\"></span>";

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

                        html += String.Format(infoTemplate, "Descrição da necessidade do acesso", "<textarea id=\"description\" name=\"description\" rows=\"5\" placeholder=\"Digite a justificativa para necessidade de acesso\"></textarea>");

                        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 + "autoservice/access_request/\" class=\"button link floatleft\">Cancelar</a></form>";
                    }
                }
                break;

            default:


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

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

                if (id > 0)
                {
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        subtitle = "Requisição de acesso";

                        DataTable drRequest = database.ExecuteDataTable("select * from st_workflow_request r with(nolock) where r.id = " + id);
                        if ((drRequest != null) && (drRequest.Rows.Count > 0))
                        {
                            WorkflowConfig workflow = new WorkflowConfig();
                            workflow.GetDatabaseData(database, (Int64)drRequest.Rows[0]["workflow_id"]);

                            WorkflowRequestStatus status = (WorkflowRequestStatus)((Int32)drRequest.Rows[0]["status"]);

                            DataTable drRequestStatus = database.ExecuteDataTable("select r.*, a.name activity_name from st_workflow_request_status r with(nolock) inner join st_workflow_activity a with(nolock) on r.activity_id = a.id where r.workflow_request_id = " + drRequest.Rows[0]["id"] + " order by date desc");
                            DataTable drActivity      = database.ExecuteDataTable("select * from st_workflow_activity a with(nolock) where a.workflow_id = " + workflow.WorkflowId + " order by a.execution_order");

                            //html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "autoservice/access_request/action/add_request/\">";
                            html += "<div class=\"no-tabs fields\"><table><tbody>";

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

                            html += String.Format(infoTemplate, "Último status", MessageResource.GetMessage("wf_" + status.ToString().ToLower()));

                            html += String.Format(infoTemplate, "Data da requisição", MessageResource.FormatDate((DateTime)drRequest.Rows[0]["create_date"], false));

                            html += String.Format(infoTemplate, "Descrição da necessidade do acesso", drRequest.Rows[0]["description"].ToString());

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


                            //sideHTML += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "autoservice/access_request/new/'\">Nova requisição</button></div>";


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


                            html += "<h3>Passos de aprovação</h3>";

                            html += "<div class=\"sep\"><table id=\"users-table\" class=\"sorter\"><thead>";
                            html += "    <tr>";
                            html += "        <th class=\"pointer w80 header headerSortDown\" data-column=\"name\">Passo <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer header headerSortDown\" data-column=\"name\">Atividade <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header\" data-column=\"status\">Último status <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";


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

                            Int32 step = 1;
                            if ((drActivity != null) && (drActivity.Rows.Count > 0))
                            {
                                foreach (DataRow dr in drActivity.Rows)
                                {
                                    String   st   = "";
                                    DateTime last = new DateTime(1970, 1, 1);

                                    if ((drRequestStatus != null) && (drRequestStatus.Rows.Count > 0))
                                    {
                                        foreach (DataRow drSt in drRequestStatus.Rows)
                                        {
                                            if (drSt["activity_id"].ToString() == dr["id"].ToString())
                                            {
                                                if (last.CompareTo((DateTime)drSt["date"]) < 0)
                                                {
                                                    last = (DateTime)drSt["date"];
                                                    st   = MessageResource.GetMessage("wf_" + ((WorkflowRequestStatus)((Int32)drSt["status"])).ToString().ToLower());
                                                }
                                            }
                                        }
                                    }

                                    if (st == "")
                                    {
                                        st = "Aguardando aprovação da atividade anterior";
                                    }

                                    html += String.Format(trTemplate, dr["id"], step++, dr["name"], st);
                                }
                            }

                            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\">Atividade <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>";

                            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 += "            <td class=\"tHide mHide\">{4}</td>";
                            trTemplate += "    </tr>";



                            if ((drRequestStatus != null) && (drRequestStatus.Rows.Count > 0))
                            {
                                foreach (DataRow dr in drRequestStatus.Rows)
                                {
                                    try
                                    {
                                        html += String.Format(trTemplate, dr["id"], MessageResource.FormatDate((DateTime)dr["date"], false), MessageResource.GetMessage("wf_" + ((WorkflowRequestStatus)((Int32)dr["status"])).ToString().ToLower()), dr["activity_name"], dr["description"]);
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                }
                            }

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

                            //html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "autoservice/access_request/\" class=\"button link floatleft\">Cancelar</a></form>";
                        }
                        else
                        {
                            eHtml += String.Format(errorTemplate, "Requisição não encontrada");
                        }
                    }
                }
                else     //Request não selecionado
                {
                    subtitle = "Requisição de acesso";

                    js += "<script type=\"text/javascript\">";
                    js += "$( document ).ready(function() {";
                    js += "    $('table tbody tr').each(function (index, element) {";
                    js += "        if ($(this).attr('data-href')) {";
                    js += "            $(this).unbind('click');";
                    js += "            $(this).click(function (event) {";
                    js += "                event.preventDefault();";
                    js += "                window.location = $(this).attr('data-href');";
                    js += "            });";
                    js += "        }";
                    js += "    });";
                    js += "});";
                    js += "</script>";

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        DataTable dtWorkflowRequests = database.ExecuteDataTable("select * from st_workflow_request where entity_id = " + login.Id + " order by create_date desc");
                        if ((dtWorkflowRequests == null) || (dtWorkflowRequests.Rows.Count == 0))
                        {
                            eHtml += String.Format(errorTemplate, "Nenhuma requisição cadastrada");
                        }
                        else
                        {
                            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=\"status\">Status <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer w150 tHide mHide header\" data-column=\"create_date\">Data de criação <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";

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

                            foreach (DataRow dr in dtWorkflowRequests.Rows)
                            {
                                try
                                {
                                    WorkflowConfig workflow = new WorkflowConfig();
                                    workflow.GetDatabaseData(database, (Int64)dr["workflow_id"]);

                                    WorkflowRequestStatus status = (WorkflowRequestStatus)((Int32)dr["status"]);


                                    html += String.Format(trTemplate, dr["id"].ToString(), workflow.Name, MessageResource.GetMessage("wf_" + status.ToString().ToLower()), ((DateTime)dr["create_date"]).ToString("yyyy-MM-dd HH:mm:ss"));
                                }
                                catch (Exception ex)
                                {
                                }
                            }


                            html += "</tbody></table>";
                        }
                    }
                }
                break;
            }

            headContent.Controls.Add(new LiteralControl(js));
            contentHolder.Controls.Add(new LiteralControl((eHtml != "" ? eHtml : html)));

            sideHTML += "<ul class=\"user-profile\">";
            sideHTML += "    <li id=\"user-profile-general\" " + (action == "" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "autoservice/access_request/\">Requisições realizadas</a></span></li>";
            //sideHTML += "    <li id=\"user-profile-password\" " + (action == "changepassword" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "autoservice/access_request/new/\">Nova requisição</a></span></li>";
            sideHTML += "</ul>";

            sideHolder.Controls.Add(new LiteralControl(sideHTML));

            String titleBarHTML = "";

            /*
             * titleBarHTML += "<ul class=\"mobile-button-bar w50 \">";
             * titleBarHTML += "    <li id=\"user-profile-general-mobile\" "+ (action == "" ? "class=\"on\"" : "") + "><a href=\"" + ApplicationVirtualPath + "autoservice/user/\">Informações gerais</a></li>";
             * titleBarHTML += "    <li id=\"user-profile-password-mobile\" " + (action == "changepassword" ? "class=\"on\"" : "") + "><a href=\"" + ApplicationVirtualPath + "autoservice/user/changepassword/\">Troca de senha</a></li>";
             * titleBarHTML += "</ul>";*/

            titleBarContent.Controls.Add(new LiteralControl(titleBarHTML));
        }