Thursday, December 18, 2008

Get Table structure from XML in SQL Server

Get Table structure from XML in SQL Server.

Here is the script to get the table view from XML Document using OPENXML.


declare @doc varchar(1000)
declare @docHandle int
set @doc = '<Employee-Details>
     <Employee>
        <Firstname>Hariharasudhan</Firstname>
        <Lastname>Chandiramurthy</Lastname>
        <DOB>11-July-1982</DOB>
     </Employee>
     <Employee>
        <Firstname>Suguna</Firstname>
        <Lastname>Ramamurthy</Lastname>
        <DOB>02-September-1979</DOB>
     </Employee>
     <Employee>
        <Firstname>Pasupathy</Firstname>
        <Lastname>Thandavan</Lastname>
        <DOB>01-August-1982</DOB>
     </Employee>
   </Employee-Details>'
exec sp_xml_preparedocument @docHandle output, @doc
select * from openxml (@docHandle, '/Employee-Details/Employee', 1)
     with (FirstName varchar(100) './Firstname/text()'
        , LastName varchar(100) './Lastname/text()'
        , Date_Of_Birth varchar(100) './DOB/text()')

Wednesday, December 17, 2008

Check the given Url is Valid

Check the given Url is Valid

In some situation we want to check the particular url (eg:google.com) is valid or not through programatically.

Here is the code for checking the url.
urlcheck.aspx

<div>
<asp:TextBox ID = "txtUrl" runat = "server" Text = "http:\\">
</asp:TextBox>
<asp:Button ID = "btnCheck" runat = "server" OnClick = "ButtonClick" Text = "Check" />
<asp:Label ID = "lblMsg" runat = "server"></asp:Label>
</div>



urlcheck.aspx.cs

protected void ButtonClick(object sender, EventArgs e)
{
try
{
System.Net.HttpWebRequest objReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtUrl.Text);
System.Net.HttpWebResponse objRes = (System.Net.HttpWebResponse)objReq.GetResponse();
if (objRes.StatusCode == System.Net.HttpStatusCode.OK)
{
lblMsg.Text = "Url is Valid";
lblMsg.ForeColor = System.Drawing.Color.SeaGreen;
}
else
{
lblMsg.Text = "Url is not Valid";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
objRes.Close();
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}

Tuesday, December 16, 2008

Check All Option in TreeView control

Javascript : Check All Option in TreeView control
ASP.Net 2.0 Provides Tree view control with more features. It gives an option to select items through checkboxes. But there is no option for select all in a single click.

We can do that using Javascript. Here the stuff....



<script language = "javascript" type = "text/javascript">
function treeViewClick()
{
var checkStatus = false;
var obj = event.srcElement;
if(obj.tagName == 'INPUT' && obj.type == 'checkbox')
{
checkStatus = obj.checked;
while(obj.tagName != 'TABLE')
{
obj = obj.parentElement;
}
if(isParent(obj)) /// Parent Node ---- Needs to set the parent status (Checked or Unchecked) to its child.
{
obj = obj.nextSibling;
var tables = obj.getElementsByTagName('TABLE');
for(tblcnt = 0; tblcnt < tables.length; tblcnt++)
{
checkAllDependents(tables[tblcnt], checkStatus);
}
}
else /// Child Node --- Needs to set the parent of this child as unchecked...
{
var parent = obj.parentElement.previousSibling;
var parentchkboxes = parent.getElementsByTagName('INPUT');
if(parentchkboxes.length > 0 && checkStatus == false)
parentchkboxes[0].checked = false;
}
}
}

function checkAllDependents(element, isChecked)
{
var ctrls = element.getElementsByTagName('INPUT');
for(cnt = 0; cnt < ctrls.length; cnt++)
{
if(ctrls[cnt].type == 'checkbox')
{
ctrls[cnt].checked = isChecked;
}
}
}

function isParent(element)
{
var anchors = element.getElementsByTagName('A');
//if(anchors.length > 1) // the Treeview Node option of SelectAction is other than "none"
if(anchors.length > 0) // the Treeview Node option of SelectAction is "none"
return true;
else
return false;
}
</script>




Here is the controls scripts.



<div>
<asp:XmlDataSource ID = "dsXML" runat = "server">
<Data>
<Products>
<Type Name = "Microsoft">
<Product ID = "1" Name = "DOTNET" />
<Product ID = "2" Name = "SQLServer" />
<Product ID = "3" Name = "Office" />
</Type>
<Type Name = "Oracle">
<Product ID = "1" Name = "Oracle11g" />
<Product ID = "2" Name = "Oracle10g" />
<Product ID = "3" Name = "Oracle9i" />
</Type>
<Type Name = "Sun">
<Product ID = "1" Name = "J2EE" />
<Product ID = "2" Name = "J2ME" />
<Product ID = "3" Name = "JSP" />
</Type>
</Products>
</Data>
</asp:XmlDataSource>

<asp:TreeView ID = "tvProducts" runat = "server"
DataSourceID = "dsXML" onclick = "treeViewClick();"
ShowCheckBoxes = "Leaf" BackColor = "seagreen" ForeColor = "white">
<DataBindings>
<asp:TreeNodeBinding DataMember = "Products" Text = "Products" SelectAction ="none" />
<asp:TreeNodeBinding DataMember = "Type" TextField = "NAME" ShowCheckBox = "true" SelectAction="none" />
<asp:TreeNodeBinding DataMember = "Product" ValueField = "ID" TextField = "NAME" SelectAction="none" />
</DataBindings>
</asp:TreeView>
</div>


Friday, December 12, 2008

Awesome Features of VS.NET 2008

Awesome Features of VS.NET 2008
VS.NET 2008 (Framework 3.5) released with wonderful features.
Look on this
VS.NET 2008 Features

Monday, November 17, 2008

Set Password Textbox value dynamically

Set Password Textbox value dynamically
Usually when we need to set values for textboxes dynamically, we just assign values to the Textbox's Text property like,

TextBox1.Text = "hsp";

But the above statement will not work, if the Textbox mode is "Password".
Suppose we want to set the values of Password mode textbox, we can use the following code.

TextBox1.Attributes["value"] = "hsp";


Also, when the page is getting postback, the values in Password textboxes will be cleared. But you can retain the text in password textboxes.
Add the following code in Page_Load event of the page.

TextBox1.Attributes.Add("value", TextBox1.Text);

Friday, November 14, 2008

Find N-th highest record in SQL Server

Find N-th highest record in SQL Server
The following list of queries can be used to get N-th maximum record from table in SQL Server.
Here, let we consider a simple employee table. And we need to get the employee details whose salary is the 2nd maximum of the table.

Option: 1

Select top 1 * from employee where salary not in (select max(salary) from employee ) order by salary desc

Option:2

Select top 1 * from (select top 2 * from employee order by salary desc) emp order by emp.salary

Option: 3

Select * from employee e1 where 1 = (select count(distinct(e2.salary)) from employee e2 where e2.salary > e1.salary)

Friday, November 7, 2008

Build components (dll) into Multiple Locations

Build components (dll) into Multiple Locations
Usually when we build a component (dll), the result dll will be stored in path which is specified in OutputPath of that project Properties.
output Path

By default the output path is “bin\debug” of the particular project.
We can change this path to our required one.

Suppose, in some solutions, we may use the same dll more than one projects. For this, we need to copy the dll and paste in specific location. This may cause some problem if we forgot to copy and paste. So, we need some automatic process for this.

Thank fully Visual studio provides a concept called Build Events.
Build Events

In that, we can include some DOS command through Macros. The Macros contains some default keys which has values like Target path etc..
Macros

Here For example I want to stored the dll into “d:\test\” folder, we need to add XCOPY command with macros.
Xcopy

xcopy "$(TargetPath)" "d:\test\" /d /y

XCopy Syntax




Copies files and directory trees.

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W]
[/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U]
[/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z]
[/EXCLUDE:file1[+file2][+file3]...]

