Search This Blog

Friday, May 28, 2010

How to convert amount into word

public string NumberToText(int number)
{
if (number == 0) return "Zero";
if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight";
int[] num = new int[4];
int first = 0;
int u, h, t;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (number < 0)
{
sb.Append("Minus ");
number = -number;
}
string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
string[] words3 = { "Thousand ", "Lakh ", "Crore " };
num[0] = number % 1000; // units
num[1] = number / 1000;
num[2] = number / 100000;
num[1] = num[1] - 100 * num[2]; // thousands
num[2] = num[2] - 100 * num[3]; // lakhs
num[3] = number / 10000000; // crores

for (int i = 3; i > 0; i--)
{
if (num[i] != 0)
{
first = i;
break;
}
}
for (int i = first; i >= 0; i--)
{
if (num[i] == 0) continue;
u = num[i] % 10; // ones
t = num[i] / 10;
h = num[i] / 100; // hundreds
t = t - 10 * h; // tens
if (h > 0) sb.Append(words0[h] + "Hundred ");
if (u > 0 || t > 0)
{
if (h > 0 || i == 0) sb.Append("and ");
if (t == 0)
sb.Append(words0[u]);
else if (t == 1)
sb.Append(words1[u]);
else
sb.Append(words2[t - 2] + words0[u]);
}
if (i != 0) sb.Append(words3[i - 1]);
}
return sb.ToString().TrimEnd();
}

Thursday, May 27, 2010

How to automatically rollback transact-sql when error raise

Syntax

SET XACT_ABORT { ON | OFF }

Remarks

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. For more information, see Distributed Queries and Distributed Transactions.

The setting of SET XACT_ABORT is set at execute or run time and not at parse time.
Examples

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 AdventureWorks2008R2;
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
Note: For more detail Click Here

TRANSACTION withinTRY…CATCH with XACT_STATE

Using TRY…CATCH with XACT_STATE

The following example shows how to use the TRY…CATCH construct to handle errors that occur inside a transaction. The XACT_STATE function determines whether the transaction should be committed or rolled back. In this example, SET XACT_ABORT is ON. This makes the transaction uncommittable when the constraint violation error occurs.


USE AdventureWorks2008R2;
GO

-- Check to see whether this stored procedure exists.
IF OBJECT_ID (N'usp_GetErrorInfo', N'P') IS NOT NULL
DROP PROCEDURE usp_GetErrorInfo;
GO

-- Create procedure to retrieve error information.
CREATE PROCEDURE usp_GetErrorInfo
AS
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_LINE () AS ErrorLine
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_MESSAGE() AS ErrorMessage;
GO

-- SET XACT_ABORT ON will cause the transaction to be uncommittable
-- when the constraint violation occurs.
SET XACT_ABORT ON;

BEGIN TRY
BEGIN TRANSACTION;
-- A FOREIGN KEY constraint exists on this table. This
-- statement will generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;

-- If the DELETE statement succeeds, commit the transaction.
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
EXECUTE usp_GetErrorInfo;

-- Test XACT_STATE:
-- If 1, the transaction is committable.
-- If -1, the transaction is uncommittable and should
-- be rolled back.
-- XACT_STATE = 0 means that there is no transaction and
-- a commit or rollback operation would generate an error.

-- Test whether the transaction is uncommittable.
IF (XACT_STATE()) = -1
BEGIN
PRINT
N'The transaction is in an uncommittable state.' +
'Rolling back transaction.'
ROLLBACK TRANSACTION;
END;

-- Test whether the transaction is committable.
IF (XACT_STATE()) = 1
BEGIN
PRINT
N'The transaction is committable.' +
'Committing transaction.'
COMMIT TRANSACTION;
END;
END CATCH;
GO

TRY…CATCH in a transaction

The following example shows how a TRY…CATCH block works inside a transaction. The statement inside the TRY block generates a constraint violation error.


BEGIN TRANSACTION;

BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT

ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;

IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO

Wednesday, May 26, 2010

