Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, October 4, 2011

Javascript Tricks (No Interview Questions)




1        How to get client date and time

Ans-        How to get client date and time
You can use java script function to show the date and time.
<script type="text/javascript">
function displayTime()
{
var localTime = new Date();
var year= localTime.getYear();
var month= localTime.getMonth() +1;
var date = localTime.getDate();
var hours = localTime .getHours();
var minutes = localTime .getMinutes();
var seconds = localTime .getSeconds();
var div=document.getElementById("div1");
div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
}

</script>

Then you can call it at web page.

<body onload="displayTime();">
<form id="form2" runat="server">
<div id="div1"></div>
</form>
</body>

Related posts: http://forums.asp.net/p/1247758/2303034.aspx



2        How to access a control by using JavaScript

Ans-  2        How to access a control by using JavaScript
Reference the ClientID property (or UniqueID) of the control in the JavaScript.
protected void Page_Load(object sender, EventArgs e)
{
Button btn= new Button();
btn.ID = "btn5";
btn.Attributes.Add("runat", "server");
btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
btn.Text = "Test";
this.form1.Controls.Add(btn);
}

function pop(InputBoxID)
{
var InputControl = document.getElementById(InputBoxID);
alert(InputControl.value);
}
Or you can use the following method:
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
alert(InputBox.value);
}

Related posts: http://forums.asp.net/p/1239593/2260331.aspx#2260331


3        How to invoke a server-side function with JavaScript

Ans- 3        How to invoke a server-side function with JavaScript

Firstly, you can drag a server button and put the server function into the button Click even,
protected void Button1_Click(object sender, EventArgs e)
{
FunctionName();
}
Secondly, you can call the server function at JavaScript by using the following code,
document.getElementById("Button1").click();

Related posts: http://forums.asp.net/p/1242420/2274228.aspx


4        How to retrieve server side variables using JavaScript code

Ans-  4       How to retrieve server side variables using JavaScript code [top]

<asp:HiddenField ID="HiddenField1" runat="server" />
public partial class LoginDemo : System.Web.UI.Page
{
private string str="hello";
protected void Page_Load(object sender, EventArgs e)
{
HiddenField1.Value=str;
}
}

Then you can access the control HiddenField1 using javascipt:
<script type="text/JavaScript">
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
</script>

Related posts: http://forums.asp.net/p/1000655/1319119.aspx


5        How to assign a value to a hidden field using JavaScript in ASP.NET

Ans-  5        How to assign a value to a hidden field using JavaScript in ASP.NET

We can use JavaScript to set the value of a hidden control and get its value at the server after a
<input id="Hidden1" type="hidden" />
<script type="text/JavaScript">
var str=”hello”
document.getElementByID(“Hidden1”).value=str
</script>
protected void Page_Load(object sender, EventArgs e)
{
string str=request["Hidden1"].ToString();
}

Related posts: http://forums.asp.net/p/1262153/2362090.aspx


6        How to register the JavaScript function at Code-Behind

Ans-   6        How to register the JavaScript function at Code-Behind
Use ResterStartupScript
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","<script>aler

Use Literal control,
private void Button2_Click(object sender, System.EventArgs e)
{
string str;
str="<script language='JavaScript'>";
str+="selectRange()";
str+="<script>";
Literal1.Text=str;
}

Related posts: http://forums.asp.net/p/981603/1257057.aspx#1257057


7        How to display images with a delay of five seconds

Ans-   7        How to display images with a delay of five seconds [top]

With this script you can see clickable images rotating in real-time without requiring banner rotat
reloads/refreshes .You should see a new banner rotating every 5 seconds:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>JavaScript</title>
<script language="javascript" type="text/javascript">
var image="";
var banners=0;
function loadbanners() {
if (banners==1)
{
image="images/AJAX.gif";
}
if (banners==2)
{
image="images/ASPDotNet.gif";
}
if (banners==3)
{
image=" images/MSDN.gif";
}
}
function cycle()
{
if (++banners > 3)
banners=1;
loadbanners();
document.getElementById("banner1").src =image;
window.setTimeout('cycle();',5000);
}
</script>
</head>
<body onload="cycle();">
<form id="form2" runat="server">
<div>
<img alt="" id="banner1" src="images/start.png" />
</div>
</form>
</body>
</html>

