Showing posts with label ajax. Show all posts
Showing posts with label ajax. 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).

Sunday, June 26, 2011

Bulk Insert using GridView and Sql Server XML



Download source and store procedure script from here.


private void InsertEmptyRow()
{
DataTable dt = new DataTable();
DataRow dr = null;


dt.Columns.Add(new DataColumn("CustName", typeof(string)));
dt.Columns.Add(new DataColumn("CustPosition", typeof(string)));
dt.Columns.Add(new DataColumn("CustCity", typeof(string)));
dt.Columns.Add(new DataColumn("CustState", typeof(string)));


for (int i = 0; i < 5; i++)
     {
          dr = dt.NewRow(); dr["CustName"] = string.Empty;
          dr["CustPosition"] = string.Empty;
          dr["CustCity"] = string.Empty;
          dr["CustState"] = string.Empty; dt.Rows.Add(dr);
    }
   gvCustomer.DataSource = dt; gvCustomer.DataBind();
}



 As, you see above code I am creating five empty rows initially which is empty. This method I am calling at page load event. Note :- I am creating only five empty rows, you can create as much required for your bulk insert according to your requirement And one more difference between, Bulk update and bulk insert is that as we fetch all records for bulk update, so we don’t have empty rows, but in insert we have five empty rows. One more thing, Suppose we insert three rows and two rows empty what would happen ?. For that I am checking if name field is empty or not, else don’t insert.

 StringBuilder sb = new StringBuilder(); sb.Append("");
for (int i = 0; i < gvCustomer.Rows.Count; i++) 

      { 
      TextBox txtName = gvCustomer.Rows[i].FindControl("txtName") as TextBox; 
      TextBox txtPosition = gvCustomer.Rows[i].FindControl("txtPosition") as TextBox; 
      TextBox txtCity = gvCustomer.Rows[i].FindControl("txtCity") as TextBox;
      TextBox txtState = gvCustomer.Rows[i].FindControl("txtState") as TextBox;
      if(txtName.Text.Length != 0)
           sb.Append("");
}
sb.Append("
");


As you see, I am checking txtName if length is more then zero then insert record else skip it. As other insert detail is simple.


string conStr = WebConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("InsertCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@XMLCustomer", sb.ToString());


try
{
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}

lblError.Text = "Record(s) Inserted successfully";
lblError.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Error Occured";
lblError.ForeColor = System.Drawing.Color.Red;
}


Store procedure also simple, just direct insert from XML structure what it consist, this is also difference between bulk update as in which we check in where condition of customer id matches or not


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE PROCEDURE [dbo].[InsertCustomer]
(
@XMLCustomer XML
)
AS
BEGIN


INSERT INTO CUSTOMER
(CustName,CustPosition,CustCity,CustState)
SELECT
TempCustomer.Item.value('@Name', 'VARCHAR(50)'),
TempCustomer.Item.value('@Position', 'VARCHAR(50)'),
TempCustomer.Item.value('@City', 'VARCHAR(50)'),
TempCustomer.Item.value('@State', 'VARCHAR(50)')
FROM @XMLCustomer.nodes('/root/row') AS TempCustomer(Item)


RETURN 0
END


Note :- In bulk update, we are passing customer id also, here its not required as it is auto increment.

I hope you like this article about how to insert bulk records at a time. Like to have a feedback on this article.


Original article :- http://weblogs.asp.net/manojkdotnet/archive/2010/01/26/bulk-insert-using-gridview-and-sql-server-xml.aspx

Saturday, June 18, 2011

Observer Design Pattern in C#


Definition

The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995) says that the Observer design pattern should "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Purpose of Observer Pattern

The Observer pattern is to notify the interested observers about some change occurred. We can add more observers in runtime as well as remove them.

Example: We have a form to select the color. For each color change we need to update the entire application. There will be observers listening to the color change event for updating themselves.

Subject and Observers

The two important key terms in the pattern are Subject and Observer.

Subject is the object which holds the value and takes responsibility in notifying the observers when the value is changed. The subject could be a database change, property change or so.

We can conclude that the subject contains the following method implementations.
public interface ISubject{
    void Register(IObserver observer);
    void Unregister(IObserver observer);

    void Notify();
}


The Observer is the object listening to the subject's change. Basically it will be having its own updating/calculating routine that runs when get notified.
public interface IObserver{
    void ColorChanged(Color newColor);
}


In the above example, we are using an observer interface which has a ColorChanged method. So the interested observers should implement this interface to get notified.

There will be only one Subject and multiple number of Observers.

Registering and Unregistering

In the above interface, the observer can use the Register() method to get notified about changes . Anytime, it can unregister about notifications using the Unregister() method.

Notifying

The Notify() method will take care of calling the listening observers.

Associations

The Subject and Observer objects will be having a one-to-many association.

ObserverPatt1.gif

Using the Code

The associated code is having a main form, where the Subject would be a class named ColorSubject.
public class ColorSubject : ISubject{
    private Color _Color = Color.Blue;
    public Color Color
    {
        get { return _Color; }
        set
        {
            _Color = value;
            Notify();
        }
    }
    #region ISubject Members
    private HashSet<IObserver> _observers = new HashSet<IObserver>();
    public void Register(IObserver observer)
    {
        _observers.Add(observer);
    }
    public void Unregister(IObserver observer)
    {
        _observers.Remove(observer);
    }
    public void Notify()
    {
        _observers.ToList().ForEach(o => o.ColorChanged(Color));
    }
 
    #endregion}
The class implements ISubject interface and thus takes care of registering, unregistering and notifying the interested observers. All the observers keep registered with the ColorSubject object.

Screen Shot of Application

ObserverPatt2.gif

On running the associated project, we can see a color selector form, which acts as as the subject. All the other forms are observers listening to the ColorChanged event.

Note: The multicast event model in .Net can also be considered as an observer pattern. Here the interested parties register a method with the subject (might be a button) and whenever the button is clicked (an event) it invokes the registered observers (subscribers)

Conclusion

In this article we have seen what Observer pattern is and an example implementation.