Tuesday, December 29, 2009

Use HostelsClub Search Web-Service in ASP.NET

HostelsClub is one of the worlds larges search engine to search hotels, hostels, rooms and also provide booking of it. so if you want to integrate such a functionality in your website then you will have to take authentication from hostelclub and he will provide you Authentication id and password for Test (free of cost) and later you can upgrade to "Production" version (it will take some percentage in booking cost's profit).

HostelsClub provides you API Library and sample application in PHP to get connect with hostelsclub. But they don't have any API Library or application in ASP.NET. so if you want to do this, below sample can help you.

Through this sample you can PING the hostelsclub web-service search engine.


string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\ping.xml"));//this is your xml file which u want to send to hostelsclub for ping
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);

byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;

using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}

HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object

XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();


}
}

//===================PING.XML=======================
< ?xml version="1.0" encoding="UTF-8"? >
< OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd" TimeStamp="2009-12-28T11:43:43-05:00" Target="Test" Version="1.006" PrimaryLangID="en" EchoToken="1" >
< EchoData >Hello World< /EchoData >
< /OTA_PingRQ >

Read More

How to send/recive XML file through HTTP Post

If you want to send a XML file through HTTP using POST to any web service which may /may not build in .net. this example can help u:
string targetUri = "http://www.targeUrl.com";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));//xml file which you want to send
string formParameterName = "OTA_request";//request type
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);

byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;

using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}

HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object

XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();


}
}
Read More

Thursday, November 26, 2009

Set Cursor Position in TextBox.

If we want to set position of cursor to any character index in textbox by using following property:
TextBox1.SelectionStart= 2; //this will set cursor after 2nd character in textbox
Read More

Make textbox numeric only with negative value accept

Lets we want to create a textbox which should take only numeric (double/decimal) value and the value can also be in negative
Solution:
Private Sub txt_KeyPressWithNegative(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtothercharges.KeyPress, txtfreight.KeyPress
Dim decexist As Boolean = False

If (CType(sender, TextBox).Text.IndexOf(".") > 0) And e.KeyChar.Equals("."c) Then
decexist = True
End If
If (e.KeyChar = "-") Then
If (CType(sender, TextBox).Text.StartsWith("-") = True) Then
e.Handled = True
Exit Sub
Else
e.Handled = True
CType(sender, TextBox).Text = "-" & CType(sender, TextBox).Text
CType(sender, TextBox).SelectionStart = CType(sender, TextBox).Text.Length
Exit Sub
End If
End If
If (Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) And Not (e.KeyChar.Equals("."c))) Or decexist Then
e.Handled = True
End If
End Sub
Read More

Wednesday, November 25, 2009

Difference between <%# Bind(””) %> and <%# Eval(””) %>

EVal is one way binding, Bind is two way

If you bind a value using Eval, it is like a read only. You can only view the data.

If you bind a value using Bind, and if you do some change on the value it will reflect on the database also

so when ever you just want to show metter on grid that time you should use Eval and if you want that user should be able to change the content and that should be reflect in database then we should use Bind

Conclusion:
Bind is Two way binding so data will go in both way from Database to Application and Application to Database.
Eval is One way binding so data will go in one way only, which is database to Application
Read More

Monday, November 23, 2009

Difference between website project and webapplication project in VS2008

n the web**site** project, you typically work off a directory on your disk. There is no "project" file that defines the project's structure. Anything that's in that directory and any of its subdirectories automatically becomes part of your site - which can be a good or a bad thing.

A website project usually doesn't live inside a namespace, e.g. any code in your App_Code subdirectory will typically not have a namespace associated with it, which makes it sort of tricky and messy to use and reference from other places.

The web**application** project on the other hand is a real, true-blue project, complete with a project file and all. Anything that's in your project file will become part of your project - if you want to add something, you have to do so explicitly - it's not just automagically part of your project just because it's in your project directory. Again - this can be a good thing or a bad thing, depending on your style of development.

In my personal opinion, I would prefer the web application over the web site, mainly for the fact that I have more and more explicit control over what happens. A file doesn't just get added to my project (and potentially wreck havoc) just because it's lying around on disk. I have namespace and all - I have more control over what happens, when it happens
Read More

Why constructor not returns value

What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap. This space includes all members variables and the vtbl. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields. Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
Read More

Multiple Combobox with same datasource

One day Mr. Jodha asked me for solution for his prolem.
Problem:
-he used select query and got all data in datatable.
-then he made that datatable as datasource for two combobox which will show different
fields of that table
-but the proble is that when he select value from one combobox then the value of same record in second
combobox get selected.

and that is main problem.
Solution:Their exist very simple solution for this kind of problem
make a new bindingcontext for every combobox
combobox1.BindingContext = New BindingContext()
combobox2.BindingContext = New BindingContext()

When they are created, they inherit from the control that is hosting
them. Since you didn't specify it, it are all using the context of the
control/form that they are hosted in, and that's why when you change one
combo box, they all change.
Read More

Tuesday, November 17, 2009

Difference between JScript, JScript.NET and Managed JScrip

Difference between JScript, JScript.NET and Managed JScript
There are three different types of JScript engines that MS currently offers to the users. In this blog I would like to discuss more about the differences between them and would go into the reasoning for three different types sometime later.

JScript (or native JScript)
Read the intro about this in my previous blog here. The native JScript engine relies primarily on Microsoft's ActiveX/COM to provide much of its functionality. The core engine (jscript.dll) is installed as a Windows/IE component on a user machine and resides in “% SystemRoot%\system32” directory.

JScript.NET
JScript .NET is the next generation of an implementation by Microsoft of the ECMA 262 language. Combining the feature set of previous versions of JScript with the best features of class-based languages, JScript .NET includes the best of both worlds. The JScript.NET engine relies primarily on the .NET Framework to provide much of its functionality and runs on the Common Language Runtime.

Differences in JScript .NET when compared to (native) JScript include true compiled code (as it is converted to MSIL format for the CLR), typed and typeless variables, late- and early-binding, classes (with inheritance, function overloading, property accessors, and more), packages, cross-language support, and full access to the .NET Framework.

Being a part of the .NET Framework, JScript .NET’s core engine Microsoft.JScript.dll is installed at “% SystemRoot%\Microsoft.NET\Framework\vX.XXXXX”. The X.XXXXX specifies the .NET Framework version which is installed. Based on the .NET Framework version that is shipped/installed, the language is at times referred to as version 1.0/1.1/2.0 correspondingly. Also, the language at times is versioned based on Visual Studio’s major version it shipped with – like 8.0 for Visual studio 2005 with which .NET Framework 2.0 was shipped. So JScript.NET-2.0 and JScript.NET-8.0 both refer to the same version.

Managed JScript
Managed JScript is the name that is used for the implementation of the ECMA-262 language over the Dynamic Language Runtime to be delivered by Silverlight. It is the latest addition to the JScript family and was released in MIX07.

Unlike JScript .NET which is less dynamic than the original JScript but provides CLS compatibility, Managed JScript is designed on top of the DLR and provides the features needed for scripting scenarios. Implementation over DLR enables Managed JScript code to works well with not only C#, but also with IronPython , IronRuby, VB among other languages. The Managed JScript engine is installed by Silverlight 1.1 at “%ProgramFiles%\Microsoft Silverlight\Microsoft.JScript.Runtime.dll”.

The official release of Managed JScript is planned as a part of Microsoft Silverlight 1.1 (the Alpha Refresh release of the same can be downloaded from here) and next versions of ASP.NET.
Read More

VB.NET/C#.NET Communication with JavaScript