source Specifies the file(s) to copy.
destination Specifies the location and/or name of new files.
/A Copies only files with the archive attribute set,
doesn't change the attribute.
/M Copies only files with the archive attribute set,
turns off the archive attribute.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/EXCLUDE:file1[+file2][+file3]...
Specifies a list of files containing strings. Each string
should be in a separate line in the files. When any of the
strings match any part of the absolute path of the file to be
copied, that file will be excluded from being copied. For
example, specifying a string like \obj\ or .obj will exclude
all files underneath the directory obj or all files with the
.obj extension respectively.
/P Prompts you before creating each destination file.
/S Copies directories and subdirectories except empty ones.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/V Verifies each new file.
/W Prompts you to press a key before copying.
/C Continues copying even if errors occur.
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Q Does not display file names while copying.
/F Displays full source and destination file names while copying.
/L Displays files that would be copied.
/G Allows the copying of encrypted files to destination that does
not support encryption.
/H Copies hidden and system files also.
/R Overwrites read-only files.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
empty directories and subdirectories.
/U Copies only files that already exist in destination.
/K Copies attributes. Normal Xcopy will reset read-only attributes.
/N Copies using the generated short names.
/O Copies file ownership and ACL information.
/X Copies file audit settings (implies /O).
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
/-Y Causes prompting to confirm you want to overwrite an
existing destination file.
/Z Copies networked files in restartable mode.

The switch /Y may be preset in the COPYCMD environment variable.


After adding the command line save the build Events.

Build Events added

Now Build your dll. The dll will be stored in “bin/debug” path of the project folder and also in “d:\test\” folder. (Make sure d: drive should contain test folder. Otherwise it gives an error)

Friday, October 31, 2008

Access / Consume Web Service using JavaScript

Access / Consume Web Service using JavaScript
Web Service is a distributed application that provides information to client irrespective of Platform, Languages. There are number of free web services available (webservicex) in universe.
We can call the web service method through JavaScript functions. To doing this, we need to concentrate the following three points,
   1.Download Web Service behavior (HTC – HTML Component) file from Microsoft and include that file into your project.
   2.Create a Proxy Web service for accessing the original web service (Since, Browser provides security issue while calling the original web service directly.)
   3.Create a Page in which, we need to add the code for accessing web service.

For explaining the concept I am using one of the free services which are available in www.webservicex.net. The service is used to validate whether the entered email address is valid one or not.

