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
Powered By Blogger · Designed By Seo Blogger Templates