Related posts:

http://forums.asp.net/p/1213103/2147140.aspx


8        How to get browser screen settings and apply it to page controls
Ans-   8

How to get browser screen settings and apply it to page controls [top]

You can use the JavaScript, suppose the control type is <image>, see the code below:
<html>
<body>
<input onclick="resizeImage()"/>
<img src="http://www.microsoft.com/library/toolbar/3.0/images/banners/ms_masthead
>
<script language="JavaScript">
var winWidth = 0;
var winHeight = 0;
function resizeImage(){
var img=document.getElementById("testImage")
if (window.innerWidth)
winWidth = window.innerWidth;
else if ((document.body) && (document.body.clientWidth))
winWidth = document.body.clientWidth;
if (window.innerHeight)
winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
if (document.documentElement && document.documentElement.clientHeight &&
document.documentElement.clientWidth)
{
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}
img.width= winHeight;
img.width= winWidth;
}
</script>
</body>
</html>

Please remove the control style if it is present.

Related posts:http://forums.asp.net/p/1228180/2212987.aspx


9        How to clear the session when the user closes a window

Ans-  9        How to clear the session when the user closes a window [top]

Use the code,
<script type="text/javascript">
function window.onbeforeunload()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();

}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
{
xmlhttp.open("GET","exit.aspx",false);
xmlhttp.send();
}

}
</script>

Related posts: http://forums.asp.net/p/1237752/2255401.aspx


These are some tricks which have to use a fresher web gardener (developer)

Thursday, September 29, 2011

WCF vs Web service


WCF is a programming model and API. "WCF Service" implies an app that uses such programming model.
"Web Service" is an app that exposes an HTTP (REST (XML or JSON), SOAP or otherwise) interface.
You can build a Web service using WCF, but you can also build a Web service using other APIs or "stacks". Like PHP or Java, for example.
With WCF you can build web services but you can also build services that are not, "Webbish". For example you can build a service that accepts incoming binary requests over only a local pipe interface. It is still a service, but it is not a "web service" because it is not using web protocols (generally HTTP and XML).

Tuesday, July 5, 2011

Developers: just a few lines of JavaScript connects your site to Hotmail, Messenger, and SkyDrive


Today, developers almost always integrate multiple web platforms into their sites – Facebook, Twitter, Google, Hotmail, and more. With this in mind, we’ve tried to make it as easy as possible for developers to use our platform alongside others to connect their websites to Messenger, SkyDrive, and Hotmail. We’re achieving this goal by focusing on the following principles:
  1. All it takes is a few lines of JavaScript to unlock powerful integration. Utilize as few lines of script as is feasible to enable single sign-on and (with the user’s consent) to allow the app access to specific data from their Hotmail, Messenger, or SkyDrive account, all without requiring a single line of server-side code for the common scenarios.
  2. The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms. Ensure the API is familiar to web developers who are already using popular web platforms that perform similar tasks.
  3. Combining our APIs with other integrated services on a page shouldn’t cause clutter. Ensure it is straightforward and cost effective to use Messenger Connect in tandem with other web platform offerings without a negative impact on developers or end users.
These principles have informed the design of our new JavaScript library that developers can include in their websites to add single sign-on and integration with services like Hotmail, Messenger, and SkyDrive.
Let’s see some of these principles in action.

All it takes is a few lines of JavaScript to unlock powerful integration

The following self-contained code sample can be hosted on any website, and will render a Connect button as shown below, which a user can click to connect to the website and be greeted by their first name.
Connect button
In the following code sample, the client_id and redirect_uri should be replaced with the developer client ID you can obtain from our application settings site, and the URL of the HTML page, respectively.
<html><head>
<title>Greeting the User Test page</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
    <script type="text/javascript">
        var APPLICATION_CLIENT_ID = "YOUR CLIENT ID",
        REDIRECT_URL = "YOUR REDIRECT URL";
        WL.Event.subscribe("auth.login", onLogin);
        WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
        
        WL.ui({
            name: "signin",
            element: "signInButton",
            brand: "hotmail",
            type: "connect"
        });

        function greetUser(session) {
            var strGreeting = "";
            WL.api(
            {
                path: "me",
                method: "GET"
            },
            function (response) {
                if (!response.error) {
                    strGreeting = "Hi, " + response.first_name + "!"
                    document.getElementById("greeting").innerHTML = strGreeting;
                }
            });
        }
     
        function onLogin() {
            var session = WL.getSession();
            if (session) {
                greetUser(session);              
            }
        }
    </script>