This article will help you to learn how to do communication between javascript and (vb.net/c#.net)

To start off, we'll start with a very simple example; all this will do is call a JavaScript function from VB.NET to display an alert with message 'Hello world'. Similarly, from the HTML page using JavaScript, we'll call a VB.NET function which will again display a messagebox with the message 'Hello world'. These are the steps you need to do to make it happen:

Calling JavaScript from VB.NET

In Visual Studio, create a new WinForms application, name it anything you like.
Add an import statement like Imports System.Security.Permissions in your form1 (main form).
Add a couple of attributes to form1, like:

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class Form1
End Class
All they do is tell the .NET Framework that we want fulltrust and make the class visible to COM so this class is visible to JavaScript.

Add a WebBrowser control to the form and set its url property to c:\temp\mypage.html (just an example path, you should set it to the HTML page you'll be using).
Add a Button control on the form, and on its click handler, write this code:

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Me.WebBrowser1.Document.InvokeScript("showJavascriptHelloWorld")
End Sub
In your HTML page, add this code:

<script type="text/javascript">
function showJavascriptHelloWorld() {
alert("Hello world");
}
</script>
Calling VB.NET from JavaScript

Continuing with the last project, add the following lines of code in your form1:

Public Sub showVbHelloWorld()
MsgBox("Hello world")
End Sub
In your form1 load event, add this line of code:

Me.WebBrowser1.ObjectForScripting = Me
What this line does is, it exposes your form1 class to the JavaScript on the HTML page. You could expose any class as long as you make it visible to COM and set its permission to fulltrust.

In your HTML page, add a Button, and on its click event, call this function:

<script type="text/javascript">
function showVbHelloWorld() {
window.external.showVbHelloWorld();
}
</script>
That is it. We've accomplished two way communication. But, most developers must have seen similar examples on MSDN or in different forums. This is just the starting point, our next step is to pass arguments to the functions.
Passing arguments to functions

Passing arguments to JavaScript functions

To pass arguments to a JavaScript function, you need to simply declare functions in your JavaScript code like you normally do. In your VB.NET code, you can pass a single argument like:


Me.WebBrowser1.Document.InvokeScript("javascriptFunction", _
New String() {"Message from vb.net to javascript"})
If you want to pass more than one variable, you can simply add it like:


Me.WebBrowser1.Document.InvokeScript("javascriptFunction", _
New String() {"Message from vb.net to javascript", _
"Argument 1","Argument 2" , "Argument n"})
So far, I am only passing string type arguments, but you are not restricted to simple strings. You can easily pass string, integers, booleans without any special additions. E.g.:


Me.WebBrowser1.Document.InvokeScript("javascriptFunction", _
New Object() {"Message from vb.net to javascript",200,true})
Arguments are not restricted to simple types, you can pass any type you want. The only restriction is you'll have to make it COM visible. In this example, I am going to pass a Person object to JavaScript. To make it work, I'll follow these steps:

Create a class called Person, like:

<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class Person
Public Sub New(ByVal firstName As String, _
ByVal lastName As String, ByVal age As Integer)
Me._firstName = firstName
Me._lastName = lastName
Me._age = age
End Sub

Private _firstName As String
Private _lastName As String
Private _age As Integer

Public Function getFirstName() As String
Return Me._firstName
End Function

Public Function getLastName() As String
Return Me._lastName
End Function

Public Function getAge() As Integer
Return Me._age
End Function

End Class
In your form1, call it like this:

Me.WebBrowser1.Document.InvokeScript("sendPerson", _
New Person() {New Person("John", "Smith", 37)})
In your JavaScript, you can use the Person object like:

<script type="text/javascript">
function sendPerson(person) {
alert("First Name:" + person.getFirstName() +
"Last Name:" + person.getLastName() +
"Age:" + person.getAge());
}
</script>
Most developers should be aware of this, but I must point out that when you pass your object to JavaScript, it is fully exposed (all public methods/properties), and JavaScript can modify your object. As an example, if I add this function in my Person class:

Public Sub setFirstName(ByVal firstName as String)
Me._firstName=firstName
End Sub
Now, in your JavaScript, modify the function sendPerson like:


function sendPerson(person) {
person.setFirstName('Roger');
}
After this call, your person will have first name as 'Roger' instead of 'John'. To avoid this situation, there are two options. Make setFristName private/protected, but that means you won't be able to access this method from VB.NET. The better solution is to add an attribute to setFirstName, like:


<System.Runtime.InteropServices.ComVisibleAttribute(False)> _
Public Sub setFirstName(ByVal firstName as String)
Me._firstName=firstName
End Sub
Now, your function is visible in your VB.NET code, but JavaScript won't be able to call it, and as a result modify it in case you don't want to expose a particular method to JavaScript for any reason.

Passing arrays to JavaScript functions (unsuccessful attempt)

OK, passing arrays to JavaScript. Some developers might think why is it a separate section. The reason is it is not straightforward to pass arrays as most people would think. If you try this code:


Dim firstNames() As String = {"John", "Richard", "Micheal"}
Dim lastNames() As String = {"Smith", "Stone", "Day"}
Me.WebBrowser1.Document.InvokeScript("passNameArrays", _
New Object() {firstNames, lastNames})
In your JavaScript, if you try doing this:


<script type="text/javascript">
function passNameArrays(firstNames, lastNames) {
alert(firstNames[0]);
}
</script>
you'll get a JavaScript error (if error messages are enabled).

So, why didn't that work, you must be asking. The reason is pretty simple. You can only pass simple types, and arrays are not simple types. You'll have to put a workaround to pass arrays.

Passing arrays to JavaScript functions (successful attempt)

OK, it is understood that we can't pass arrays to JavaScript (at least, I am not aware of a way for passing them; if anyone knows a method, they are welcome to correct me). The simplest workaround is to create a type which wraps your array and passes that type instead of a simple array. E.g., you could wrap your array of strings like:


<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class myArr
Implements IList(Of String)

Private _list As New List(Of String)

Public Sub New()

End Sub
Public Sub New(ByVal arr() As String)
For Each Str As String In arr
Me._list.Add(Str)
Next
End Sub

Public Sub Add(ByVal item As String) _
Implements System.Collections.Generic.ICollection(Of String).Add
Me._list.Add(item)
End Sub

Public Sub Clear() _
Implements System.Collections.Generic.ICollection(Of String).Clear
Me._list.Clear()
End Sub

Public Function Contains(ByVal item As String) As Boolean _
Implements System.Collections.Generic.ICollection(Of String).Contains
Return _list.Contains(item)
End Function

Public Sub CopyTo(ByVal array() As String, ByVal arrayIndex As Integer) _
Implements System.Collections.Generic.ICollection(Of String).CopyTo

End Sub

Public ReadOnly Property Count() As Integer _
Implements System.Collections.Generic.ICollection(Of String).Count
Get
Return Me._list.Count
End Get
End Property

'Rest of the class method needs to be implemented here
End Class
And now, if we take on the example from the previous section where we unsuccessfully tried to pass an array of first and last names, let's give it another try:


Dim firstNames As New myArr(New String() {"John", "Richard", "Micheal"})
Dim lastNames As New myArr(New String() {"Smith", "Stone", "Day"})
Me.WebBrowser1.Document.InvokeScript("passNameArrays", _
New Object() {firstNames, lastNames})
In your JavaScript, you could use it like:


<script type="text/javascript">

function passNameArrays(firstNames, lastNames) {
alert(firstNames.item(0));
}
</script>
And now, you should see an alert with the text "John". All the rest of the functions like count, indexOf etc. are available from JavaScript.

I have implemented the class as IList(Of String), but you could implement it as IList(Of Object) and pass any type of array (as long as they are COM visible).

An important fact to remember

One important fact which most developers should be aware of is that you are not bound to pass a set number of arguments to the JavaScript function. You could pass any number of arguments to the JavaScript function, e.g., our last JavaScript function could be written and used like this:


<script type="text/javascript">
function passNameArrays() {
alert(arguments[0].item(0));
}
</script>
Passing arguments from JavaScript to VB.NET functions

We have spend enough time passing arguments to JavaScript. Let's move on to the next step, passing arguments to VB.NET functions. You could simply do it like this in JavaScript:


<script type="text/javascript">
function sendPerson() {
window.external.sendPerson("John", "Smith", 26);
}
</script>
and on your VB.NET side, you could define the function to receive these arguments, like:


Public Sub sendPerson(ByVal firstName As String, _
ByVal lastName As String, ByVal age As Integer)
MsgBox(String.Format("First name: {0} Last Name: {1} Age: {2}", _
firstName, lastName, age))
End Sub
and you are done.

Again, you are not bound to pass simple types as arguments. You could pass JavaScript objects as arguments, if required. Take a look at the last example in a different way. The JavaScript will be:


<script type="text/javascript">
function sendPerson() {
var person = new Array();
person["firstName"] = "John";
person["lastName"] = "Smith";
person["age"] = 26;
window.external.sendPerson(person );
}
</script>
and you can use the Person object on the VB.NET side, like:


Public Sub sendPerson(ByVal person As Object)
MsgBox(String.Format("First name: {0} Last Name: {1} Age: {2}", _
person.firstName, person.lastName, person.age))
End Sub
similar example but different method to achieve the same result.

Returning values from functions

Returning a value from a JavaScript function to VB.NET

What about returning a value from functions? Simple, you could easily get the value from a JavaScript function; e.g., if we call this line in VB.NET:


Dim str As String = _
Me.WebBrowser1.Document.InvokeScript("getJavascriptString")
MsgBox(str)
and in JavaScript, we could write the function to return a string like:


<script type="text/javascript">
function getJavascriptString() {
return "String returned from javascript";
}
</script>
Again, you are not bound to simple types. You can return your custom JavaScript objects very easily. E.g., let's create a Person class in JavaScript this time, and write a function which will return the Person object back to VB.NET.


<script type="text/javascript">
function person(name,age) {
this.name = name;
this.age = age;
this.getName = function() { return this.name; }
this.getAge = function() { return this.age; }
}

function getPersonObject() {

myPerson = new person("Chris McCreadie", 48);
return myPerson;
}
</script>
On your VB.NET side, you can do something like this (must warn you the code below is not going to work):


Dim jsPerson As Object = Me.WebBrowser1.Document.InvokeScript("getPersonObject")
MsgBox(String.Format("Name: {0} Age:{1}", jsPerson.getName(), jsPerson.getAge()))
If you try the above code, the first line will run fine, but at runtime (as it is late binding), you'll receive an exception on the second line. If you are asking why it doesn't work, frankly speaking, I don't know, but if you know the answer, you are welcome to explain it.

So, what is the solution? The solution is pretty simple. You take help from System.Reflection, and modify the above code to something like this:


Dim jsPerson As Object = Me.WebBrowser1.Document.InvokeScript("getPersonObject")
Dim jsPersonType As Type = jsPerson.GetType()
Dim name As String = jsPersonType.InvokeMember("getName", _
Reflection.BindingFlags.InvokeMethod, Nothing, jsPerson, Nothing)
Dim age As Integer = jsPersonType.InvokeMember("getAge", _
Reflection.BindingFlags.InvokeMethod, Nothing, jsPerson, Nothing)
MsgBox(String.Format("Name: {0} Age: {1}", name, age))
The above code should work perfectly and give you the desired results. I won't go in to the details of explaining the InvokeMember function, there's plenty of help on MSDN and Google for that.

What's the next step now? We can access simple types and complex (custom) types. Can we access the objects (HTML buttons, text fields, div) on the page? Yes, we can. And surprisingly, they are easier to access. Let's pull our sleeves and write a simple function in JavaScript which will return a Button object which happens to be on the page.


<script type="text/javascript">
function getHtmlButton() {
//assuming there's a button with id myBtn on the page
return document.getElementById('myBtn');
}
</script>
Now, on the VB.NET side, we could do something like this:


Dim htmlButton As Object = Me.WebBrowser1.Document.InvokeScript("getHtmlButton")
htmlButton.value = "Set from vb.net"
The above code will change the button text to "Set from vb.net". We could slightly improve the above code by doing a couple of things:

Add a reference in your project for "Microsoft HTML Object Library", can be found under the COM section.
And now, change the first line of the above code to:

Dim htmlButton As mshtml.HTMLInputElement = _
Me.WebBrowser1.Document.InvokeScript("getHtmlButton")
What these changes will do is, firstly, it will make our htmlButton object a strongly type one instead of the Object type. Secondly, you'll get intellisence from Visual Studio, and it will make your job easier in trying to figure out what method/properties to call/set on the htmlButton.

I would give another example just to show the possibilities.


'assuming JavaScript got a function which will return a div on the page
Dim htmlDiv As mshtml.HTMLDivElement = _
Me.WebBrowser1.Document.InvokeScript("getHtmlDiv")
htmlDiv.style.background = "Red"
Most of the types in MSHTML are self explanatory, and you can guess what will be converted from the HTML to the MSHTML type. But if you can't tell, here's a small tip: Set your variable to type Object initially, and once you have received an HTML object from JavaScript (assuming you've setup a break point), hover your mouse over it and Visual studio will let you know the exact type, or alternatively, you can look in the Autos or Local window in Visual Studio.

A tip: All (most) developers know this, but if anyone doesn't, here is a little tip if you want more than one value back from JavaScript. If you are passing objects, JavaScript can modify those objects. If we take the example where we created a list(of String) in VB.NET and if we need to get the list of first names and last names from JavaScript, we could do something like this:


Dim firstNames As New myArr()
Dim lastNames As New myArr()
Me.WebBrowser1.Document.InvokeScript("getNames", _
New Object() {firstNames, lastNames})
and on the JavaScript side, we could do something like:


function getNames(firstNames, lastNames) {
firstNames.add("John");
firstNames.add("Chris");
lastNames.add("Martin");
lastNames.add("Churn");
}
and as a result, we could easily get multiple values back from JavaScript. I agree this is not the best example, but I hope you get the concept I am trying to explain.

Returning a value from a VB.NET function to JavaScript

I am sure I don't need this section, but just for completeness, I'll give an example here. On the VB.NET side, we could write a simple function to return the current date and time like:


Public Function getCurrentTime() As DateTime
Return DateTime.Now
End Function
and on the JavaScript side:


function getCurrentTime() {
alert(window.external.getCurrentTime());
}
Ask me a question :-) I know you must be asking a question right now. Have I done some mistake or submitted an incomplete code? How can I return a DateTime from VB.NET when it is not a simple type and I haven't added any wrapper class around it? The answer is it's a fully working code, and even though DateTime is not a simple type, it's one of the special types which automatically get converted to the JavaScript Date type. Every other concept in returning values from VB.NET is explained above, and I don't think any further explanation is needed. You can return string, integer, boolean, datetime, without any special arrangements, but for other types, you'll have to expose the type/class to COM for it to be visible.

Exception handling

So far, all the examples I have done (for simplicity), I haven't done any exception handling, but that doesn't mean in a production code you'll be doing this. Every call from one platform to the other must be done with an assumption that it wont' work and something at some point will go wrong. As JavaScript is an interpreted language, even if there's some mistake in the script, it might not be visible until runtime when you call JavaScript from your VB.NET code. Similarly, when you call VB.NET from JavaScript, if an exception is thrown from the VB.NET function, it won't crash your program/exe but will be thrown back to the JavaScript and you'll get a JavaScript error dialog from Internet explorer.
Read More

Learn Object Oriented JavaScript

Learn Basic JavaScript If you are beginner.

This Article is for Learning Advanced JavaScript and how to use it in Asp.net

ASP.NET and Visual Studio 7.0 are making important contributions to the improvement of the web development experience. Unfortunately, there is also a tendency created among developers to limit their interaction with JavaScript. Clearly JavaScript is valuable for adding client-side functionality to web pages. However ASP.NET programming models suggest that developers produce page layout while emitting client-side JavaScript from ASP.NET controls. As a consequence, this model tends to limit JavaScript to procedural adjuncts. This is rather unfortunate because it severely limits the power of an object-oriented scripting language that developers can use to write rich and reusable client-side components.

There are several reasons why JavaScript object-oriented capabilities are not fully utilized:

The tendency of client-side operations to be discrete favoring procedures.
ASP.NET programming model for its controls suggests limiting JavaScript to functional adjuncts.
Legacy JavaScript lacked key features such as exception handling and inner functions.
Text books on JavaScript often de-emphasize its support for object-oriented programming.
JavaScript does not formally support class inheritance like conventional OOP languages.
But writing JavaScript procedurally creates another set of undesirable conditions:

Task duplication due to the decoupling of data and functions.
Tendency to use complex array patterns to simulate abstract data types.
Increases the impact risk and side effects of code modifications.
Complicates auditing of functions thereby diminishing reusability.
The consequential effect is reduced performance.
We can enhance our scripts and eliminate these problems by writing JavaScript in an object-oriented fashion. JavaScript possess all the familiar object-oriented programming tenets, by its ability to define new object types and extend them through its prototype property. Prototypes serve as templates for an entire class of abstract data types. Therefore prototype properties are shared by all instantiated objects of the class. While this is a powerful and expressive type of inheritance model, what's missing is the customary class inheritance support that is familiar to programmers of conventional object-oriented languages.

Writing object-oriented JavaScript will be presented in a series of three articles. The first installment provides background on how JavaScript supports the main principles of object-oriented programming. Part two demonstrates how JavaScript constructs can be used to build a class inheritance framework and write scripts supporting a JavaScript class hierarchy. The third and final installment shows how to use the JavaScript class framework to build object-oriented client-side abstractions of ASP.NET user controls.

It is the aim of this series to introduce an alternate programming strategy and style that fully utilities JavaScript capabilities, and then elevates JavaScript from its typical junior partner role (reinforced by the ASP.NET programming model), into full domain partnership with ASP.NET. The result will enable developers to write rich client-side scripts.

Principles of Object-Oriented Programming in JavaScript

Abstract Data Types

Abstract data types are descriptions and representations of a real-world construct. Many languages support aggregation of disparate intrinsic data types to represent some real world construct. For example in "C" the struct keyword denotes such an aggregation. However an abstract data type is more than just an aggregation of disparate data types. An abstract data type also defines behaviors represented by the abstraction. In many object-oriented languages the combination of data and its associated behaviors denotes a class. Languages such as C++, Java, and C# provide the class keyword to identify abstract data types.

While JavaScript reserves the class keyword it does not support defining classes in the same manner as conventional OOP languages. In JavaScript functions are used as object descriptors and all functions are actually JavaScript objects. Thus in JavaScript, classes are function definitions. The code below illustrates how the simplest class is defined in JavaScript -- the empty class MyClass:


function MyClass() {}
Figure 1. Empty class definition
Using the JavaScript new operator defines myClassObj as an object instance of the type MyClass:


var myClassObj = new MyClass();
Figure 2. Object instantiation
Notice that the function keyword is overloaded and serves as both the constructor function for objects as well as identifying procedural functions:


var result = MyClass();
Figure 3. MyClass used as a procedural function
The difference between MyClass being interpreted as a constructor or as a procedure is the new operator. The new operator instantiates an object of class MyClass calling the constructor function, while in the second call a procedural call is made to the function MyClass expecting a return result.

MyClass defined in figure 1 is an empty class having no assigned data or behavior. JavaScript can dynamically add properties to the instantiated objects of MyClass:


var myClassObj = new MyClass();
myClassObj.myData = 5;
myClassObj.myString = "Hello World";
alert( myClassObj.myData ); // displays: 5

alert( myClassObj.myString ); // displays: "Hello World"

Figure 4. Dynamically assigning object properties
The problem however is that only the instance of MyClass referenced by myClassObj possesses the additional data properties. Subsequent instances will not have any properties. What is needed is a way to defined properties to all instances of MyClass. Using the this keyword in the constructor function data properties are now defined on all instances of MyClass:


function MyClass()
{
this.myData = 5;
this.myString = "Hello World";
}

var myClassObj1 = new MyClass();
var myClassObj2 = new MyClass();
myClassObj1.myData = 10;
myClassObj1.myString = "Obj1: Hello World";
myClassObj2.myData = 20;
myClassObj2.myString = "Obj2: Hello World";
alert( myClassObj1.myData ); // displays: 10

alert( myClassObj1.myString ); // displays: "Obj1: Hello World"

alert( myClassObj2.myData ); // displays: 20

alert( myClassObj2.myString ); // displays: "Obj2: Hello World"

Figure 5. Defining data properties to all instances of the class
MyClass is still incomplete because there are no behaviors assigned to it. To add methods to MyClass, properties that reference functions are added to MyClass:


function MyClass()
{
this.myData = 5;
this.myString = "Hello World";
this.ShowData = DisplayData;
this.ShowString = DisplayString;
}

function DisplayData()
{
alert( this.myData );
}

function DisplayString()
{
alert( this.myString );
}

var myClassObj1 = new MyClass();
var myClassObj2 = new MyClass();
myClassObj1.myData = 10;
myClassObj1.myString = "Obj1: Hello World";
myClassObj2.myData = 20;
myClassObj2.myString = "Obj2: Hello World";
myClassObj1.ShowData(); // displays: 10

myClassObj1.ShowString(); // displays: "Obj1: Hello World"

myClassObj2.ShowData(); // displays: 20

myClassObj2.ShowString(); // displays: "Obj2: Hello World"

Figure 6. Defining data and methods to all instances of the class
The figure above defines a complete abstract data types or class in JavaScript. MyClass now defines a concrete type possessing data and associated behaviors.

Encapsulation

Using MyClass as defined above permits accessibility of its internal data representation as well as having its methods and variable names global in scope increasing the risk of name collisions. Encapsulation supports data hiding and the concept of viewing objects as self-contained entities providing services to consumers.


function MyClass()
{
var m_data = 5;
var m_text = "Hello World";
this.SetData = SetData;
this.SetText = SetText;
this.ShowData = DisplayData;
this.ShowText = DisplayText;

function DisplayData()
{
alert( m_data );
}

function DisplayText()
{
alert( m_text );
return;
}

function SetData( myVal )
{
m_data = myVal;
}

function SetText( myText )
{
m_text = myText;
}
}

var myClassObj1 = new MyClass();
var myClassObj2 = new MyClass();
myClassObj1.SetData( 10 );
myClassObj1.SetText( "Obj1: Hello World" );
myClassObj2.SetData( 20 );
myClassObj2.SetText( "Obj2: Hello World" );
myClassObj1.ShowData(); // displays: 10

myClassObj1.ShowText(); // displays: "Obj1: Hello World"

myClassObj2.ShowData(); // displays: 20

myClassObj2.ShowText(); // displays: "Obj2: Hello World"

Figure 7. Dynamically assigning properties to all object instances
JavaScript treats a class definition as a function definition and uses the var keyword to define local variables. Therefore var indicates that m_data is a local or "private" variable of MyClass. In figure 6, var was not used and thus, MyData is global in scope or "public". The var keyword is how encapsulation is specified in JavaScript.

Inheritance

JavaScript supports inheritance through the use of object prototypes. A prototype is a template of properties that is shared by all instances of the object type. Thus instances of object types "inherit" the values of its prototype property. In JavaScript, all object types have a prototype property that can be both extended and inherited.

In the example below, the Shape prototype object defines three properties, GetArea, GetPerimeter, and Draw, that reference the functions, Shape_GetArea, Shape_GetParameter, and Shape_Draw. Every instance of Shape inherits the prototype allowing them to call the Shape functions through the properties.

To achieve inheritance in JavaScript, the prototype of a previously defined object type is copied into the prototype of the derived object type. The Shape prototype below is copied into prototype of the derived Circle and Rectangle object types. Then the Draw property is overridden supplying the proper the function reference for the new class.


Shape.prototype.GetArea = Shape_GetArea;
Shape.prototype.GetParameter = Shape_GetParameter;
Shape.prototype.Draw = Shape_Draw;

function Shape()
{
}

function Shape_GetArea()
{
return this.area;
}

function Shape_GetParameter()
{
return this.parameter;
}

function Shape_Draw()
{
alert( "Drawing generic shape" );
}

Circle.prototype = new Shape();
Circle.prototype.constructor = Circle;
Circle.prototype.baseClass = Shape.prototype.constructor;
Circle.prototype.Draw = Circle_Draw;

function Circle( r )

{
this.area = Math.PI * r * r;
this.parameter = 2 * Math.PI * r;
}

function Circle_Draw()
{
alert( "Drawing circle" );
}

Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;

function Rectangle( x, y )

{
this.area = x * y;
this.parameter = 2 * x + 2 * y;
}

Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.baseClass = Shape.prototype.constructor;
Rectangle.prototype.Draw = Rectangle_Draw;

function Rectangle( x, y )

{
this.area = x * y;
this.parameter = 2 * x + 2 * y;
}

function Rectangle_Draw()
{
alert( "Drawing rectangle" );
}

var circle = new Circle( 10 );
var rectangle = new Rectangle( 10, 20 );

alert( "Circle base class = " + circle.baseClass );
alert( "Circle area = " + circle.GetArea() );
alert( "Circle parameter = " + circle.GetParameter() );
circle.Draw();

alert( "Rectangle base class = " + rectangle.baseClass );
alert( "Rectangle area = " + rectangle.GetArea() );
alert( " Rectangle parameter = " + rectangle.GetParameter() );
rectangle.Draw();
Figure 8. JavaScript Inheritance
Circle and Rectangle prototypes are assigned to the prototype of the Shape class through an object instance thereby "inheriting" the methods assigned to the prototype array of the Shape class. An instance of the Shape class is necessary to create a copy of the Shape prototype array. This permits overriding of the Shape methods yet preserving the original prototype array associated to all Shape objects.

Both the Circle and Shape classes extend the Shape class by overriding Draw method supplying its own respective implementation while inheriting the Shape implementation of the GetArea and GetParameter methods:


var circle = new Circle( 10 );
var rectandle = new Rectangle( 10, 20 );
alert( "Circle base class = " + circle.baseClass );
// Alert: Circle base class = <STRING constructor Shape of output>

alert( "Circle area = " + circle.GetArea() );
// Alert: Circle area = 314.1592653589793

alert( "Circle parameter = " + circle.GetParameter() );
// Alert: Circle parameter = 62.83185307179586

circle.Draw();
// Alert: Drawing circle


alert( "Rectangle base class = " + rectangle.baseClass );
// Alert: Rectangle base class = <STRING constructor Shape of output>

alert( "Rectangle area = " + rectangle.GetArea() );
// Alert: Rectangle area = 200

alert( "Rectangle parameter = " + rectangle.GetParameter() );
// Alert: Rectangle parameter = 60

rectangle.Draw();
// Alert: Drawing rectangle

Figure 9. Results of JavaScript Inheritance
Polymorphism

Polymorphism defines disparate behaviors and actions by objects to the same function invocation. The Draw property of Shape, Circle, and Rectangle object types is polymorphic. The Draw property invokes a different function depending upon its object type.


var shape = new Shape();
var circle = new Circle( 10 );
var rectandle = new Rectangle( 10, 20 );
shape.Draw();
// Alert: Drawing generic shape

circle.Draw();
// Alert: Drawing circle

rectangle.Draw();
// Alert: Drawing rectangle
Read More

Basic JavaScripts

As we all know in web application development the javascript is very important so lets learn some basic javaScript.


< html >
< head >
< title >This is a JavaScript example< /title >
< script language="JavaScript" >
< !--
document.write("Hello World!");
//-- >

< /script >
< /head >
< body > Hi, man! < /body >
< /html >
Usually, JavaScript code starts with the tag < script language="JavaScript" > and ends with the tag < /script >. The code placed between < head > and < /head >. Sometimes, people embed the code in the < body > tags:


< html >
< head >< /head >
< body >
< script >
.....// The code embedded in the < body > tags.
< /script >
< /body >
< /html >
Why do we place JavaScript code inside comment fields < !-- and //-- >? It's for ensuring that the Script is not displayed by old browsers that do not support JavaScript. This is optional, but considered good practice. The LANGUAGE attribute also is optional, but recommended. You may specify a particular version of JavaScript:


< script language="JavaScript1.2" >
You can use another attribute SRC to include an external file containing JavaScript code:


< script language="JavaScript" src="hello.js" >< /script >
For example, shown below is the code of the external file hello.js:


document.write("Hello World!")
The external file is simply a text file containing JavaScript code with the file name extension ".js". Note:

Including an external file only functions reliably across platforms in the version 4 browsers.
The code can't include tags < script language... > and < /script >, or you will get an error message.


write and writeln

In order to output text in JavaScript you must use write() or writeln(). Here's an example:


< HTML >
< HEAD >
< TITLE > Welcome to my site< /TITLE >< /HEAD >
< BODY >
< SCRIPT LANGUAGE="JAVASCRIPT" >
< !--
document.write("Welcome to my site!");
// -- >

< /SCRIPT >
< /BODY >
< /HTML >
Note: the document object write is in lowercase as JavaScript is case sensitive. The difference between write and writeln is: write just outputs a text, writeln outputs the text and a line break.



Document object

The document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScript code:


document.write("Hi there.")
In this code, document is the object. write is the method of this object. Let's have a look at some of the other methods that the document object possesses.

lastModified
You can always include the last update date on your page by using the following code:

< script language="JavaScript" >
document.write("This page created by John N. Last update:" + document.lastModified);
< /script >
All you need to do here is use the lastModified property of the document. Notice that we used + to put together This page created by John N. Last update: and document.lastModified.

bgColor and fgColor
Lets try playing around with bgColor and fgColor:

< script >
document.bgColor="black"
document.fgColor="#336699"
< /script >


Message Box

alert
There are three message boxes: alert, confirm, and prompt. Let's look at the first one:

< body >
< script >
window.alert("Welcome to my site!")
< /script >
< /body >
You can put whatever you want inside the quotation marks.

confirm
An example for confirm box:

window.confirm("Are you sure you want to quit?")
prompt
Prompt box is used to allow a user to enter something according the promotion:

window.prompt("please enter user name")
In all our examples above, we wrote the box methods as window.alert(). Actually, we could simply write the following instead as:


alert()
confirm()
prompt()


Variables and Conditions

Let's see an example:


< script >
var x=window.confirm("Are you sure you want to quit")

if (x)
window.alert("Thank you.")
else
window.alert("Good choice.")
< /script >
There are several concepts that we should know. First of all, var x= is a variable declaration. If you want to create a variable, you must declare the variable using the var statement. x will get the result, namely, true or false. Then we use a condition statement if else to give the script the ability to choose between two paths, depending on this result (condition for the following action). If the result is true (the user clicked "ok"), "Thank you" appears in the window box. If the result is false (the user clicked "cancel"), "Good choice" appears in the window box instead. So we can make more complex boxes using var, if and those basic methods.


< script >
var y=window.prompt("please enter your name")
window.alert(y)
< /script >
Another example:


< html >< head >
< script >
var x=confirm("Are you sure you want to quit?")
if (!x)
window.location="http://www.yahoo.com"
< /script >
< /head >
< body >
Welcome to my website!.
< /body >< /html >
If you click "cancel", it will take you to yahoo, and clicking ok will continue with the loading of the current page "Welcome to my website!". Note:if (!x)means: if click "cancel". In JavaScript, the exclamation mark ! means: "none".



Function

Functions are chunks of code.Let's create a simple function:


function test()
{
document.write("Hello can you see me?")
}
Note that if only this were within your < script >< /script > tags, you will not see "Hello can you see me?" on your screen because functions are not executed by themselves until you call upon them. So we should do something:


function test()
{
document.write("Hello can you see me?")
}
test()
Last linetest() calls the function, now you will see the words "Hello can you see me?".



Event handler

What are event handlers? They can be considered as triggers that execute JavaScript when something happens, such as click or move your mouse over a link, submit a form etc.

onClick
onClick handlers execute something only when users click on buttons, links, etc. Let's see an example:

< script >
function ss()
{
alert("Thank you!")
}
< /script >
< form >
< input type="button" value="Click here" onclick="ss()" >
< /form >
The function ss() is invoked when the user clicks the button. Note: Event handlers are not added inside the < script > tags, but rather, inside the html tags.

onLoad
The onload event handler is used to call the execution of JavaScript after loading:

< body onload="ss()" >
< frameset onload="ss()" >
< img src="whatever.gif" onload="ss()" >
onMouseover,onMouseout
These handlers are used exclusively with links.

< a href="#" onMouseOver="document.write('Hi, nice to see you!" >Over Here!< /a >
< a href="#" onMouseOut="alert('Good try!')" >Get Out Here!< /a >
onUnload
onunload executes JavaScript while someone leaves the page. For example to thank users.

< body onunload="alert('Thank you for visiting us. See you soon')" >
Handle multiple actions
How do you have an event handler call multiple functions/statements? That's simple. You just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:

< form >
< input type="button" value="Click here!" onClick="alert('Thanks
for visiting my site!');window.location='http://www.yahoo.com'" >
< /form >


Form

Let's say you have a form like this:


< form name="aa" >
< input type="text" size="10" value="" name="bb" >< br >
< input type="button"
value="Click Here"onclick="alert(document.aa.bb.value)" >
< /form >
Notice that we gave the names to the form and the element. So JavaScript can gain access to them.

onBlur
If you want to get information from users and want to check each element (ie: user name, password, email) individually, and alert the user to correct the wrong input before moving on, you can use onBlur. Let's see how onblur works:

< html >< head >< script >
function emailchk()
{
var x=document.feedback.email.value
if (x.indexOf("@")==-1)
{
alert("It seems you entered an invalid email address.")
document.feedback.email.focus()
}
}
< /script >< /head >< body >

< form
name="feedback" >
Email:< input type="text" size="20" name="email"
onblur="emailchk()" >< br >
Comment: < textarea name="comment" rows="2" cols="20" >< /textarea >< br >
< input type="submit" value="Submit" >
< /form >
< /body >< /html >
If you enter an email address without the @, you'll get an alert asking you to re-enter the data. What is: x.indexOf(@)==-1? This is a method that JavaScript can search every character within a string and look for what we want. If it finds it will return the position of the char within the string. If it doesn't, it will return -1. Therefore, x.indexOf("@")==-1 basically means: "if the string doesn't include @, then:


alert("It seems you entered an invalid email address.")
document.feedback.email.focus()
What's focus()? This is a method of the text box, which basically forces the cursor to be at the specified text box. onsubmit Unlike onblur, onsubmit handler is inserted inside the < form > tag, and not inside any one element. Lets do an example:


< script >
< !--
function validate()
{
if(document.login.userName.value=="")
{
alert ("Please enter User Name")
return false
}
if(document.login.password.value=="")
{
alert ("Please enter Password")
return false
}
}
//-- >

< /script >

< form name="login" onsubmit="return validate()" >
< input type="text" size="20" name="userName" >
< input type="text" size="20" name="password" >
< input type="submit" name="submit" value="Submit" >
< /form >
Note:
if(document.login.userName.value==""). This means "If the box named userName of the form named login contains nothing, then...". return false. This is used to stop the form from submitting. By default, a form will return true if submitting. return validate() That means, "if submitting, then call the function validate()".

Protect a file by using Login
Let's try an example

< html >< head >
< SCRIPT Language="JavaScript" >
function checkLogin(x)
{
if ((x.id.value != "Sam")||(x.pass.value !="Sam123"))
{
alert("Invalid Login");
return false;
}
else
location="main.htm"
}
< /script >

< /head >< body >
< form >
< p >UserID:< input type="text" name="id" >< /p >
< p >Password:< input type="password" name="pass" >< /p >
< p >< input type="button" value="Login" onClick="checkLogin(this.form)" >< /p >
< /form >
< /body >< /html >
|| means "or", and ,!= indicates "not equal". So we can explain the script: "If the id does not equal 'Sam', or the password does not equal 'Sam123', then show an alert ('Invalid Login') and stop submitting. Else, open the page 'main.htm'".



Link

In most cases, a form can be repaced by a link:


< a href="JavaScript:window.location.reload()" >Click to reload!< /a >
More examples:


< a href="#" onClick="alert('Hello, world!')" >Click me to say Hello< /a >< br >

< a href="#" onMouseOver="location='main.htm'" >Mouse over to see Main Page< /a >


Date

Let's see an example:


< HTML >< HEAD >< TITLE >Show
Date< /TITLE >< /HEAD >
< BODY >
< SCRIPT LANGUAGE="JavaScript" >
var x= new Date();
document.write (x);
< /SCRIPT >
< /BODY >< /HTML >
To activate a Date Object, you can do this: var x=new Date(). Whenever you want to create an instance of the date object, use this important word: new followed by the object name().
Dynamically display different pages
You can display different pages according to the different time. Here is an example:

var banTime= new Date()
var ss=banTime.getHours()
if (ss< =12)
document.write("< img src='banner1.gif' >")
else
document.write("< img src='banner2.gif' >")
Date object
Methods
getDate
getTime
getTimezoneOffset
getDay
getMonth
getYear getSeconds
getMinutes
getHours


Window

Open a window
To open a window, simply use the method "window.open()":

< form >
< input type="button" value="Click here to see" onclick="window.open('test.htm')" >
< /form >
You can replace test.htm with any URL, for example, with http://www.yahoo.com.

Size, toolbar, menubar, scrollbars, location, status
Let's add some of attributes to the above script to control the size of the window, and show: toolbar, scrollbars etc. The syntax to add attributes is:

open("URL","name","attributes")
For example:


< form >
< input type="button" value="Click here to see"
onclick="window.open('page2.htm','win1','width=200,height=200,menubar')" >
< /form >
Another example with no attributes turned on, except the size changed:


< form >
< input type="button" value="Click here to see"
onclick="window.open('page2.htm','win1','width=200,height=200')" >
< /form >
Here is the complete list of attributes you can add:

width height toolbar
location directories status
scrollbars resizable menubar
Reload
To reload a window, use this method:

window.location.reload()
Close Window
Your can use one of the codes shown below:

< form >
< input type="button" value="Close Window" onClick="window.close()" >
< /form >
< a href="javascript:window.close()" >Close Window< /a >
Loading
The basic syntax when loading new content into a window is:

window.location="test.htm"
This is the same as


< a href="test.htm >Try this < /a >
Let's provide an example, where a confirm box will allow users to choose between going to two places:


< script >
< !--
function ss()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
//-- >

< /script >
Remote Control Window
Let's say you have opened a new window from the current window. After that, you will wonder how to make a control between the two windows. To do this, we need to first give a name to the window.Look at below:

aa=window.open('test.htm','','width=200,height=200')
By giving this window a name "aa", it will give you access to anything that's inside this window from other windows. Whenever we want to access anything that's inside this newly opened window, for example, to write to this window, we would do this: aa.document.write("This is a test.").

Now, let's see an example of how to change the background color of another window:


< html >< head >< title >< /title >< /head >
< body >
< form >
< input type="button" value="Open another page"
onClick="aa=window.open('test.htm','','width=200,height=200')" >
< input type="radio" name="x" onClick="aa.document.bgColor='red'" >
< input type="radio" name="x" onClick="aa.document.bgColor='green'" >
< input type="radio" name="x" onClick="aa.document.bgColor='yellow'" >
< /form >
< /body >< /html >
opener
Using "opener" property, we can access the main window from the newly opened window.
Let's create Main page:


< html >
< head >
< title >< /title >
< /head >
< body >
< form >
< input type="button" value="Open another page"
onClick="aa=window.open('test.htm','','width=100,height=200')" >
< /form >
< /body >
< /html >
Then create Remote control page (in this example, that is test.htm):


< html >
< head >
< title >< /title >
< script >
function remote(url){
window.opener.location=url
}
< /script >
< /head >
< body >
< p >< a href="#" onClick="remote('file1.htm')" >File
1< /a >< /p >
< p >< a href="#" onClick="remote('file2.htm')" >File
2< /a >< /p >
< /body >
< /html >
Try it now!



Frame

One of the most popular uses of loading multiple frames is to load and change the content of more than one frame at once. Lets say we have a parent frame:


< html >
< frameset cols="150,*" >
< frame src="page1.htm" name="frame1" >
< frame src="page2.htm" name="frame2" >
< /frameset >
< /html >
We can add a link in the child frame "frame1" that will change the contents of not only page1, but page2 too. Shown below is the html code for it:


< html >
< body >
< h2 >This is page 1 < /h2 >
< a href="page3.htm"
onClick="parent.frame2.location='page4.htm'" >Click Here< /a >
< /body >
< /html >
Notice: You should use "parent.frameName.location" to access another frame. "parent" standards for the parent frame containing the frameset code.
Read More

Monday, November 16, 2009

How to detect browser close button is clicked ?

call this function from page_unload() so when user will close the browser either by [X] button or by alt+f4 or from exit (from file menu). by using this function you can detect that browser is going to close and you can perform any of your choice operation just before browser get close.

function CheckBrowser()
{
// Check Browser Close [X] , Alt+F4 , File -> Close
if(window.event.clientX < 0 && window.event.clientY <0)
{
window.open("Operation.aspx",
"Operation",'left=12000,top=1200,width=10,height=1');
}
}
Read More

Wednesday, November 4, 2009

What is use of "SET XACT_ABORT" in SQL

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Depending upon the severity of the error, the entire transaction may be rolled back even when SET XACT_ABORT is OFF. OFF is the default setting.

Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.

XACT_ABORT must be set ON for data modification statements in an implicit or explicit transaction against most OLE DB providers, including SQL Server. The only case where this option is not required is if the provider supports nested transactions.

example:
The following code example causes a foreign key violation error in a transaction that has other Transact-SQL statements. In the first set of statements, the error is generated, but the other statements execute successfully and the transaction is successfully committed. In the second set of statements, SET XACT_ABORT is set to ON. This causes the statement error to terminate the batch and the transaction is rolled back.

USE AdventureWorks;
GO
IF OBJECT_ID(N't2', N'U') IS NOT NULL
DROP TABLE t2;
GO
IF OBJECT_ID(N't1', N'U') IS NOT NULL
DROP TABLE t1;
GO
CREATE TABLE t1
(a INT NOT NULL PRIMARY KEY);
CREATE TABLE t2
(a INT NOT NULL REFERENCES t1(a));
GO
INSERT INTO t1 VALUES (1);
INSERT INTO t1 VALUES (3);
INSERT INTO t1 VALUES (4);
INSERT INTO t1 VALUES (6);
GO
SET XACT_ABORT OFF;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (1);
INSERT INTO t2 VALUES (2); -- Foreign key error.
INSERT INTO t2 VALUES (3);
COMMIT TRANSACTION;
GO
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (4);
INSERT INTO t2 VALUES (5); -- Foreign key error.
INSERT INTO t2 VALUES (6);
COMMIT TRANSACTION;
GO
-- SELECT shows only keys 1 and 3 added.
-- Key 2 insert failed and was rolled back, but
-- XACT_ABORT was OFF and rest of transaction
-- succeeded.
-- Key 5 insert error with XACT_ABORT ON caused
-- all of the second transaction to roll back.
SELECT *
FROM t2;
GO
Read More

Monday, November 2, 2009

Primary Key , Foreign Key Column Name for Key Constraint


Query written below will give you result as shown in image.
SELECT
[constraint_name] = f.[name],
[child_table] = OBJECT_NAME(f.parent_object_id),
[child_column] = cc.name,
[parent_table] = OBJECT_NAME(f.referenced_object_id),
[parent_column] = pc.name
FROM
sys.foreign_keys f
INNER JOIN
(
SELECT
c.[object_id],
c.name,
c.column_id,
ic.index_id
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON
c.[object_id] = ic.[object_id]
AND c.column_id = ic.column_id
) AS pc
ON
f.key_index_id = pc.index_id
INNER JOIN
sys.foreign_key_columns fkc
ON
f.[object_id] = fkc.constraint_object_id
AND pc.[object_id] = fkc.referenced_object_id
AND fkc.referenced_column_id = pc.column_id
INNER JOIN
sys.columns cc
ON
fkc.parent_object_id = cc.[object_id]
AND fkc.parent_column_id = cc.column_id
ORDER BY
constraint_name,
child_table
Read More

Thursday, October 29, 2009

What is Difference between ScriptManager & ScriptManagerProxy

ScriptManager
A server control that makes script resources available to the browser, including the Microsoft AJAX Library and the functionality that enables partial-page rendering.



ScriptManagerProxy
A server control that enables nested components to add script and service references if the page already contains a ScriptManager control.
Read More

What is Use of Scriptmanager in asp.net AJAX

The ScriptManager control manages client script for Microsoft ASP.NET AJAX pages. By default, the ScriptManager control registers the script for the Microsoft AJAX Library with the page. This enables client script to use the type system extensions and to support features such as partial-page rendering and Web-service calls.

Background
When a page contains one or more UpdatePanel controls, the ScriptManager control manages partial-page rendering in the browser. The control interacts with the page life cycle to update the parts of the page that are inside UpdatePanel controls. For more information, see Partial-Page Rendering Overview.

The EnablePartialRendering property of the ScriptManager control determines whether a page participates in partial-page updates.


ScriptManager is a server-side control that sits on your Web Form and enables the core of ASP.NET AJAX. Its primary role is the arbitration of all other ASP.NET AJAX controls on the Web Form and the addition of the right scripting libraries to the Web browser so that the client portion of ASP.NET AJAX can function. Often you will find yourself using the ScriptManager to register other controls, Web services, and client scripts.
As a server-side control, ScriptManager reacts to events in the ASP.NET page lifecycle and uses those events to coordinate the activities of all the controls, options, and code employed by ASP.NET AJAX. ScriptManager will hook a particular event, get notified when it occurs, and configure a few settings depending on the environment; this process will repeat itself several times through the rendering cycle of your ASP.NET page. The settings it configures, however, are often the exact settings needed to make your use of ASP.NET AJAX seamless.

Why Use the ScriptManager Control

You must use a ScriptManager control on a page to enable the following features of ASP.NET AJAX:

Client-script functionality of the Microsoft AJAX Library, and any custom script that you want to send to the browser. For more information, see ASP.NET AJAX and JavaScript.

Partial-page rendering, which enables regions on the page to be independently refreshed without a postback. The ASP.NET AJAX UpdatePanel, UpdateProgress, and Timer controls require a ScriptManager control to support partial-page rendering.

JavaScript proxy classes for Web services, which enable you to use client script to access Web services by exposing Web services as strongly typed objects.

JavaScript classes to access ASP.NET authentication and profile application services.

Enabling Partial-Page Rendering

When a page contains one or more UpdatePanel controls, the ScriptManager control manages partial-page rendering in the browser. The control interacts with the page life cycle to update the parts of the page that are inside UpdatePanel controls. For more information, see Partial-Page Rendering Overview.

The EnablePartialRendering property of the ScriptManager control determines whether a page participates in partial-page updates. By default, the EnablePartialRendering property is true. Therefore, partial-page rendering is enabled by default when you add a ScriptManager control to the page. For information about how to use the UpdatePanel control with the ScriptManager control, see Introduction to the UpdatePanel Control and Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls.

Handling Errors

During partial-page rendering, you can handle errors by doing the following:

Set the AllowCustomErrorsRedirect property, which determines how the custom error section of the Web.config file is used when an error occurs during an asynchronous postback.

Handle the ScriptManager control's AsyncPostBackError event, which is raised when there is a page error during an asynchronous postback.

Set the AsyncPostBackErrorMessage property, which is the error message that is sent to the browser.

Using Type System Extensions

Microsoft AJAX Library adds type-system extensions to JavaScript that provide namespaces, inheritance, interfaces, enumerations, reflection, and helper functions for strings and arrays. These extensions provide functionality in client script that is like that of the .NET Framework. They enable you to write ASP.NET 2.0 AJAX Extensions applications in a structured way that improves maintainability, makes it easier to add features, and makes it easier to layer functionality. Adding a ScriptManager control to an ASP.NET Web page automatically includes the type-system extensions so that you can use the library in client script.

Registering Custom Script

Use the ScriptManager control to manage resources that you have created for controls that participate in partial-page updates. Resources include scripts, styles, hidden fields, and arrays. The Scripts collection of the ScriptManager control contains a ScriptReference object for each script that is available to the browser. You can specify the scripts declaratively or programmatically.

The ScriptManager control also exposes registration methods that you can use to manage client script and hidden fields programmatically. When you are registering script or hidden fields that support partial-page updates, you must call registration methods of the ScriptManager control. (To register scripts that are not needed for partial-page updates, you use methods of the ClientScriptManager class.)


Registering Web Services

The ScriptManager control's Services collection contains a ServiceReference object for each Web service that is registered with the ScriptManager control. The ASP.NET AJAX framework generates a client proxy object for each ServiceReference object in the Services collection. The proxy classes and their strongly typed members simplify using Web services from client script.
You can programmatically add ServiceReference objects to the Services collection to register Web services at run time.

Using Authentication and Profile Services from Client Script

The Microsoft AJAX Library includes proxy classes for calling the ASP.NET 2.0 forms authentication and profile application services directly from JavaScript. If you want to use a custom authentication service, you can register it using the ScriptManager control.

The ScriptManagerProxy Class

Only one instance of the ScriptManager control can be added to the page. The page can include the control directly, or indirectly inside a nested component such as a user control, content page for a master page, or nested master page. In cases where a ScriptManager control is already on the page but a nested or parent component needs additional features of the ScriptManager control, the component can include a ScriptManagerProxy control. For example, the ScriptManagerProxy control enables you to add scripts and services that are specific to nested components.
Read More

Friday, October 23, 2009

What is the CHECK constraint in SQL Server?

Business rule validation can be applied to a table by using CHECK constraint. CHECK constraint must be specified as a logical expression that evaluates either to TRUE or FALSE.
A CHECK constraint takes longer to execute as compared to NOT NULL, PRIMARY KEY, FOREIGN KEY or UNIQUE constraints. Thus CHECK constraint must be avoided if the constraint can de defined using NOT NULL, PRIMARY KEY, FOREIGN KEY constraints.
Read More

What are the types of constraints in SQL Server?

There are three types of constraints in SQL Server -
1. Domain Constraint - deals with one are more columns.
2. Entity Constraint - are all about individual rows.
2. Referential Integrity Constraint - are created when a value in one column must match the value in another column - in either the same table or in a different table.
Read More

What is the limit of a row n SQL Server?

A row can be up to 8KB.
Read More

What is the maximum number of columns in a row in SQL Server?

1024 columns.
Read More

What is the DEFAULT constraint in SQL Server?

A DEFAULT constraint, like all constraints, becomes an integral part of the table definition. It defines what to do when new row is inserted that does not include data for the column on which you have defined the DEFAULT constraint. You can either define it as a literal value(like default salary to zero or UNKNOWN for a string column) or as one of several values such as GETDATE().
The main things to understand about a DEFAULT constraint are -

1. DEFAULTs are only used in INSERT statements- They are ignored for UPDATE and DELETE statements.
2. If any value is supplied in the INSERT then the default is not used.
3. If no values supplied the default will always be used.
Read More

How to find out column names and their datatypes in a given table using a query in SQL Server?

Using the table tablename, write the query as follows -
Select * from information_schema.columns where table_name = tablename
Read More

What is the DEADLOCK ?

A deadlock is a situation in which two transactions conflict with each other and the only resolution is to cancel one transaction.
Read More

What is a Subquery ?

A Subquery is a normal T-SQL query that is nested inside another query. They are created using parentheses when you have a SELECT statement that serve as the basis for the either part of the data or the condition in another query.
Subqueries are generally used to fill one of couple of needs -

1. Break a query up into a series of a logical steps.
2. Provide a listing to be the target of a WHERE clause together with [IN|ESISTS|ANY|ALL].
3. TO provide a lookup driven by each individual record in a parent query.
Eg.
SELECT SelectList FROM SomeTable WHERE SomeColumn = (SELECT SingleColumn FROM SomeTable WHERE Condition that results in only one row returned)
Read More

What is the EXISTS operator in SQL Server ? OR What is the EXISTS keyword in SQL Server ?

When you use EXISTS, you do not really returned data - instead you return a simple TRUE/FALSE regarding the existence of data that meets the criteria established in the query that the EXISTS statement is operated against.
EXISTS simply test whether the inner query returns any row. If it does, then the outer query proceeds, if not, the outer query does not executes, and the entire SQL statement returns nothing.

The EXISTS condition is considered "to be met " if the subquery returns at least one row.

The syntax for EXISTS condition is -
SELECT columns FROM sometable WHERE EXISTS (subquery)
Read More

How to find nth highest salary from Employee table in SQL Server?

SELECT TOP 1 salary FROM (SELECT DISTINCT TOP n salary FROM employee ORDER BY salary DESC) a ORDER BY salary
Read More

How to convert timestamp data to date data (datetime datatype) in SQL Server?

The name timestamp is a little misleading. Timestamp data has nothing to do with dates and times and can not be converted to date data. A timestamp is a unique number within the database and is equivalent to a binary(8)/varbinary(8) datatype. A table can have only one timestamp column. Timestamp value of a row changes with every update of the row. To avoid the confusion, SQL Server 2000 introduced a synonym to timestamp, called rowversion.
Read More

What is the IDENTITY property in SQL Server?

The IDENTITY property enables you to use system generated values in your tables column. It is similar to the auto number datatype in MS ACCESS. You are allowed a single column in each table with the IDENTITY property. Typically, IDENTITY column generates system assigned keys. To enforce entity integrity, you must uniquely identify each row in a table. If no natural column or set of column does this, you might went to create an IDENTITY column.
You can use the IDENTITY property if the column to which it is being assigned is an integer or compatible with an integer. Therefore you can use the following datatypes - tinyint, bigint, smallint, numeric, integer, decimal.

You can use numeric and decimal only if they have scale of 0 (zero). It must also not allowed to NULL.
Read More

What is the CASCADE action in SQL Server?

By default, you can not delete a record or update the referenced column in a referenced table if that record is referenced from the dependent table. If you want to be able to delete or update such records, then you need to set up a CASCADE action for the delete and/or update.
Read More

What is the FOREIGN KEY in SQL Server?

FOREIGN KEYs are both a method of ensuring data integrity and a manifestation of the relationships between tables. When you add a FOREIGN KEY to a table, you create a dependency between the table for which you define the FOREIGN KEY (the referencing table) and the table your FOREIGN KEY references (the referred table). After adding a FOREIGN KEY, any record you insert into the referencing table must have a matching record in the referenced column(s) of the referenced table, or the value of the FOREIGN KEY column(s) must be set to NULL.
Read More

What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.
Read More

Get Current System Date Format

To get short date pattern of your system:
messagebox.show(System.Globalization.CultureInfo.CurrentCulture
.DateTimeFormat.ShortDatePattern())

To get long date pattern of your system:
messagebox.show(System.Globalization.CultureInfo.CurrentCulture.
DateTimeFormat.LongDatePattern())
Read More

Change Format of Date in VB.NET

Dim departDate As Date
departDate = Date.Now
Dim d As String = Format(departDate, "dd/MM/yyyy")
MsgBox(d)
'Above Example shows how to convert date format according to our requirements.
Read More

Tuesday, October 20, 2009

Restricting numeric entries only in a DataGridView column

At times we have a requirement where we need to restrict the user to enter only numbers in a column of a DataGridView to achieve this we need to use EditingControlShowing event of DataGridView, this event is new in .Net framework 2.0 and it occurs when a control for editing a cell is showing. Following sample shows a implementation of it:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((int)(((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex) == 1)
{
e.Control.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TextboxNumeric_KeyPress);

}
}

private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean nonNumberEntered;

nonNumberEntered = true;

if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
{
nonNumberEntered = false ;
}

if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true ;
}
else
{
e.Handled = false;
}

}
Read More