1.Web Service Behavior
   The WebService behavior enables client-side script to invoke remote methods exposed by Web Services, or other Web servers, that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP, without requiring expert knowledge of its implementation. The WebService behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects, and XML data. The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.
For more information click here
You can download the HTC file from Microsoft and include that file into your project.

2.Create a Proxy Web Service
   While using the remote web service directly, the browser prompts security issue like,

"This page is accessing information that is not under its control. This poses a security risk "



To avoid this, we need to create proxy service in our local, to access the remote web service.
For creating proxy service we need to do the following steps.
   a)Get the particular web service’s WSDL as .cs file and Compile it. Using WSDL.exe command, we can get the .cs file of web service WSDL like,
Go to Visual studio command prompt,
C:\WSDL http://www.webservicex.net/ValidateEmail.asmx?WSDL
The validateemail.cs file will be created. Now we need to compile this file into dll.
C:\csc /t:library /out:WS_ValidateEmail.dll validateemail.cs
The validateemail.dll will be create. Now Copy the dll file and paste into bin folder of your project. Make the reference of this dll via Add reference.

   b)Create Proxy Web Service and call the original web service via newly created dll.
Create a proxy web service by click File->New->File and select Web Service. Name the file as “ProxyWS.asmx” and add the following function into the file.


[WebMethod]
public bool IsValidEmail(string email)
{
ValidateEmail objWS = new ValidateEmail();
bool result = objWS.IsValidEmail(email);
return result;
}


3.Create Page to access Web service.
   Create a page and add the following scripts.

<script language = "javascript" type ="text/javascript">
function initWS()
{
var email = document.getElementById('txtEmail').value;
if(email.length > 0)
{
// Initialize and create object using web service behavior.
divWS.useService("proxyWS.asmx?WSDL","objWS")
if(divWS.objWS)
{
document.getElementById("sLoad").style.visibility = "visible";
document.getElementById("btnValidate").style.visibility = "hidden";
divWS.objWS.callService(getResult,"IsValidEmail", email);
}
}
}
function getResult(result)
{
if(result.error)
{
alert("Error : " + result.errorDetail.code + " , " + result.errorDetail.string + " , " + result.errorDetail.raw);
}
else
{
if(result.value)
alert("Valid Email");
else
alert("Invalid Email");
}
document.getElementById("sLoad").style.visibility = "hidden";
document.getElementById("btnValidate").style.visibility = "visible";
}
</script>


Add the following code in <body> section,

<form id="form1" runat="server">
<div id = "divWS" style="BEHAVIOR: url(webservice.htc)">
</div>
<table>
<tr>
<td> Enter the Email Address :</td>
<td> <input type = "text" id = "txtEmail" /> </td>
</tr>
<tr>
<td colspan = "2">
<span id = "sLoad" style="visibility:hidden">Loading</span>
<input type = "button" id = "btnValidate" value = "Validate" onclick = "initWS();" />
</td>
</tr>
</table>
</form>

Wednesday, October 22, 2008

ORACLE : Minutes between Two dates

ORACLE : Minutes between Two dates
The following function is returning the No. of minutes between two specific dates.

 FUNCTION F_GET_MINUTES_DIFF
 (
   dSTARTDATE    DATE,
   dENDDATE    DATE
 ) RETURN NUMBER
 IS
   v_MINSDIFF   NUMBER(5);
 BEGIN
   SELECT
    ROUND(
     (((TRUNC(dSTARTDATE) + 1) - dSTARTDATE) * 1440)
     + ((dENDDATE - TRUNC(dENDDATE)) * 1440)
     + (((TRUNC(dENDDATE) - TRUNC(dSTARTDATE))-1) * 1440),
    2) INTO v_MINSDIFF
   FROM
    DUAL;
   RETURN v_MINSDIFF;
 END F_GET_MINUTES_DIFF;

Example to call the function

 DECLARE
   MINSDIFF NUMBER(5);
 BEGIN
   MINSDIFF := F_GET_MINUTES_DIFF(TO_DATE('21-10-2008 12:00:01 AM', 'dd-mm-yyyy hh:mi:ss pm'), SYSDATE);
   DBMS_OUTPUT.PUT_LINE(MINSDIFF);
 END;

Monday, October 20, 2008

Check Prime numbers

Function to Check Prime number

Here a simple function to check whether the given number is Prime or not.


private bool isPrime(int tmp)
 {
   if (tmp <= 3)
    return true;
   else
   {
    for (int cnt = 2; cnt < tmp; cnt++)
    {
     if (tmp % cnt == 0)
      return false;
     }
    return true;
   }
 }

Friday, October 17, 2008

Enumerations in C#.Net

Enumerations in C#.Net

An enum is a value type with a set of related named constants often referred to as an enumerator list.

Here I am using the Build in Enum type named DbType, which returns all the types.

Get value of particular index

DbType value = (DbType)10;

The Result will be Int16

Get index of particular value,

int index = (int)DbType.Int16;


The Result will be 10

Wednesday, October 15, 2008

ORACLE : VARRAYS

VARRAYS IN ORACLE
Varrays (short for variable-size arrays) hold a fixed number of elements. They use sequential numbers as subscripts. You can define equivalent SQL types, allowing varrays to be stored in database tables. They can be stored and retrieved through SQL, but with less flexibility than nested tables.


