Thursday, January 3, 2013

SQL Helper Class

Highlight Gridview Row on Mouse Over with Navigate Link

protected void gvShowlist_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           // Navigate Link 
           string script = String.Format("window.open('./Destination.aspx?t=tool&qs1={0}&qs2={1}','_self')", DataBinder.Eval(e.Row.DataItem, "QS1_Value"), DataBinder.Eval(e.Row.DataItem, "QS2_Value"));
            e.Row.Attributes.Add("onclick", script);

           // Highlight on Mouse Over
            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
            }
            else
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#f1f3f6';");
            }
        }
    }

Another Way with JQuery

Javascript centered popup window

function popup(url) {
        var width = screen.width - 200;
        var height = screen.height - 150;
        var left = 100;
        var top = 50;
        var params = 'width=' + width + ', height=' + height;
        params += ', top=' + top + ', left=' + left;
        params += ', directories=no';
        params += ', location=no';
        params += ', menubar=no';
        params += ', resizable=no';
        params += ', scrollbars=yes';
        params += ', status=no';
        params += ', toolbar=no';
        newwin = window.open(url, 'NewWindowPopup', params);
        if (window.focus) { newwin.focus() }
        return false;
    }

Call this Function in Code behind
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>popup('" + url + "')</script>");

Call this Function in Code behind using Ajax WITH UpdatePanel
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenWin", "popup('" + url + "')", true);

ASP.Net Resources ( Multi Languages )

Creating a website with multi languages very common development to all web developers. Somehow, I hope this could be helpful and it is just about sharing knowledge.

What is Global Resources :
   - One Language One Resource file ( share within pages in the entire web site. )
   - Explicit localization
   - Create resource file manually.

What is Local Resources :
   - For each page One Resource file ( cannot share with other page )
   - Implicit localization
   - By web Tools. (Finish the page first and switch to Design View. Tools > Generate Local Resource)

My example is Explicit localization

1. Create BasePage Class in App_Code folder
public class BasePage : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        if (Session["CUL"] != null)
        {
            String selectedLanguage = Session["CUL"].ToString();
            UICulture = selectedLanguage;
            Culture = selectedLanguage;

            Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(selectedLanguage);
            Thread.CurrentThread.CurrentUICulture = new
                CultureInfo(selectedLanguage);
        }
        base.InitializeCulture();
    }
}

2. All the Web Forms need to change inheritance class BagePage class instead of default inherit System.Web.UI.Page.


 






4.a. Default.aspx
   <asp:Label ID="Label1" runat="server"
            Text="<%$ Resources:LocalString, Welcome %>"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server"
            Text="<%$ Resources:LocalString, Construction %>"></asp:Label>
        <br />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem Text="en-US" Value="en-US"></asp:ListItem>
        <asp:ListItem Text="en-AU" Value="en-AU"></asp:ListItem>
        </asp:DropDownList>
   
        <br />
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default2.aspx">HyperLink</asp:HyperLink>

4.b. Default.aspx.cs

using System.Threading;
using System.Globalization;

public partial class _Default : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["CUL"] != null)
            {
                DropDownList1.SelectedIndex=DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Session["CUL"].ToString()));
            }
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["CUL"] = DropDownList1.SelectedItem.Value;
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}

5. Default2.aspx
<asp:Label ID="Label2" runat="server"
            Text="<%$ Resources:LocalString, Construction %>"></asp:Label>

That is ALL. Enjoy programming
Download Sample

Useful links :
- What  is BasePage Class
- Microsoft MSDN
    http://msdn.microsoft.com/en-us/library/ms247245.aspx
    http://msdn.microsoft.com/en-us/library/ms227427.aspx
    http://msdn.microsoft.com/en-us/library/fw69ke6f(v=vs.90).aspx

Friday, September 21, 2012

Maintaining Session Variable in DLL in Asp.Net

In order to control Session Variable in DLL, the class need to inherit from IRequiresSessionState interface and set the class Serializable attribute.
The property should be static (class member) in order to avoid instantiate new object.
eg. CurrentUserSESSION.USER_ID 

public enum SESSION_NAME
    {
        USER_ID,
        USER_PASSWORD,
        USER_FULLNAME,
        USER_ROLE
    }

    [Serializable()]
    public class CurrentUserSESSION : IRequiresSessionState
    {
        public static string USER_ID        {
            get
            {
                return GetSessionValue<string>(SESSION_NAME.USER_ID);
            }
            set
            {
                SetSessionValue<string>(SESSION_NAME.USER_ID, value);
            }
        }
        public static string USER_PASSWORD //login user id
        {
            get
            {
                return GetSessionValue<string>(SESSION_NAME.USER_PASSWORD);
            }
            set
            {
                SetSessionValue<string>(SESSION_NAME.USER_PASSWORD, value);
            }
        }
        public static string USER_FULLNAME
        {
            get
            {
                return GetSessionValue<string>(SESSION_NAME.USER_FULLNAME);
            }
            set
            {
                SetSessionValue<string>(SESSION_NAME.USER_FULLNAME, value);
            }
        }
        public static string USER_ROLE
        {
            get
            {
                return GetSessionValue<string>(SESSION_NAME.USER_ROLE);
            }
            set
            {
                SetSessionValue<string>(SESSION_NAME.USER_ROLE, value);
            }
        }
      
        public CurrentUserSESSION()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private static T GetSessionValue<T>(SESSION_NAME SESSIONNAME)
        {
            if (null != HttpContext.Current.Session[SESSIONNAME.ToString()])
                return (T)HttpContext.Current.Session[SESSIONNAME.ToString()];
            else
                return default(T);
        }

        private static void SetSessionValue<T>(SESSION_NAME SESSIONNAME, T SESSIONVALUE)
        {
            HttpContext.Current.Session[SESSIONNAME.ToString()] = SESSIONVALUE;
        }
    }

Generating MS Word file on the fly in Asp.Net

There is a simple way in order to generate MS Word using ContentType = "application/word" but it will give you in Web Layout instead of Print Layout generally.

public void ExportToMSWord(string fileNameWord)
    {
        StringBuilder sb = new StringBuilder();
        string strBody = string.Empty;
        strBody = @"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
        "xmlns:w='urn:schemas-microsoft-com:office:word'" +
        "xmlns='http://www.w3.org/TR/REC-html40'>";

        strBody = strBody + "<!--[if gte mso 9]>" +
        "<xml>" +
        "<w:WordDocument>" +
        "<w:View>Print</w:View>" +
        "<w:Zoom>100</w:Zoom>" +
        "</w:WordDocument>" +
        "</xml>" +
        "<![endif]-->";

        sb.Append(strBody);
        sb.Append("<table width=\"100%\" style=\"background-color:#cfcfcf;\"><tr><td>aaaaaaaaaaa</td><td>bbbbbbbbb</td></tr></table>");

        string attachment = "attachment; filename= " + fileNameWord;
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/word";
        //StringWriter sw = new StringWriter();
        //HtmlTextWriter htw = new HtmlTextWriter(sw);
        ////this.RenderControl(htw);
        //Response.Write(strBody + sw.ToString());
        Response.Write(sb);
        Response.End();
    }


Alternatively, Interop assemblies of Microsoft Word Object Library can be used and in that case, Microsoft office version need to be aware.