Tuesday, October 13, 2009

Transposing Column to Row Through Select Query

My student Mr. Bhupendra Asked me that how can i show values of my columns of table as a ROW. To do so: (we also require such query while creating cross-tab report
lets we have following table:

CREATE TABLE [vehical_type](
[unqid] [uniqueidentifier] primary key,
[vname] [varchar](100) NULL
)

we can get our desired result from below query:
-- It will be better to create Stored Procedure of it.
declare @st varchar(max)
set @st='create table tmp ('
-- instead of taking normal table we can take temporary table by using #tmp
select @st = @st + ' temp' + convert(varchar,ROW_NUMBER() OVER(ORDER BY vname )) + ' varchar(max),' from vehical_type order by vname
set @st = left(@st,len(@st)-1) + ');'
--exec(@st)
--select @st
set @st= @st + 'insert into tmp values ('
select @st = @st + '''' + CONVERT(varchar(max), unqid) + ''',' from vehical_type
set @st = left(@st,len(@st)-1) + ');'

set @st= @st + 'insert into tmp values ('
select @st = @st + '''' + vname + ''',' from vehical_type
set @st = left(@st,len(@st)-1) + ');'
--select @st
exec(@st)
select * from tmp
drop table tmp
Read More

Friday, October 9, 2009

How to set required field validator for dropdownlist

My colleague Sweta asked me to how to set required field validator for doopdownlist.
so to set required field validator for doopdownlist we need to follow these steps.

1. let your dropdown list in such format that first item of it is "--Select--" as in example give below.

2. if your valumember is integer type then set value '0' of valuemamber
for "--Select--"

3. take required field validator and select your dropdownlist as control to validate and in field "Initial Value" enter '0' (without single quotes)

Note: if you are using GUID (uniqueidentifier) or any other type of value as valuemember of dropdownlist then place value of "-- select--" in "Initial Value" field of required field validator.

example:
< asp:DropDownList ID="DropDownList1" runat="server" Height="37px" Width="191px" >
< asp:ListItem Value="0" >Select < /asp:ListItem >
< asp:ListItem >--Select-- < /asp:ListItem >
< asp:ListItem >bb < /asp:ListItem >
< asp:ListItem >cc < /asp:ListItem >
< asp:ListItem >dd < /asp:ListItem >
< /asp:DropDownList >
< asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList1" ErrorMessage="RequiredFieldValidator"
InitialValue="0" > < /asp:RequiredFieldValidator >
Read More

Tuesday, October 6, 2009

How to implement keyword "Limit" like functionality in MS SQL Server

select * from mytable limit 10, 20

the equivalent in MS SQL Server would be:

select top 20 * from mytable where pk not in (select top 10 pk from mytable order by pk) order by pk
Read More

Evaluate Rows one by one

through qry written below we will get 1 record at a time and in random order.
SELECT TOP 1 * FROM TabCountryMast ORDER BY newid()
Read More

Thursday, October 1, 2009

Create Control at runtime using JavaScript

through code written below we can create control at runtime using javascript



< %@ Page Language="C#" AutoEventWireup="true" CodeFile="AddRemoveJavascript.aspx.cs" Inherits="AddRemoveJavascript" % >

< !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 >
< script type="text/javascript" >
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my' + num + 'Div';
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = "Element Number " + num + " has been added! < a href=\"javascript:;\" onclick=\"removeElement(\'" + divIdName + "\')\" >Remove the element "" + divIdName + ""< /a >";

ni.appendChild(newdiv);
}
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