</head>
<body>
    <p>Connect to display a welcome greeting.</p>
    <div id="greeting"></div>
    <div id="signInButton"></div>
</body>
</html>
There are a number of key concepts in the above example that I’ll briefly go over. The first step to using the JavaScript SDK is to include the wl.js script file on your webpage.
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
If your target audience doesn’t speak English, it is fairly straightforward to load versions of the JavaScript library that contain localized strings for dozens of languages.
After including the Messenger Connect JavaScript API, there are a few setup steps to link up components of the page with the JavaScript API, as shown below:
WL.Event.subscribe("auth.login", onLogin);
WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
The WL.Event.subscribe call above indicates that the onLogin() function should be invoked after the user has been successfully signed in. The WL.init call above is used to specify the application’s client ID, and the URL that the user should be redirected to after signing in which, for this example, is the current page:
WL.ui({
name: "signin",
element: "signInButton",
brand: "hotmail",
type: "connect"
});
The call to WL.ui is used to draw the Hotmail connect button. The code above attaches it to the DIV named “signInButton”. Once the user has signed in and granted consent to allow the page to access their data, the onLogin() function is invoked:
function onLogin() {
    var session = WL.getSession();
    if (session) {
        greetUser(session);              
    }
}
This function checks to see if a valid login session has been created and if so, invokes the greetUser() functionshown below:
function greetUser(session) {
    var strGreeting = "";
    WL.api(
    {
        path: "me",
        method: "GET"
    },
    function (response) {
        if (!response.error) {
            strGreeting = "Hi, " + response.first_name + "!"
            document.getElementById("greeting").innerHTML = strGreeting;
        }
    });
}
This method employs the work horse of the JavaScript SDK: WL.api. This function is used for making REST API requests. In this specific example, the request is made to fetch the user object for the current user using the “me” query. Once the user object is obtained, the webpage displays the user’s first name.

The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms

We want to ensure that we don’t add to the learning curve for developers, so we made sure that our JavaScript API would work in familiar ways for developers who integrate with multiple popular web platforms via JavaScript. For example, you may want to include social sharing for Facebook and Twitter alongside the ability to access SkyDrive photo albums and the ability to add events to your Hotmail calendar.
Common tasks in our JavaScript API such as signing in the user, accessing data from their contact list, viewing their photos, and showing the permission dialog all look and work very similarly to comparable scenarios in other common platforms like Facebook, Twitter, etc. This makes it very easy for any developer who is familiar with programming against these APIs to pick up and start integrating SkyDrive, Hotmail, and Messenger into their websites.

Combining Hotmail, Messenger, and SkyDrive with other integrated services on a page shouldn’t cause clutter

Websites typically don’t just offer integration with one service provider. It is common for a website to want to enable sharing to multiple sites like Facebook and Twitter, or allow users to upload their photos from Flickr, Facebook, and SkyDrive.
One of the challenges with supporting services that identity multiple providers on a website is what many have dubbed “the NASCAR effect,” which is when a site has so many logos from so many different providers that it looks a little like a race car with too many corporate sponsors. This practice often ends up confusing users due to the paradox of choice.
To help with this, we make it easy for your app or site to check if a customer uses one of our services before even offering the option to connect. Again, with just a few lines of JavaScript, you can tailor your connection and offer the right features to the right users – just use the WL.getLoginStatus function as follows:
WL.getLoginStatus(function (response) {
           if (response.status && response.status!= ‘Unknown’) {
               WL.ui({
                name: "signin",
                brand: "hotmail",
                type: "connect",
                element: "signInButton"
               });
           }else{
           /* draw sign-in button for other identity providers */ 
           }
       });
The code above checks to see if the customer uses one of our services, and if the status comes back as “Unknown,” it can then call some fallback code that draws the sign-in control of another identity provider such as Facebook, Twitter, or Google.
These are just a few examples of the ways we’ve improved our JavaScript API to simplify the developer experience. Keep the feedback coming, and we look forward to seeing more of your apps and sites connected to Hotmail, Messenger, and SkyDrive.