Note:
Varrays are a good choice when the number of elements is known in advance, and when the elements are usually all accessed in sequence. When stored in the database, varrays retain their ordering and subscripts.


For Example

----------- CREATING VARRAY TYPE ------------
------- 10 rows of varchar2(25) column
CREATE OR REPLACE
TYPE TYPE_VARRAY AS VARRAY(10) OF VARCHAR2(25);
---------------------------------------------

--- CREATEING TABLE WITH VARRAY COLUMN ------
CREATE TABLE TBL_WITH_VARRAY
(
ID NUMBER
, ADDEDDATE DATE
, DATA TYPE_VARRAY
)
---------------------------------------------

DESC TBL_WITH_VARRAY
SELECT * FROM USER_TYPES

SELECT * FROM TBL_WITH_VARRAY

INSERT INTO TBL_WITH_VARRAY
(
ID
, ADDEDDATE
, DATA
) VALUES
(
1
, SYSDATE
, TYPE_VARRAY('1','2','3','4','5')
);
/
INSERT INTO TBL_WITH_VARRAY
(
ID
, ADDEDDATE
, DATA
) VALUES
(
2
, SYSDATE
, TYPE_VARRAY('A','B','C','D','E','F','G','H','I','J','K')
);
---[1]: (Error): ORA-22909: exceeded maximum VARRAY limit
INSERT INTO TBL_WITH_VARRAY
(
ID
, ADDEDDATE
, DATA
) VALUES
(
2
, SYSDATE
, TYPE_VARRAY('A','B','C','D','E','F','G','H','I','J')
);

SET SERVEROUTPUT ON;

DECLARE
TMP_VARRAY TYPE_VARRAY;
BEGIN
SELECT DATA INTO TMP_VARRAY FROM TBL_WITH_VARRAY WHERE ID = 2;
DBMS_OUTPUT.PUT_LINE('NO.OF RECORDS : ' || TMP_VARRAY.COUNT);
FOR CNT IN TMP_VARRAY.FIRST..TMP_VARRAY.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(TMP_VARRAY(CNT));
END LOOP;
END;
/

DECLARE
TMP_VARRAY TYPE_VARRAY;
BEGIN
SELECT DATA INTO TMP_VARRAY FROM TBL_WITH_VARRAY WHERE ID = 2;
DBMS_OUTPUT.PUT_LINE('NO.OF RECORDS : ' || TMP_VARRAY.COUNT);
FOR CNT IN REVERSE TMP_VARRAY.FIRST..TMP_VARRAY.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(CNT || ' : ' || TMP_VARRAY(CNT));
END LOOP;
END;

------- CREATING OBJECT TYPE --------
CREATE OR REPLACE
TYPE TYPE_OBJ_TEST AS OBJECT
(
CODE NUMBER
, VAL VARCHAR2(25)
);
-------------------------------------

----- CREATING VARRAY OF OBJECT -----
CREATE OR REPLACE
TYPE TYPE_VARRAY_OBJ IS VARRAY(10) OF TYPE_OBJ_TEST;
-------------------------------------

----- CREATING TABLE WITH OBJECT VARRAY ----
CREATE TABLE TBL_WITH_VARRAY1
(
ID NUMBER
, ADDEDDATE DATE
, DATA TYPE_VARRAY_OBJ
)
--------------------------------------------

DESC TBL_WITH_VARRAY1
SELECT * FROM TBL_WITH_VARRAY1

INSERT INTO TBL_WITH_VARRAY1
(
ID
, ADDEDDATE
, DATA
) VALUES
(
1
, SYSDATE
, TYPE_VARRAY_OBJ (TYPE_OBJ_TEST(91,'IND'), TYPE_OBJ_TEST(65,'SG'))
);

INSERT INTO TBL_WITH_VARRAY1
(
ID
, ADDEDDATE
, DATA
) VALUES
(
2
, SYSDATE
, TYPE_VARRAY_OBJ(TYPE_OBJ_TEST(91,'IND'), TYPE_OBJ_TEST(65,'SG'),TYPE_OBJ_TEST(11,'ABC'), TYPE_OBJ_TEST(22,'DEF'))
);

SET SERVEROUTPUT ON;

DECLARE
TMP_VARRAY TYPE_VARRAY_OBJ;
TMP_OBJ TYPE_OBJ_TEST;
BEGIN
SELECT DATA INTO TMP_VARRAY FROM TBL_WITH_VARRAY1 WHERE ID = 2;
DBMS_OUTPUT.PUT_LINE('NO.OF RECORDS : ' || TMP_VARRAY.COUNT);
FOR CNT IN TMP_VARRAY.FIRST..TMP_VARRAY.LAST
LOOP
TMP_OBJ := TMP_VARRAY(CNT);
DBMS_OUTPUT.PUT_LINE(TMP_OBJ.CODE || ' - ' || TMP_OBJ.VAL);
END LOOP;
END;

For Syntax and more information

ORACLE : NESTED TABLES

