Friday, November 13, 2009

Get Tables and Columns Names by LINQ


Here I am explaining one of the tricks to get all table name list along with column of it from your DataContext.
I am using the System.Data.Linq.Mapping.MetaModel to get information about tables and it have much more database related information.

Following are the code to list all table name along with column from your DataContext.

//DataContext object.
DataClassesDataContext DB = new DataClassesDataContext();
       
//String variable to stor html to render.
string strHtmlToLoad = "";
       
//Heading
strHtmlToLoad = "<-h2->Table Names<-/h2-><-ol->";
       
//Loop through tables add name to string
foreach (var mTable in DB.Mapping.GetTables())
{
strHtmlToLoad += "<-li->" + mTable.TableName + "<-ul->";

//Loop through table's columns add name to string
foreach (var mColumn in mTable.RowType.DataMembers)
strHtmlToLoad += "<-li->" + mColumn.MappedName + "<-/li->";
           
strHtmlToLoad += "<-/ul-><-/li->";
}

//Reander HTML
Response.Write(strHtmlToLoad + "<-/ol->");

Please remove "-" from above code. I have to add it because of HTML rendring of this post made that element active and mesh up the post formate.



Thursday, November 12, 2009

Dynamic columns in Gridview

There are many types of column field are are available for grid view like
  • BoundField
  • ButtonField
  • CheckBoxField
  • CommandField
  • HyperLinkField
  • ImageField
  • TemplateField
Here I explain how to add dynamically Bound Field and then Template Field into grid view. First we look how to add Bound Field into Grid view and then Template Field.

First of all make your AutoGenerateColumns property to false.

Prepare your data source which will you going bind with grid view. it will be Data Table or Generic List of class type or structure type any thing or Table Class of your Linq dbml data contexts class.

Here we are going to use Data Table as follow.

DataTable dt = new DataTable("ItemMaster");

dt.Columns.Add(new DataColumn("ItemId",typeof(Int32)));
dt.Columns.Add(new DataColumn("ItemName", typeof(String)));
dt.Columns.Add(new DataColumn("Price", typeof(Decimal)));

for (int i = 0; i < 10; i++)
{
     DataRow dr = dt.NewRow();
     dr[0] = i + 1;
     dr[1] = "Name " + i.ToString();
     dr[2] = i * 0.5 + 1;
     dt.Rows.Add(dr);
}

For each column of table we have to add one BoundField into gridview following is code for that

foreach (DataColumn dc in dt.Columns)
{
     BoundField bf = new BoundField();
     bf.DataField = dc.ColumnName;
     bf.HeaderText = dc.ColumnName;
     GridView1.Columns.Add(bf);
}

Now you grid view is ready to bind DataTable.

GridView1.DataSource = dt;
GridView1.DataBind();

This type of dynamic generated column is useful when we want custom css and style depend on some logic. and we want to show hide some column dynamically.

To add Template Field dynamically you have to create one class which inherit ITemplate interface. Here in example we create one hyperlink template field class which inherit ITemplate interface then we bind that field to our grid view using data table.



public class HyperLinkTemplate : ITemplate
{
    private DataControlRowType TemplateType;
    private string ColumnName;
    private string NavigateUrl;
    private string Text;

    public HyperLinkTemplate(DataControlRowType TemplateType, string ColumnName, string NavigateUrl, string Text)
    {
        this.TemplateType = TemplateType;
        this.ColumnName = ColumnName;
        this.NavigateUrl = NavigateUrl;
        this.Text = Text;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (TemplateType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = ColumnName;
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink objHyperLink = new HyperLink();
                objHyperLink.Target = "_blank";
                objHyperLink.DataBinding += new EventHandler(objHyperLink_DataBinding);
                container.Controls.Add(objHyperLink);
                break;
            default:
                break;
        }
    }