Saturday, June 18, 2011

Passing Values From JavaScript Functions to ASP.Net Functions in ASP.Net

Sometimes it necessry to pass values from a JavaScript function to an ASP.Net function. For example, we have a table and a GridView control on a page. In our table there are fields such as Employee Name, Age and Salary of the Employee and the condition is that only those employees should be added to the database whose age is greater than or equal to 25 and we want to carry out the validation process using JavaScript on a single click event of a button control and if the age is greater than or equal to 25 it should be added to the database and the corresponding records should be displayed in the GridView control.

So for beginning with this example we need to create a table named Emp in our database. I've created Test as a database. These are the following SQL queries.
create database Testuse Testcreate table Emp(EmpName varchar(20) not null,EmpAge int not null,EmpSalary money not null)
select * from Emp.

Now to begin with the ASP.Net code.

The following design needs to be done.


By default there are no records in the emp table; that's why the GridView will not display any records. Now fill the table with the required fields and then click on the save button. Like in the following:

PVasp1.gif
PVasp3.gif

Once you click on the save button a message will be ask if you want to add these details? If you click on ok it will check whether your age is greater than or equal to 25 or not. If it is not then it will display an error message or else it will add the details to the database and display it in GridView.
PVasp4.gif

In this case my age was 23 so it is not greater than 25 so it displayed the error message.
The following is the source code of our Default.aspx and Default.aspx.cs.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>   <script type="text/javascript">        function ValidateAge()
        {
            //var a=document.getElementById('<%= //TextBox2.ClientID%>').value; // or //var a=document.forms[0]["TextBox2"].value; 
           var a=document.forms[0]["TextBox2"].value; 
          var control=a;
           var x=confirm("Do you want to Add Details?"); 
           if(a>=29 && x==true)
          {
                   //get the client Id of the hidden field and store the value of a in it.                document.getElementById('<%= inpHide.ClientID%>').value=control;
                // document.all("Button1").click();//to Call asp Button click event from javascript.          }
          else          {
            alert("Your age should be greater than 29");
           //to open a new web page you can use the following command.         //window.open("Pop.aspx","List","scrollable =no,resizeable=no,width=400,height=250");          }
        }
   </script>
</head>
<
body>    <form id="f1" runat="server">    <div>        <table width="45%">            <tr>                <td>                    <asp:Label ID="Label1" runat="server" Text="Enter Name :"></asp:Label></td>                <td>                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Label ID="Label2" runat="server" Text="Enter Age :"></asp:Label></td>                <td>                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>                    <asp:HiddenField ID="inpHide" runat="server" />                </td>            </tr>            <tr>                <td style="height: 26px">                    <asp:Label ID="Label3" runat="server" Text="Enter Salary :"></asp:Label></td>                <td style="height: 26px">                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>            </tr>            <tr>                <td align="center" colspan="2">                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" OnClientClick="ValidateAge()" /></td>            </tr>        </table>    </div>        <asp:GridView ID="GridView1" runat="server">        </asp:GridView>    </form></body>
</
html>
Default.aspx.cs
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    string dbcon = ConfigurationManager.ConnectionStrings["AdvWorks"].ConnectionString;
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
            FillGrid();
    }
    public void FillGrid()
    {
        con = new SqlConnection(dbcon);
        da = new SqlDataAdapter("Select * from emp", con);
        ds = new DataSet();
        da.Fill(ds, "Emp");
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds.Tables["Emp"].DefaultView;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidAge", "ValidateAge()", true);        try        {
            int result = int.Parse(inpHide.Value);
            if (result>=25)
            {
                con = new SqlConnection(dbcon);
                cmd = new SqlCommand("Insert into Emp values('" + TextBox1.Text + "','" + TextBox2.Text + "','" +
TextBox3.Text + "')", con);
                con.Open();
                int rows = cmd.ExecuteNonQuery();
                if (rows > 0)
                {
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                    TextBox3.Text = "";
                    con.Close();
                    FillGrid();
                }
            }
        }
        catch (Exception e1)
        {
            con.Close();
        }
    }
}

Hope this will help you in your programming.