NESTED TABLES in ORACLE
Nested tables hold an arbitrary number of elements. They use sequential numbers as subscripts. You can define equivalent SQL types, allowing nested tables to be stored in database tables and manipulated through SQL.
Within the database, nested tables can be considered one-column database tables. Oracle stores the rows of a nested table in no particular order. But, when you retrieve the nested table into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. That gives you array-like access to individual rows.
PL/SQL nested tables are like one-dimensional arrays. You can model multi-dimensional arrays by creating nested tables whose elements are also nested tables.
Nested tables differ from arrays in two important ways:
1. Arrays have a fixed upper bound, but nested tables are unbounded. So, the size of a nested table can increase dynamically
2. Arrays must be dense (have consecutive subscripts). So, you cannot delete individual elements from an array. Initially, nested tables are dense, but they can become sparse (have nonconsecutive subscripts). So, you can delete elements from a nested table using the built-in procedure DELETE. That might leave gaps in the index, but the built-in function NEXT lets you iterate over any series of subscripts.


Note:
Nested tables can be stored in a database column, so Nested tables are appropriate for important data relationships that must be stored persistently.



Example scripts

----- Creating Nested Tables type ----------------------
---- Unlimited rows of varchar2(25) column.
CREATE OR REPLACE
TYPE TYPE_NESTED_TABLES IS TABLE OF VARCHAR2(25);
/
---------------------------------------------------------

-------- Creating table with nested table types ---------
CREATE TABLE TBL_WITH_NESTEDTABLES
(
ID NUMBER
, ADDEDDATE DATE
, DATA TYPE_NESTED_TABLES
) NESTED TABLE DATA STORE AS NESTED_TABLES_TAB
/
---------------------------------------------------------

DESC TBL_WITH_NESTEDTABLES
DESC NESTED_TABLES_TAB

SELECT * FROM USER_NESTED_TABLES
SELECT * FROM USER_TAB_COLS WHERE TABLE_NAME = 'TBL_WITH_NESTEDTABLES'
SELECT * FROM USER_TYPES


INSERT INTO TBL_WITH_NESTEDTABLES
(
ID
, ADDEDDATE
, DATA
) VALUES
(
1
, SYSDATE
, TYPE_NESTED_TABLES('A','B','C')
);
/

INSERT INTO TBL_WITH_NESTEDTABLES
(
ID
, ADDEDDATE
, DATA
) VALUES
(
2
, SYSDATE
, TYPE_NESTED_TABLES('1','2','3','4','5')
);
/
INSERT INTO TBL_WITH_NESTEDTABLES
(
ID
, ADDEDDATE
, DATA
) VALUES
(
3
, SYSDATE
, TYPE_NESTED_TABLES('AA','BB','CC','DD','EE','FF')
);
/

SELECT * FROM TBL_WITH_NESTEDTABLES

SET SERVEROUTPUT ON;

DECLARE
TMP_TYPE TYPE_NESTED_TABLES;
BEGIN
SELECT DATA INTO TMP_TYPE FROM TBL_WITH_NESTEDTABLES WHERE ID = 1;
DBMS_OUTPUT.PUT_LINE('NO.OF RECORDS : ' || TMP_TYPE.COUNT);
FOR CNT IN TMP_TYPE.FIRST..TMP_TYPE.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(TMP_TYPE(CNT));
END LOOP;
END;
/

DECLARE
TMP_TYPE TYPE_NESTED_TABLES := TYPE_NESTED_TABLES('TN','AP','KA','KE','UP');
BEGIN
UPDATE TBL_WITH_NESTEDTABLES SET DATA = TMP_TYPE WHERE ID = 1;
END;
/

SELECT
T1.ID
, T1.ADDEDDATE
, T2.*
FROM
TBL_WITH_NESTEDTABLES T1,
TABLE(T1.DATA) T2



For More information

Tuesday, October 14, 2008

Partial Update using Prototype JavaScript Framework

Partial Update using Prototype JavaScript Framework
Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.
Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the code base of choice for web application developers everywhere.
For downloads and details,

Oracle: I/O operations Using UTL_FILE

I/O operations in Oracle Using UTL_FILE
This is easy writing to the alert log is accomplished by using Oracle’s UTL_FILE package. The UTL_FILE package allows Oracle SQL and PL/SQL to read and write directly from flat files on the server.


CREATE DIRECTORY TARGETDIR AS 'DIRECTORY PATH' --- Path should be accessible from Oracle Server.
/

SET serveroutput on

DECLARE
ex BOOLEAN;
flen NUMBER;
bsize NUMBER;
BEGIN
utl_file.fgetattr('TARGETDIR', 'test.txt', ex, flen, bsize);

IF ex THEN
dbms_output.put_line('File Exists');
ELSE
dbms_output.put_line('File Does Not Exist');
END IF;
dbms_output.put_line('File Length: ' || TO_CHAR(flen));
dbms_output.put_line('Block Size: ' || TO_CHAR(bsize));
END fgetattr;
/



For more information regarding UTL_FILE, Click
Here and Here

Friday, October 10, 2008

String Aggregation in Oracle

String Aggregation in Oracle

Aggregation is concatenation of values from more than one row. In Oracle we can achieve this aggregation in 3 ways.
For example, we need get all employees for each department at single row.

1. Specific Function
Here we can create a function for concatenation, call the function for each department. The function contains for…loop, it may takes more times when the table contains huge data.