    void objHyperLink_DataBinding(object sender, EventArgs e)
    {
        HyperLink objHyperLink = sender as HyperLink;
        GridViewRow row = (GridViewRow)objHyperLink.NamingContainer;
        objHyperLink.NavigateUrl = NavigateUrl;
        objHyperLink.Text = DataBinder.Eval(row.DataItem, Text).ToString();
    }
}

To bind this HyperLinkTemplate to oure grid view use following code. Here we bind Item name column to this template field with editpage.aspx url. this code display both boud field and template field adding.



foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName != "ItemName")
{
BoundField bf = new BoundField();
bf.DataField = dc.ColumnName;
bf.HeaderText = dc.ColumnName;
GridView1.Columns.Add(bf);
}
else
{
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new HyperLinkTemplate(DataControlRowType.Header, dc.ColumnName, "", "");
tf.ItemTemplate = new HyperLinkTemplate(DataControlRowType.DataRow, dc.ColumnName, "~/editpage.aspx", dc.ColumnName);
GridView1.Columns.Add(tf);
}
}





Friday, November 6, 2009

Get website's base URL..



Following function is help you to get root path or site base URL of your web application.
Like if your page URL like "http://www.blogger.com/post-create.g?blogID=5406317769839137062"
this function return base URL like "http://www.blogger.com".

public static string GetApplicationPath()
{
     string appPath = null;

     //Getting the current context of HTTP request
     HttpContext context = HttpContext.Current;

     //Checking the current context content
     if (context != null)
     {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                context.Request.Url.Scheme,
                context.Request.Url.Host,
                context.Request.Url.Port == 80 ? string.Empty : ":" + context.Request.Url.Port,
                context.Request.ApplicationPath);
     }
     return appPath;
}

Better One

public static string GetApplicationPath()
{

var request = HttpContext.Current.Request;
var appUrl = HttpRuntime.AppDomainAppVirtualPath;

if (!string.IsNullOrWhiteSpace(appUrl) && appUrl != "/")
    appUrl += "/";

var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

 return baseUrl;

}

Thursday, November 5, 2009

Message Panel



This in post show you how effectively you can show you messages and error regarding the user events using the Message Panel control. following are the step by step description of how to create and use Message panel.

Create Message panel

In your application add folder App_Code.
To do that right clicking on Web project select Add Asp.net folder >> App_Code



