Friday, September 28, 2012

How to call server side function from client side javascript in ASP.Net?


How to call serverside function from client side javascript in ASP.Net?


Call ASP.Net/C# function using Javscript
Usually in ASP.net platform, server side functions (all codes written in asp.net,C#) are executing from the server side and all client side funtions (javascript,jquery,ajax) are executing from the client side. Obviously client side functions are too faster than the server side because there is no need to go upto server, will running from the browser itself.
But we are unable to written all functions in client side to get good performance. But for this technique, there is some tips can be used. What we are going to do is, we are writing a server side code in ASP.Net,C# and call these functions from client side using javascript and ajax.
Steps to Calling ServerSide method from javscript
  1. Create a aspx page with three textboxes and a button control.
  2. User enter two numbers in first two textboxes and press calculate button.
  3. We are fetching entered values and calling a serverside funtion by passing this values.
  4. In the server side function find the sum and return the result.
  5. In client side’s succes event, getting result from the server and displayed to third textbox.
Step 1 :
 Create a aspx page with controls, two textboxes for entering the numbers, one button for find the sum of number and a one more text box to display the result.
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="testWebApp.Result" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    Number1:
                </td>
                <td>
                    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Number2:
                </td>
                <td>
                    <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Sum:
                </td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSum" runat="server" Text="Sum" OnClientClick="CallSum();return false;" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
Step 2  
In code behind, write a web method to access two parameters and return the result. In the function we added parameters and return the result.
protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Server side function Sum
        /// </summary>
        /// <param name="arg1">arg1</param>
        /// <param name="arg2">arg2</param>
        /// <returns>result(sum)</returns>
        [System.Web.Services.WebMethod]
        public static int Sum(int arg1, int arg2)
        {

            /* On server side we can do any thing. Like we can access the Session.
             * We can do database access operation. Without postback.
             */
            try
            {
                return arg1 + arg2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Step 3
 Create a javscript method in aspx page to get input textboxes values and call serverside function. Here itself we decalre a success and failure event, for getting the event from the server after the current function executed.
 <script language="javascript" type="text/javascript">
    <!--

        // Javascript function
        function CallSum() {
            //Get the controls
            var txt1 = $get("txt1");
            var txt2 = $get("txt2");
            var txtresult = $get("txtSum");

            //Call server side function
            PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);

            /*Server side function get the 2 arguments arg1 and arg2. We are passing txt1.value and txt2.value
            for that. OnCallSumComplete is callback function for complete successfully. OnCallSumError is callback
            function on error. txtresult is usercontext parameter.

            OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

            If server side code executed successfully then OnCallSumComplete will call.
            If server side code do not executed successfully then OnCallSumError will call.

            */
        }

        // Callback function on complete
        // First argument is always "result" if server side code returns void then this value will be null
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumComplete(result, txtresult, methodName) {
            //Show the result in txtresult
            txtresult.value = result;
        }

        // Callback function on error
        // Callback function on complete
        // First argument is always "error" if server side code throws any exception
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumError(error, userContext, methodName) {
            if (error !== null) {
                alert(error.get_message());
            }
        }

    // -->
    </script>
Project is ready for call server sided functions from client side using javascript. Run the application and enter two numbers in first and second textboxes then press calculate button, the we can show that result is displayed in third box without any page postback. If we enterd alphabets instead of numbers, from the server it will happening error and ‘failure’ event occurred in the javascript will alert the details of the error.




Reference : 

How to call serverside function from client side javascript in ASP.Net?

How to maintain scroll position after post back?


How to maintain scroll position in ASP.Net Pages
When web pages are posted back to the server, by default user is returned to the top of the page. On a large web page, you might have a requirement to scroll down the user automatically to the last position on the page.
MaintainScrollPositionOnPostBack page property can be used to achieve this  in one of the following ways.
  1. Application level:To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.<pages maintainScrollPositionOnPostBack=”true”>
  2. Page Level:for a particular page, open the aspx and set the property<%@ Page MaintainScrollPositionOnPostback=”true” …
  3. Code level: to set the property programmaticallyPage.MaintainScrollPositionOnPostBack = true;
Reference : http://tuvianblog.com/2012/01/06/how-to-maintain-scrollposition-after-post-back/

Monday, September 17, 2012

Add Web Part Programatically on Home / Default Page

Hi,


  • Create a SharePoint 2010 Solution in Visual Studio.
  • Add Feature & its scope.
  • Add Feature Receiver Class & the add below mentioned code :



        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // Get a reference to a web and a list
            SPWeb web = properties.Feature.Parent as SPWeb;
            string pageURL=web.RootFolder.WelcomePage;
            if(pageURL=="")
                pageURL="default.aspx";
            SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(pageURL  , System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
            
            // Add the web part
            mgr.AddWebPart(CreatePageWebPart(web.Url), "Left", 1);
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                // Get a reference to a web and a list
                SPWeb web = properties.Feature.Parent as SPWeb;
                string pageURL = web.RootFolder.WelcomePage;
                if (pageURL == "")
                    pageURL = "default.aspx";
                SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(pageURL, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                

                for (int i = 0; i < mgr.WebParts.Count; i++ )
                {
                    if (mgr.WebParts[i].ID == "Tasks-My_Tasks")
                    {
                        mgr.DeleteWebPart(mgr.WebParts[i]);
                        break;
                    }
                }
            }
            catch (Exception ex) { string s = ex.ToString(); }
        }


        private XsltListViewWebPart CreatePageWebPart(string webURL)
        {
            // create our List View web part
            XsltListViewWebPart wp = new XsltListViewWebPart();
            using (SPSite site = new SPSite(webURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Tasks"];
                    wp.ID = "Tasks-My_Tasks";
                    wp.ListId = list.ID;
                    wp.ListName = list.ID.ToString();
                    wp.ViewGuid = list.Views["My Tasks"].ID.ToString();
                    wp.XmlDefinition = list.Views["My Tasks"].GetViewXml();

                    // set basic properties along with the title
                    wp.AllowConnect = false ;
                    wp.Title = "My Tasks :";
                    wp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.Default ;
                }
            }
            return wp;
        }

Enjoy Codding!!!





Friday, September 14, 2012

PDF Viewer Webpart

Here now presenting PDF Viewer web part solution with code. You can view any pdf file by providing url of the pdf document or you can use this pdf viewer web part as connected web part also.



When you install this web part , you will see a “View PDF” button in your ribbon of all document libraries.












You can view pdf by clicking on the button from the ribbon.

















Enjoy!!!

Monday, September 10, 2012

SharePoint 2013 Important Links


SharePoint Server 2013 Preview Download:
http://technet.microsoft.com/en-US/evalcenter/hh973397
SharePoint Foundation 2013 Preview Download:
http://www.microsoft.com/en-us/download/details.aspx?id=30345
SharePoint 2013 & Office 2013 Training For Developers:
http://msdn.microsoft.com/en-US/sharepoint/fp123633
SharePoint 2013 Training For IT Pros:
http://technet.microsoft.com/en-US/sharepoint/fp123606
Start: Set up the development environment for SharePoint 2013:
http://msdn.microsoft.com/en-us/library/ee554869(v=office.15)
Cheers

Thursday, September 6, 2012

How to calculate difference between two dates in javascript/jquery


Simple steps to calculate difference between two date fields using JavaScript/JQuery 
In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks
Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 
Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.
function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}
How to calculate the date difference from client side using javascript?
Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.
Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.
function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}
In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}
ASPX page having two date fields as follows :
<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>