Try catch in SQL

BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

Saturday, May 22, 2010

How to enable session in web service web method

[WebMethod(EnableSession = true)]
public CascadingDropDownNameValue[] GetCountryData(string knownCategoryValues, string category)
{
Thread.Sleep(500);
List Countries = new List();
StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int RegionId = Convert.ToInt32(sd["undefined"]);

CountryByRegionIdTableAdapter cbrta = new CountryByRegionIdTableAdapter();
CountryDataSet.CountryByRegionIdDataTable cbrdt = cbrta.GetCountryByRegionId(RegionId, SessionManager.CaseStudyUserID);

foreach (DataRow dr in cbrdt.Rows)
{
Countries.Add(new CascadingDropDownNameValue(Convert.ToString(dr["CountryName"]), Convert.ToString(dr["CountryID"])));
}

return Countries.ToArray();
}

Friday, May 21, 2010

How to use usrsor in sql

DEclare @RoleID INT
DEclare @WebPageID INT

DECLARE CaseStudy_Role CURSOR FOR SELECT RoleID FROM Role WHERE RoleID in (1,2,3,4,5)
OPEN CaseStudy_Role
FETCH NEXT FROM CaseStudy_Role INTO @RoleID
WHILE @@Fetch_status = 0
BEGIN
DECLARE CaseStudy_WebPage CURSOR FOR SELECT WebPageID FROM WebPage
OPEN CaseStudy_WebPage
FETCH NEXT FROM CaseStudy_WebPage INTO @WebPageID
WHILE @@Fetch_status = 0
BEGIN
INSERT INTO RoleRight VALUES(@WebPageID, @RoleID)
FETCH NEXT FROM CaseStudy_WebPage INTO @WebPageID
END
CLOSE CaseStudy_WebPage
DEallocate CaseStudy_WebPage

FETCH NEXT FROM CaseStudy_Role INTO @RoleID
END
CLOSE CaseStudy_Role
DEallocate CaseStudy_Role

Thursday, May 20, 2010

How to validate Email Id

<asp:TextBox ID="txtEmail" runat="server" Width="303px" Enabled="true" ReadOnly="false"> </asp:TextBox>
<asp:RequiredFieldValidator ID="RFVtxtEmailID1" runat="server" ControlToValidate="txtEmail"
InitialValue="" Enabled="true" Text="*" ForeColor="Red" Font-Bold="true" ErrorMessage="Enter Email Address">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
Display="Dynamic" ErrorMessage="Invalid Email Address." ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*
</asp:RegularExpressionValidator>

Thursday, May 6, 2010

How to set interval in javascript

Copy and save the entire code as a html file and see the result.

<html>
<head>
<script type="text/javascript">
function fls()
{
var date1 = new Date();
if(document.getElementById('spa1').style.color == 'red')
{

document.getElementById('spa1').style.color = 'blue';

}
else
{
document.getElementById('spa1').style.color = 'red';

}
document.getElementById('spa1').innerText = date1;
setTimeout('fls()',1000);

}
</script>
</head>
<body onload="javascript:fls();">
<div id='spa1' style='color: red;font-weight:bold;'> New </div>

</body>
</html>

How to get system date /time using javascript

Having created an instance of a Date( ) object using the Date Constructor (see the previous part of this series) any of the Date( ) object methods can be used to manipulate the data in the object. The methods available can be grouped by function as follows:

To get the various fields represented by the data contained in the Date( ) object:




getFullYear( ) return the four digit year
getMonth( ) return the month
getDate( ) return the day of the month
getDay( ) return the day of the week
getHours( ) return the hours
getMinutes( ) return the minutes
getSeconds( ) return the seconds
getMilliseconds( ) return the milliseconds

and to set those fields to a particular value:
setFullYear( ) set the four digit year
setMonth( ) set the month
setDate( ) set the day of the month
setDay( ) set the day of the week
setHours( ) set the hours
setMinutes( ) set the minutes
setSeconds( ) set the seconds
setMilliseconds( ) set the milliseconds