Add one class file name MessagePanel.cs and copy pest following code into it.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Controls
{
   // TODO: add clear link (display: none;) plus requried js
   [ToolboxData("<{0}:MessagePanel runat=\"server">")]
    public class MessagePanel : Panel, INamingContainer
    {
        private const string VSKEY_MESSAGE = "Message";
        private const string VSKEY_ERROR = "Error";

        bool _showMessagePanel;
        bool _showErrorPanel;

        string _messageCssClass;
        string _errorCssClass;
        string _messageIconUrl;
        string _errorIconUrl;

        public MessagePanel()
        {
            ViewState[VSKEY_MESSAGE] = String.Empty;
            ViewState[VSKEY_ERROR] = String.Empty;
        }
       
        #region Accessors
        public string Message
        {
            get { return (string)ViewState[VSKEY_MESSAGE]; }
            set { ViewState[VSKEY_MESSAGE] = value; }
        }

        public string Error
        {
            get { return (string)ViewState[VSKEY_ERROR]; }
            set { ViewState[VSKEY_ERROR] = value; }
        }

        public bool ShowMessagePanel
        {
            get { return _showMessagePanel; }
            set { _showMessagePanel = value; }
        }

        public bool ShowErrorPanel
        {
            get { return _showErrorPanel; }
            set { _showErrorPanel = value; }
        }

        public string MessageCssClass
        {
            get
            {
                if (this._messageCssClass == null)
                {
                    this._messageCssClass = "MessagePanel";
                }
                return _messageCssClass;
            }
            set { _messageCssClass = value; }
        }

        public string ErrorCssClass
        {
            get
            {
                if (this._errorCssClass == null)
                {
                    this._errorCssClass = "ErrorPanel";
                }
                return _errorCssClass;
            }
            set { _errorCssClass = value; }
        }

        public string MessageIconUrl
        {
            get
            {
                if (_messageIconUrl == null)
                {
                    _messageIconUrl = "~/Resources/images/messagebox_info.gif";
                }
                return _messageIconUrl;
            }
            set { _messageIconUrl = value; }
        }

        public string ErrorIconUrl
        {
            get
            {
                if (_errorIconUrl == null)
                {
                    _errorIconUrl = "~/Resources/images/messagebox_critical.gif";
                }
                return _errorIconUrl;
            }
            set { _errorIconUrl = value; }
        }

        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            if (null != Page)
                Page.VerifyRenderingInServerForm(this);

            if (this.ShowErrorPanel)
            {
                Panel errorPanel = BuildPanel(this.Error, this.ErrorCssClass, ErrorIconUrl);
                this.Controls.Add(errorPanel);
            }

            if (this.ShowMessagePanel)
            {
                Panel messagePanel = BuildPanel(this.Message, this.MessageCssClass, MessageIconUrl);
                this.Controls.Add(messagePanel);
            }

            base.Render(writer);
        }

         protected virtual Panel BuildPanel(string messageText, string cssClass, string imageUrl)
        {
            Panel result = new Panel();

            if (null != imageUrl && cssClass.Length > 0) result.CssClass = cssClass;

            if (null != imageUrl && imageUrl.Length > 0)
            {
                System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
                image.ImageUrl = imageUrl;
                result.Controls.Add(image);
            }

            Panel message = new Panel();
            message.Controls.Add(new LiteralControl(messageText));
            result.Controls.Add(message);

            return result;
        }

        public void ShowMessage(string message)
        {
            ShowMessage(message, true);
        }

        public void ShowMessage(string message, bool clearExistingMessages)
        {
            if (clearExistingMessages)
                this.Message = message;
            else
                this.Message += " " + message;

            this.ShowMessagePanel = true;
            this.Visible = true;
        }

        public void ShowError(string message)
        {
            ShowError(message, true);
        }

        public void ShowError(string message, bool clearExistingMessages)
        {
            if (clearExistingMessages)
                this.Error = message;
            else
                this.Error += " " + message;

            this.ShowErrorPanel = true;
            this.Visible = true;
        }

        public void Clear()
        {
            this.Visible = false;
        }


    }
}



Add following CSS code in your .css file and put proper images at path shown into the code

/* Start: Message/Error Display CSS*/
div.MessagePanel {
/*background:#EEEEEE none repeat scroll 0%;*/
border:1px dashed #0BAF4D;
color:#0BAF4D;
font-weight:bold;
/*padding:5px;*/
font-size:13px;
margin-bottom:10px;
}


div.ErrorPanel {
/*background:#FFFFCC none repeat scroll 0%;*/
border:1px dashed red;
color:red;
font-weight:bold;
font-size:13px;
margin-bottom:10px;
}

div.ErrorPanel img, div.MessagePanel img {
float:left;
}

div.ErrorPanel div, div.MessagePanel div {
margin-left:32px;
padding-top:8px;
padding-bottom:8px;
text-align:left;
}
/* End: Message/Error Display CSS*/



How to put Message panel into .ASPX or .ASCX file

Add following into the web.config

<system.web>
  <pages>
     <controls>
         <add tagPrefix="Controls" namespace="Controls"/>
     controls>
  pages>
system.web>

Add following in your .ASPX or .ASCX file where you want to show message panel.

<Controls:MessagePanel ID="msgPanel" runat="server">
Controls:MessagePanel>


How to code with Message panel

In codebehind file use following methods to show and display messages and errors

To clear message

msgPanel.Clear();

To show message

msgPanel.ShowMessage("Meesage");

To show error

msgPanel.ShowError("Error");


Out put of message panel is like bellow

Message





Error