CREATE OR REPLACE FUNCTION func_testStrAggt
(
nDEPTNO in EMP1.DEPTNO1%TYPE
)
RETURN VARCHAR2
IS
strRet varchar2(32000) := '';
BEGIN
FOR cur_rec IN (SELECT ENAME FROM EMP1 WHERE DEPTNO1 = nDEPTNO)
LOOP
strRet := strRet || cur_rec.ENAME || ' ,';
END LOOP;
RETURN strRet;
END;

SELECT DEPTNO1, func_testStrAggt(DEPTNO1) AS EMPLOYEES FROM (select distinct DEPTNO1 from EMP1)

2.Using ROW_NUMBER() and SYS_CONNECT_BY_PATH functions in Oracle 9i
This is a new concept which is available oracle 9i and later.

SELECT DEPTNO1,
LTRIM(MAX(SYS_CONNECT_BY_PATH(Ename,','))
KEEP (DENSE_RANK LAST ORDER BY curr), ',') AS EMPLOYEES
FROM
(SELECT DEPTNO1, ENAME,
ROW_NUMBER() OVER (PARTITION BY DEPTNO1 ORDER BY Ename) AS curr,
ROW_NUMBER() OVER (PARTITION BY DEPTNO1 ORDER BY Ename) - 1 AS prev
FROM EMP1
)
GROUP BY DEPTNO1
CONNECT BY prev = PRIOR curr AND DEPTNO1 = PRIOR DEPTNO1
START WITH curr = 1


4. Using XML concept
This concept uses the XML tags and concatenate with tags.

SELECT DEPTNO1,
SUBSTR(
REPLACE(
REPLACE(XMLAgg(XMLElement("dummy",ENAME)),'</dummy>','')
,'<dummy>',',')
,2)
AS EMPLOYEES
FROM EMP1 GROUP BY DEPTNO1

The Output Will be like
















DEPTNO1EMPLOYEES
10allen ,scot
20role ,stamp ,timn
30paln

Overriding Built in Functions in JavaScript

Overriding Built in Functions in JavaScript
We can override the built functions (eg: window.open, window.close etc) with our own functions.


<script language = 'javascript'>
function MyownOpen()
{
var args = MyownOpen.arguments;
if (args.length)
alert(args[0]);
}

window.open = MyownOpen;

</script>




<a href = "#" onclick = "window.open('http://hspharic.blogspot.com');" >
My blog </a>

Check whether Javascript enabled or now

Check whether JavaScript is Enabled or not in Browser.

<NOSCRIPT>
<META HTTP-EQUIV="Refresh" CONTENT="2;URL=content.html">
</NOSCRIPT>