< /script >
< /head >
< body >
< form id="form1" runat="server" >
< div >
< input type="hidden" value="0" id="theValue" / >
< p >< a href="javascript:;" onclick="addElement();" >Add Some Elements< /a >< /p >
< div id="myDiv" > < /div >

< /div >
< /form >
< /body >
< /html >
Read More

Wednesday, September 30, 2009

Check/ Uncheck all child nodes of a node in TreeView

when we need to Check/ Uncheck all chield nodes of anynode in TreeView we need to create a recursive function which will do check all to all child nodes of the current node and voice-versa.

Private Sub tvrights_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvrights.AfterCheck
RemoveHandler tvrights.AfterCheck, AddressOf tvrights_AfterCheck
CheckChildNode(e.Node)
CheckParentNode(e.Node)
AddHandler tvrights.AfterCheck, AddressOf tvrights_AfterCheck
End Sub



Private Sub CheckChildNode(ByVal currNode As TreeNode)
'set the children check status to the same as the current node
Dim checkStatus As Boolean = currNode.Checked
For Each node As TreeNode In currNode.Nodes
node.Checked = checkStatus
CheckChildNode(node)
Next
End Sub

Private Sub CheckParentNode(ByVal currNode As TreeNode)
Dim parentNode As TreeNode = currNode.Parent
If parentNode Is Nothing Then Exit Sub
parentNode.Checked = True
For Each node As TreeNode In parentNode.Nodes
If Not node.Checked Then
parentNode.Checked = False
Exit For
End If
Next
CheckParentNode(parentNode)
End Sub
Read More

