Monday, February 25, 2013

Calling Web Services from Javascript

This also quite straight simple and I am using Asp.Net. The requirement and the procedures are as stated below.
It might be helpful if compare with Calling Code behind Server function from Javascript.

1. Using Ajax.
2. Add ScriptManager or ToolkitScriptManager
3. And a new Web Services Assuming that returning List<string>.
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
    public List<string> GetData(string CatID)
    {
        List<string> list = new List<string>();
        if (CatID== "1")
        {
            list.Add("Nokia N95");
            list.Add("Nokia N70");
            list.Add("Nokia 6630");
        }
        else
        {
            list.Add("Dell Laptop");
            list.Add("HP Laptop");
            list.Add("Sony Laptop");
        }
        return list;
    }
}
4. Add javascript function as following.
<script type="text/javascript">
       function CallWS_onclick() {
         var catid = $get('<%= txtCatID.ClientID %>').value;
         MyWebService.GetData(catid , onSuccess, onFailed);
      }
      function onSuccess(result)
      {
          var Result= $get('<%= lblResult.ClientID %>');             
         Result.innerHTML = "";
            
         for(i=0 ; i<result.length ; i++)
         {
            Result.innerHTML += result[i] + "<br />";
         }
      }
      function onFailed(error)
      {
          var Result= $get('<%= lblResult.ClientID %>');
         Result.innerHTML = "Service Error: " + error.get_message();
      }
   </script>
5. Add one input button in design page.
<input id="Button1" type="button" value="Get Products"
      onclick="Button1_onclick(this)" /> 

That's it.
Enjoy Programming ! 
Ref:http://www.ezzylearning.com/tutorial.aspx?tid=3967791&q=calling-web-services-in-client-script-using-asp-net-ajax

Sunday, February 24, 2013

Calling Code behind Server function from Javascript

It is quite straight simple and I am using Asp.Net. The requirement and the procedures are as following.
It might be helpful if compare with Calling Web Services from Javascript .
1. Using Ajax
2. Set EnablePageMethods="true" in ScriptManager or ToolkitScriptManager attribute.
3. Code behind method must be public.
4. Apply WebMethod attribute to the codebehind function [System.Web.Services.WebMethod]
[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{
   //Do Logic staff here
   return "Result";
}
5. Create javascript function
(If javascript is external file, add ref in body tag. Not in head tag.)

function CallMe(custidTextBox,DestTextBox)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, DestTextBox);
 }
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
6. Attach this javascript to desired control.
<input id="BtnSave" class="button_sub" name='<%# Eval("Document_No") + "|"+ Eval("Line_No")%>' type="button" value="Save" onclick="SaveByMe(this,this)" /> 
That's it.
Enjoy Programming.  
Ref : http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

Tuesday, February 5, 2013

Gridview Row Mouseover highlight and anchor link


 protected void Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblDreceive = ((Label)e.Row.FindControl("lblDateReceive"));
            Label lblDissue = ((Label)e.Row.FindControl("lblDateIssue"));

            object d1 = DataBinder.Eval(e.Row.DataItem, "Posted_Purch_Receipt_Date");
            object d2 = DataBinder.Eval(e.Row.DataItem, "Sales_Shipment_Date");
            if (d1 != null)
            {
                DateTime dReceive = DateTime.Parse(d1.ToString());
                lblDreceive.Text = dReceive.Year > 1999 ? dReceive.Day.ToString("00") + "-" + dReceive.Month.ToString("00") + "-" + dReceive.Year.ToString("00") : "";
            }
            else
            {
                lblDreceive.Text = "";
            }

            if (d2 != null)
            {
                DateTime dIssue = DateTime.Parse(d2.ToString());
                lblDissue.Text = dIssue.Year > 1999 ? dIssue.Day.ToString("00") + "-" + dIssue.Month.ToString("00") + "-" + dIssue.Year.ToString("00") : "";
            }
            else
            {
                lblDissue.Text = "";
            }

            string script = String.Format("window.open('./EditBufferExchange.aspx?t=tool&entryno={0}&purrec={1}','_self')", DataBinder.Eval(e.Row.DataItem, "Entry_No"), DataBinder.Eval(e.Row.DataItem, "Posted_Purch_Receipt_No"));
            e.Row.Attributes.Add("onclick", script);

            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';");
            }


        }
    }

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