If the browser does not have JavaScript enabled (or it's not supported), it will be taken to the page "content.html" in 2 seconds.
If JavaScript is enabled, the Refresh command will be ignored.

Schedule Task in Sql Server

Schedule Task in Sql Server
In Sql Server, there is an interesting concept called Schedule. With this we can do some automatic functionality.
For example, I want to check goods stock daily. For this I can create a job to check the stock and schedule that job to be executing in time basis.

Here, I have taken the objects from pubs database.
I have created one new table named ‘hsp_CheckStock’.
Actually what I did is,
Checking the stores table whether the Quantity is > 10. If it is then I will put the corresponding title and qty into hsp_checkstock table with date of updated. This is done in stored procedure named ‘sp_hsp_UpdateStock’.



use pubs
create table hsp_CheckStock (title varchar(100), qty int, updatedon datetime)

create procedure sp_hsp_UpdateStock
as
insert hsp_checkstock
select t.title, s.qty, getdate() as updatedon from sales s, titles t
where s.title_id = t.title_id and s.qty > 10;

use msdb
/* Create Job --- For calling from schedule. Click here for syntax */
exec sp_add_job
@job_name = 'job_hsp_updatestock'

/* Create Job step --- For Executing the stored procedure. Click here for syntax */
exec sp_add_jobstep
@job_name = 'job_hsp_updatestock',
@step_name = 'jobstep_hsp_updatestock',
@subsystem = 'TSQL',
@command = 'exec pubs.dbo.sp_hsp_UpdateStock'

/*Click here for syntax */
exec sp_add_jobserver
@job_name = 'job_hsp_updatestock'

/* Create Schedule --- For executing the job at specific time base. Click here for syntax */

exec sp_add_jobschedule
@job_name = 'job_hsp_updatestock',
@name = 'jobschedule_hsp_updatestock',
@freq_type = 4, --- Daily
@freq_interval = 1,
@active_start_time = 160000 --- 4PM


Now, the checking process is doing in automatic manner. The same concept you can try for automatic email reminder.

Associative Arrays in Oracle PL/SQL

Associative Arrays in Oracle PL/SQL
The “Associative Arrays” are also known as “Index-By” tables in PL/SQL. We all know that a variable can hold only one value (as the variable occupies one memory location based on the data type chosen). An “Associative Array” can also be considered a single variable, but with more than one memory location.
An “Associative Array” can hold a huge amount of information in several memory locations, identified by some “index.” This “index” could simply be an integer or string, or something else.
In general, an “Associative Array” stores pairs of data (either sequentially or non- sequentially). Each pair of data would generally contain a “key” and a “value.” If stored sequentially, the “key” would be nothing but a consecutive number holding the “value.” While storing information into an “Associative Array,” the user needs to specify both “key” and “value.”
This concept looks very similar to the concept of arrays in C/C++. In C/C++ an array is a continuous memory of several locations starting with zero as index. But, here the “index” could be anything (there is no strict rule for working with the “index”).
Also, it is as much as same HashTable in C#.

Members of Associative Array
COUNT : It returns the number of elements available in the particular Array.
FIRST : It gives the first key available within the associative array.
LAST : It gives the last key available within the associative array.
NEXT(index): It returns the next key from the current key available in
variable “index”.
PRIOR(index): It returns the previous key from the current key
available in variable “index”.
DELETE(index): Deletes the key and associative value of particular key.
DELETE(start, end): Delete keys and values of specific range.

Example:

DECLARE
TYPE NUMBERARRAY IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
v_TYPENUMBER NUMBERARRAY;
v_TOTAL NUMBER := 0;
iCNT NUMBER;
BEGIN
v_TYPENUMBER(51) := 1200;
v_TYPENUMBER(2) := 200;
v_TYPENUMBER(30) := 600;
iCNT := v_TYPENUMBER.FIRST;
WHILE iCNT <= v_TYPENUMBER.LAST
LOOP
DBMS_OUTPUT.PUT_LINE('Index : ' || iCNT);
v_TOTAL := v_TOTAL + v_TYPENUMBER(iCNT);
iCNT := v_TYPENUMBER.NEXT(iCNT);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Result = ' || v_TOTAL);
END;


The Output Will be like,
Index : 2
Index : 30
Index : 51
Result = 2000

Javascript : Font Installation check

Font availability check
The below script checks whether the particular font is installed in the client browser or not.


<script language = ‘javascript’ >

function checkIfInstalled(fname)
{
IE4 = document.all;
NS4 = document.layers;
ver4 = (IE4 || NS4);
if(!ver4) return false;

isMac = (navigator.appVersion.indexOf("Mac") != -1);
isWin = (navigator.appVersion.indexOf("Win") != -1);

arNotNavWin = ["Webdings","Marlett"];

if(NS4 && isWin)
{
for(i=0;i<arNotNavWin.length;i++)
{
if (fname == arNotNavWin[i]) return false;
}
}

teststr = "font existence test"
if(IE4)
{
if(!window.fntLyr0)
{
lyrstr0 = "<SPAN ID=fntLyr0 STYLE='position:absolute;visibility:hidden;width:30;font:12pt Courier'>"+ teststr +"</SPAN>";
lyrstr1 = "<SPAN ID=fntLyr1 STYLE='position:absolute;visibility:hidden;width:30;font-size:12pt'>"+ teststr +"</SPAN>";
document.body.insertAdjacentHTML("BeforeEnd",lyrstr0);
document.body.insertAdjacentHTML("BeforeEnd",lyrstr1);
}
fntLyr1.style.fontFamily = fname +",Courier";
width0 = (isMac) ? fntLyr0.offsetWidth : fntLyr0.scrollWidth;
width1 = (isMac) ? fntLyr1.offsetWidth : fntLyr1.scrollWidth;
}
if(NS4)
{
lyrstr1 = "<FONT FACE='"+ fname +",Courier' POINT-SIZE=12>"+ teststr +"</FONT>";
if(!window.fntLyr0)
{
lyrstr0 = "<FONT FACE='Courier' POINT-SIZE=12>"+ teststr +"</FONT>";
fntLyr0 = new Layer(400);
fntLyr0.document.write(lyrstr0);
fntLyr0.document.close();
fntLyr1 = new Layer(400);
fntLyr1.document.write(lyrstr1);
fntLyr1.document.close();
}
else
{
fntLyr1.document.write(lyrstr1);
fntLyr1.document.close();
}
width0 = fntLyr0.clip.width;
width1 = fntLyr1.clip.width;
}
return (width0 != width1)? 'Installed' : 'Not installed';
}
</script>

Code to call the script function.

<h1>Check the Font installed or not</h1>
<input id = 'txtFont' name = 'txtFont' value = 'Arial' >
<input type = 'button' value = 'IsInstalled'
onclick ="alert(checkIfInstalled(txtFont.value))" />


Visit to check this script.

Get value in ‘n’ times without using for…loop

Get value in ‘n’ times without using for…loop
When we need to get some values in 1000 times, usually we go for a loop and concatenate the strings. But this can be done in a single statement.


<script language = ‘javascript’ >
function Repeats(str, cnt)
{
return alert( (new Array(cnt + 1)).join(str));
}
</script>


By using the above function, you can get a string in ‘n’ number of times like,

Enter the String : <input id = 'txtStr' name = 'txtStr' />
<input type = 'button' onclick = 'Repeats(txtStr.value,1000);' value = ' show' />


To Test


Enter the String :

Javascript : Clipboard functions

Clipboard operations through Javascript

<script language = 'Javascript'>
function Copy2Clipboard()
{
   window.clipboardData.setData("Text", document.getElementById('txt').value);
}

function GetFromClipboard()
{
   document.getElementById('txt').value = window.clipboardData.getData("Text");
}
</script>



<input id = 'txt' name = 'txt'>
<input type = 'button' onclick = "Copy2Clipboard()" value = "Copy2Clipboard" />
<input type = 'button' onclick = "GetFromClipboard()" value = "GetFromClipboard" />


To Test

Add item to Select Box

Insert new item dynamically to Select Box (Combo) using script

Javascript:

<script language = 'javascript'>
function AddItem()
{
document.getElementById('s').add(new Option('A','1',false,false));
document.getElementById('s').add(new Option('B','2',false,false));
document.getElementById('s').add(new Option('C','3',true,true));
}
</script>


VBScript:

<script language = 'vbscript'>
Function AddItem()
set Opt = document.createElement("option")
Opt.Text = "HSP"
Opt.Value = "s"
s.Add Opt, 0
set Opt1 = document.createElement("option")
Opt1.Text = "Test"
Opt1.Value = "T"
s.Add Opt1, 1
End Function
</script>



<select id = 's'></select>
<input type = 'button' onclick = "AddItem()" value = "Add Item" />
Call Page Function from User Control using Delegates

This article will explain you about how to call the function which is in Page from User Control button click. This same concept can be used to get values from user control to page.


In Below example, I have created one user control which contains one textbox and button control. Whenever the user click the button, the value of the textbox should be passed in function which is available in page.


TestUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUserControl.ascx.cs" Inherits="TestUserControl" %>

<div>
</div>
<asp:TextBox ID ="txtVal" runat = "server" ></asp:TextBox>
<asp:Button ID = "btn" runat = "server" OnClick = "ButtonClick" Text = "PassValue" />


TestUserControl.ascx.cs

public delegate void SendMessageToPageHandler(string Msg);
public event SendMessageToPageHandler evtSendMsg;

protected void ButtonClick(object sender, EventArgs e)
{
if (evtSendMsg != null)
{
evtSendMsg(txtVal.Text);
}
}

Here I declared the delegate with one string parameter. Also I have created one event with that delegate. This event will be fired when we click the button.
Now what we need to do is,
1. Create a function with one string parameter and no return value.
2. Assign the function reference into delegate which was created in user control.

callUserControls.aspx


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

<%@ Register Src="TestUserControl.ascx" TagName="TestUserControl" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:TestUserControl ID="TestUserControl1" runat="server" />
<asp:Label ID = "lbl" runat = "server"></asp:Label>
</div>
</form>
</body>
</html>


callUserControls.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
TestUserControl1.evtSendMsg += new TestUserControl.SendMessageToPageHandler(TestUserControl1_evtSendMsg);
}

