Pages

Friday, November 25, 2011

Code for displaying columns of the gridview based on the columns checked in the Listbox.

Here is the code for displaying columns of the gridview based on the columns checked in the Listbox. This will by default display one column in the gridview and one checkbox ticked in checkbox list. On selecting other checkboxes i.e. firstname, last name, age,gender the columns become visible in the gridview.
<div>
<asp:CheckBoxList ID="chkColumns" runat="server">
</asp:CheckBoxList>
<asp:Button ID="btnShow" runat="server" Text="Show" OnClick="btnShow_Click" />
</div>
<a href="javascript:void(0);">Click</a>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
    <asp:BoundField DataField="id" HeaderText="id" />
</Columns>
</asp:GridView>

    public static DataTable dt;// = new DataTable();
    public static ArrayList existing = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            createtable();
        }
    }
    private void createtable()
        {
            dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("firstname");
            dt.Columns.Add("lastname");
            dt.Columns.Add("age");
            dt.Columns.Add("gender");
            object[] d1 = {"1","a","a1","10","M" };
            object[] d2 = { "2", "b", "b1", "20", "F" };
            object[] d3 = { "3", "c", "c1", "30", "M" };
            object[] d4 = { "4", "d", "d1", "40", "F" };
            dt.Rows.Add(d1);
            dt.Rows.Add(d2);
            dt.Rows.Add(d3);
            dt.Rows.Add(d4);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            bindCheckbox();
            AddVisibleColumnsToArray();
            MarkCheckedInArrayForVisibleColumns();
        }
    private void bindCheckbox()
        {
            chkColumns.DataSource = dt.Columns;
            chkColumns.DataBind();
    }
    private void AddVisibleColumnsToArray()
        {
            GetColumnByDBName(GridView1);
        }
        private void MarkCheckedInArrayForVisibleColumns()
        {
            foreach (ListItem item in chkColumns.Items)
            {
                if (existing.Contains(item.Value))
                    item.Selected = true;
            }
        }
    protected void btnShow_Click(object sender, EventArgs e)
        {
            ArrayList arr =new ArrayList();
            HideGridviewColumns(GridView1,arr);
            foreach (ListItem item in chkColumns.Items)
            {
                if (item.Selected)
                {
                    BoundField b = new BoundField();
                    b.DataField = item.Value;
                    b.HeaderText = item.Value;
                    GridView1.Columns.Add(b);
                }
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
            AddVisibleColumnsToArray();
            MarkCheckedInArrayForVisibleColumns();
    }
    public void GetColumnByDBName(GridView aGridView)
        {
            existing.Clear();
            System.Web.UI.WebControls.BoundField DataColumn;
   
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;
   
                if (DataColumn != null)
                {
                    if (DataColumn.Visible)
                    {
                        if (!existing.Contains(DataColumn.HeaderText))
                            existing.Add(DataColumn.HeaderText);
                    }
                }
            }
        }
   

Tuesday, November 22, 2011

Get XML node and node attribute value

XmlDocument webConfig = new XmlDocument();
        webConfig.Load(HttpContext.Current.Server.MapPath(@"~\web.config"));
        XmlNode node = webConfig.SelectSingleNode("/configuration/system.web/authentication/forms");
        node.Attributes["timeout"].Value;

        node.Value;

       

Forms Authentication for folders with different login page

Folder Structure:

Admin(Folder)
--Default.aspx
--Login.aspx
--Web.Config
User(Folder)

--Default.aspx
--Login.aspx
--Web.Config
Default.aspx
Login.aspx
Web.Config


The problem is as follows:
If a visitor try to access a page in Admin folder he must be redirected to login page located in Admin folder, here his username and password will be checked in SQL Server table, if authenticated then he will be redirected to Default page and he can access any page in Admin folder, but not the pages in User folder
Note: login page in Admin folder and login page in User folder are different.
Same scenario is for User folder

Solution:Here are the steps to follow:
1. Put following lines in /Admin/Web.config file<configuration>
 <location path="Login.aspx">
  <system.web>
   <authorization>
    <allow users="?"/>
   </authorization>
  </system.web>
</location>
</configuration>
2. Put following lines in /User/Web.config file
<configuration>
 <location path="Login.aspx">
  <system.web>
   <authorization>
    <allow users="?"/>
   </authorization>
  </system.web>
 </location>
</configuration>
3. Put following lines in Web.config file (root). Here Login.aspx page is placed at the root path (Note: loginUrl here is the Login page located on the root path)
<authentication mode="Forms">
 <forms name="login" timeout="120" slidingExpiration="false" loginUrl="Login.aspx"></forms>
</authentication>
<location path="Admin">
 <system.web>
  <authorization>
 <allow roles="Admin"/>
 <deny users="*"/>
  </authorization>
 </system.web>
</location>
  <location path="User">
    <system.web>
      <authorization>   
        <allow  roles="User"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Default.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
4. Put following code only in the Login.aspx page located on the root path
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["ReturnUrl"] != null && Request.QueryString["ReturnUrl"].ToString().Length > 0)
        {
            string returnUrl = Request.QueryString["ReturnUrl"].ToString();
            if (returnUrl.ToLower().Contains("/user/"))
            {
                Response.Redirect(string.Format("~/user/Login.aspx?ReturnUrl={0}", returnUrl));
            }
            if (returnUrl.ToLower().Contains("/admin/"))
            {
                Response.Redirect(string.Format("~/admin/Login.aspx?ReturnUrl={0}", returnUrl));
            }
        }
    }
5. On the Login.aspx page under Admin & User folder do the authentication and put following line at the end of button click.HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, createPersistentCookie));

6. And finally put following code for both signOut and redirect accordingly.
 FormsAuthentication.SignOut();
        Response.Redirect("~/admin/Login.aspx");
        or
        FormsAuthentication.SignOut();
        Response.Redirect("~/user/Login.aspx");


Hoping that this might help!       
 


Friday, November 11, 2011

Hide Gridview column

static public void HideGridviewColumns(GridView aGridView,ArrayList arrColumnName)
    {
        System.Web.UI.WebControls.BoundField DataColumn;
        if (arrColumnName.Count > 0)
        {
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

                if (DataColumn != null)
                {
                    DataColumn.Visible = !arrColumnName.Contains(DataColumn.HeaderText);

                }
            }
        }
        else
        {
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

                if (DataColumn != null)
                {
                    DataColumn.Visible = false;
                }
            }
        }
    }

Get ColumnIndex By DataColumn and HeaderText in Gridview

static public int GetColumnIndexByDBName(GridView aGridView, String ColumnText)
    {
        System.Web.UI.WebControls.BoundField DataColumn;

        for (int Index = 0; Index < aGridView.Columns.Count; Index++)
        {
            DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

            if (DataColumn != null)
            {
                if (DataColumn.DataField == ColumnText)
                    return Index;
            }
        }
        return -1;
    }

static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
    {
        TableCell Cell;
        for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
        {
            Cell = aGridView.HeaderRow.Cells[Index];
            if (Cell.Text.ToString() == ColumnText)
                return Index;
        }
        return -1;
    }