Visit all Nodes of TreeView

when we need to traverse all nodes of a treeview then we will have to create a recursive function.
In below example we are showing how to visit all nodes of treeview.
eg:-

Private Sub TraverseTreeView(ByVal tview As TreeView)
Dim temp As New TreeNode
For k As Integer = 0 To tview.Nodes.Count - 1
temp = tview.Nodes(k)
messagebox.show(temp) 'this will show node text
For i As Integer = 0 To temp.Nodes.Count - 1
visitChildNodes(temp.Nodes(i))
Next
Next
End Sub

Private Sub visitChildNodes(ByVal node As TreeNode)

messagebox.show(node) 'this will show node text
For j As Integer = 0 To node.Nodes.Count - 1
visitChildNodes(node.Nodes(j))
Next
End Sub
Read More

Monday, September 28, 2009

Custom Page Size Crystal Report by Code

Dim oRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
oRpt.Load(Server.MapPath("CrystalReport.rpt"))
oRpt.PrintOptions.PaperOrientation = [Shared].PaperOrientation.Portrait
oRpt.PrintOptions.PaperSize = [Shared].PaperSize.PaperEnvelope10

CrystalReportViewer1.ReportSource = oRpt
Read More

Tuesday, September 22, 2009

Repair a database

Repair a database