void TestUserControl1_evtSendMsg(string Msg)
{
lbl.Text = "The Value is : " + Msg;
}

Or

You can also use Anonymous function like,


protected void Page_Load(object sender, EventArgs e)
{
TestUserControl1.evtSendMsg += delegate(string s) {
lbl.Text = "The Value is : " + s;};
}



Delegates



What is a delegate?
Delegate is type which holds the method(s) reference in an object. it is also referred as a type safe function pointers.
Advantages:
Ø Encapsulating the method's call from caller
Ø Effective use of Delegate improves the performance of application.
Ø Used to call a method asynchronously.
Syntax:
public delegate type_of_delegate delegate_name()
Example : public delegate int mydelegate(int param1,int param2)
Note
Ø you can use delegate without parameter or with parameter list
Ø you should follow the same syntax as in the method
If you are referring the method with two int parameters and int return type the delegate which you are declaring should be the same format. This is how it is referred as type safe function pointer.

Features of delegates:

Ø A delegate represents a class.
Ø A delegate is type-safe.
Ø We can use delegates both for static and instance methods
Ø We can combine multiple delegates into a single delegate.
Ø Delegates are often used in event-based programming, such as publish/subscribe.
Ø We can use delegates in asynchronous-style programming.
Ø We can define delegates inside or outside of classes.

Wednesday, October 8, 2008

Anonymous Methods/Delegates in C#.net

Anonymous Methods/Delegates in C#.net

C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible.

Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] evenIntegers = Array.FindAll(_integers,
delegate(int integer)
{
return (integer%2 == 0);
}
);

The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}
which is called for each integer in the array and returns either true or false depending on if the integer is even.
If you don't use an anonymous method, you will need to create a separate method as such:

private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] evenIntegers = Array.FindAll(_integers, IsEven);

private bool IsEven(int integer)
{
return (integer%2 == 0);
}
When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.

Sunday, July 13, 2008

Get Cursor Position using Javascript

To Get Cursor staring position using Javascript
function getSelectionStart(o)
{
if (o.createTextRange)
{
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
}
else
return o.selectionStart
}

To Get Cursor End position using Javascript
function getSelectionEnd(o)
{
if (o.createTextRange)
{
var r = document.selection.createRange().duplicate()
r.moveStart('character', -o.value.length)
return r.text.length
}
else
return o.selectionEnd
}

Wednesday, May 28, 2008

Draw Signature or images in Asp.net Web Page

You can draw images (like signature etc) in your web pages using Microsoft Ink assembly. Actually this is specially designed for Tablet PC. But we can use this in ASP.Net web pages too.
Visit here to more!