Reference :

How to calculate difference between two dates in javascript/jquery

Wednesday, September 5, 2012

Disable Right click of mouse


How to disable right click functionality from the asp.net web page
In some of the web page has the requirement to protect source code from the users. Users can right click the page and take the source code. In order protect right click functionality on the web page we can implement javascript functionality to prevent user’s right click on the web page. So user not able to access features available on the right click menus.
By implementing javascript method we can identify the right click event from the user by checking the button code and prevent if the user clicks right click. Below mentioned web page prevented to click right click by the user. When the user trying to right click it will return warning message to user and return the action.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisableRightClick.aspx.cs"
 Inherits="ExperimentLab.DisableRightClick" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Sample to Disable Right Click of Page</title>
 <script language="JavaScript" type="text/javascript">
 //Message to display whenever right click on website
 var message = "Sorry, Right Click have been disabled.";
 function click(e) {
 if (document.all) {
 if (event.button == 2 || event.button == 3) {
 alert(message);
 return false;
 }
 }
else {
 if (e.button == 2 || e.button == 3) {
 e.preventDefault();
 e.stopPropagation();
 alert(message);
 return false;
 }
 }
 }
if (document.all) {
 document.onmousedown = click;
 }
else {
 document.onclick = click;
 }
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 In this page right click not allowed.
 </div>
 </form>
</body>
</html>
Reference from : http://tuvianblog.com/2012/03/20/disable-right-click-on-a-web-page-in-asp-netc-using-jqueryjavascript/