To determine whether a database needs to be repaired run:

dbcc checkdb('DB-NAME') with no_infomsgs
replacing 'DB-NAME' with the name of the database.

If this completes without displaying any errors then the database does not need to be repaired.

If the errors that come back contain lines saying:

... Run DBCC UPDATEUSAGE
Then the database does not need to be repaired, simply run:

dbcc updateusage('DB-NAME') with no_infomsgs
If a database does need to be repaired then:

if you can identify why the database needs to be repaired. Look in the windows system and application event logs to see if any problems have been logged which might account for the problem. For example is the problem caused by a failing disk? Often you will not be able to identify the cause, but if you can then remember to address it.
it is suggested that instead of repairing the database it be restored from the last reliable backup.
To repair a database the database must first be placed into single user mode:

alter database DB-NAME set SINGLE_USER

once the database is in single user mode it can be repaired. There are a number of repair options but the two typically used are "REPAIR_REBUILD" and "REPAIR_ALLOW_DATA_LOSS". I suggest in the first instance using:

dbcc checkdb('DB-NAME',REPAIR_REBUILD)
this will make any repairs that SQL Server can perform without the loss of data.

If (and only if) SQL Server cannot repair the database without the loss of data then use:

dbcc checkdb('DB-NAME',REPAIR_ALLOW_DATA_LOSS)
once the database has been repaired it should be switched out of single user mode and back into multi-user mode:

set database DB-NAME set MULTI_USER
These notes have been tested against SQL Server 2005 running under Windows 2008 Standard Server.
Read More

Monday, September 14, 2009

Static Class

Static classes are used when a class provides functionality that is not specific to any unique instance. Here are the features of static classes in C# 2.0.

Static classes can not be instantiated.
Static classes are sealed so they can not be inherited.
Only static members are allowed.
Static classes can only have static constructor to initialize static members.
Advantages

Compiler makes sure that no instance of static class is created. In previous version of C#, the constructor has to be marked private to avoid this from happening.

Also compiler makes sure that no instance members are declared within a static class.

Sample:

Public static class MyStaticClass
{
Private static int _staticVariable;
Public static int staticVariable;
{
Get
{
Return _staticVariable;
}
Set
{
_staticVariable = value;
}
}
Public static void Function()
{
}
}

--------------***********************----------------------------------------
A static class is defined as a class that contains only static members (of course besides the instance members inherited from System.Object and possibly a private constructor). Some languages provide built-in support for static classes. In C# 2.0, when a class is declared to be static, it is sealed, abstract, and no instance members can be overridden or declared.
public static class File {
...
}
If your language does not have built-in support for static classes, you can declare such classes manually as in the following C++ example:
public class File abstract sealed {
...
}
Static classes are a compromise between pure object-oriented design and simplicity. They are commonly used to provide shortcuts to other operations (such as System.IO.File), or functionality for which a full object-oriented wrapper is unwarranted (such as System.Environment).
DO use static classes sparingly.
Static classes should be used only as supporting classes for the object-oriented core of the framework.
DO NOT treat static classes as a miscellaneous bucket.
There should be a clear charter for the class.
DO NOT declare or override instance members in static classes.
DO declare static classes as sealed, abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes.

Example of Static Class in C#.net

using System;

static class MathFunction {
// Return the reciprocal of a value.
static public double reciprocal(double num) {
return 1/num;
}

// Return the fractional part of a value.
static public double fracPart(double num) {
return num - (int) num;
}

// Return true if num is even.
static public bool isEven(double num) {
return (num % 2) == 0 ? true : false;
}

// Return true of num is odd.
static public bool isOdd(double num) {
return !isEven(num);
}

}

class MainClass {
public static void Main() {
Console.WriteLine("Reciprocal of 5 is " +
MathFunction.reciprocal(5.0));

Console.WriteLine("Fractional part of 4.234 is " +
MathFunction.fracPart(4.234));

if(MathFunction.isEven(10))
Console.WriteLine("10 is even.");

if(MathFunction.isOdd(5))
Console.WriteLine("5 is odd.");

// The following attempt to create an instance of
// MathFunction will cause an error.
// MathFunction ob = new MathFunction(); // Wrong!
}
}
Read More
Powered By Blogger · Designed By Seo Blogger Templates