The use of these methods is fairly straightforward and is illustrated in the example below. Take special note, however, of the get and set Day and Month. Day is the day of the week expressed as an integer index value whose range, in typical JavaScript index value fashion, begins at zero. Thus, zero is Sunday, one is Monday, etc. with 6 being Saturday. Similarly, Month ranges from zero (January) to 11 (December).

The following two groups are the equivalent of the above, but where the time and date are expressed as Universal Time (ie GMT - see Timezone Offset in the next part of this series):
getUTCFullYear( ) return the Universal Time four digit year
getUTCMonth( ) return the Universal Time month
getUTCDate( ) return the Universal Time day of the month
getUTCDay( ) return the Universal Time day of the week
getUTCHours( ) return the Universal Time hours
getUTCMinutes( ) return the Universal Time minutes
getUTCSeconds( ) return the Universal Time seconds
getUTCMilliseconds( ) return the Universal Time milliseconds

setUTCFullYear( ) set the Universal Time four digit year
setUTCMonth( ) set the Universal Time month
setUTCDate( ) set the Universal Time day of the month
setUTCDay( ) set the Universal Time day of the week
setUTCHours( ) set the Universal Time hours
setUTCMinutes( ) set the Universal Time minutes
setUTCSeconds( ) set the Universal Time seconds
setUTCMilliseconds( ) set the Universal Time milliseconds

The following example determines how many days are left until a specific date -- in this case a birthday which occurs on December 15. The Date( ) object constructor is used to create two instances of the Date( ) object; one for today and one for the birthday. An "if" statement then checks to make sure the birthday hasn't already passed, and prints a message if not. The the time difference is obtained by subtracting today's value from the birthday value and dividing the resulting millisecond value into days. (The calculation uses Math.floor( ) which rounds a calculation down to the nearest integer value.)
Example
<SCRIPT language="javascript">

today = new Date( ); // set today's date
birthday = new Date( ); // set up the Birthday object

birthday.setMonth(11); // set birthday month to December
birthday.setDate(15); // set birthday date to the 15th

if (today.getTime( ) < birthday.getTime( ))
{ diff = birthday.getTime( ) - today.getTime( );
diff = Math.floor(diff / (1000 * 60 * 60 * 24));
document.write('There are ' + diff + ' days until December 15.');
}

</SCRIPT>


As an interesting exercise, try enhancing this script to determine if today is the birthday, or if this year's birthday has already passed (there's already code for that) and printing an appropriate message in each case.



In the next part of this series, we continue with the use of the Date( ) object methods.

Wednesday, May 5, 2010

How to convert Currency To word in Crystal report

if (CDbl ({@RS}) <= 99999) then
ToWords(CDbl ({@RS}),0)
else if (CDbl ({@RS}) <= 9999999) then
ProperCase(ToWords(CDbl (Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-5)),0) + " Lac " + ToWords(CDbl (Right (replace ({@RS}, ",",""),5)),0))
else if (CDbl ({@RS}) <= 999999999) then
ProperCase(
ToWords(CDbl (Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-7)),0) + " Crore "+
ToWords(CDbl (Right(Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-5),2)),0) + " Lac " +
ToWords(CDbl (Right (replace ({@RS}, ",",""),5)),0)
)
else if (CDbl ({@RS}) <= 99999999999) then
ProperCase(
ToWords(CDbl (Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-9)),0) + " Arab "+
ToWords(CDbl (Right(Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-7),2)),0) + " Crore "+
ToWords(CDbl (Right(Left (replace ({@RS}, ",",""), LEN(replace ({@RS}, ",",""))-5),2)),0) + " Lac " +
ToWords(CDbl (Right (replace ({@RS}, ",",""),5)),0)
)

Monday, May 3, 2010

How to round to 2 decimal places using javascript

Following lines are for rounding a number to specified decimal places.

function roundNumber(num, dec)
{
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

Above javascript function can be implement as follows

var roundedNumber = roundNumber(annualPremium,2);