Search This Blog

Tuesday, November 30, 2010

Common Regular Expressions

Common Regular Expressions




















Field ExpressionFormat SamplesDescription
Name^[a-zA-Z''-'\s]{1,40}$John Doe

O'Dell
Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. You can modify this list.
Social Security Number^\d{3}-\d{2}-\d{4}$111-11-1111Validates the format, type, and length of the supplied input field. The input must consist of 3 numeric characters followed by a dash, then 2 numeric characters followed by a dash, and then 4 numeric characters.
Phone Number^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$(425) 555-0123

425-555-0123

425 555 0123


1-425-555-0123
Validates a U.S. phone number. It must consist of 3 numeric characters, optionally enclosed in parentheses, followed by a set of 3 numeric characters and then a set of 4 numeric characters.
E-mail ^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$someone@example.comValidates an e-mail address.
URL^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$http://www.microsoft.comValidates a URL
ZIP Code^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$12345Validates a U.S. ZIP Code. The code must consist of 5 or 9 numeric characters.
Password(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$ Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
Non- negative integer^\d+$0


986
Validates that the field contains an integer greater than zero.
Currency (non- negative)^\d+(\.\d\d)?$1.00Validates a positive currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point. For example, 3.00 is valid but 3.1 is not.
Currency (positive or negative)^(-)?\d+(\.\d\d)?$1.20Validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point.

Thursday, November 25, 2010

How to find all tables and its definition in current sql database

Below query will show you all tables definition with column details.

SELECT
SysObjects.[Name] as TableName,
SysColumns.[Name] as ColumnName,
SysTypes.[Name] As DataType,
SysColumns.[Length] As Length
FROM SysObjects
INNER JOIN SysColumns ON SysObjects.[Id] = SysColumns.[Id]
INNER JOIN SysTypes ON SysTypes.[xtype] = SysColumns.[xtype]
WHERE
SysObjects.[type] = 'U'
ORDER BY SysObjects.[Name]


SysObjects.[Type] value's details

1: C = CHECK constraint
2: D = Default or DEFAULT constraint
3: F = FOREIGN KEY constraint
4: FN = Scalar function
5: IF = Inlined table-function
6: K = PRIMARY KEY or UNIQUE constraint
7: L = Log
8: P = Stored procedure
9: R = Rule
10: RF = Replication filter stored procedure
11: S = System table
12: TF = Table function
13: TR = Trigger
14: U = User table
15: V = View
16: X = Extended stored procedure

Wednesday, November 24, 2010

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during ..

"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request"

When you are using FormView with ItemTemplate , InsertItemTemplate and EditItemTemplate and you click any event like save, update or delete. After this you click on any postback control then you may get the above exception.

Cause: All template FormView may have different control definition e.g. ItemTemplate does not match control definition with IsertItemTemplate or EditItemTemplate(number of controls or mismatch of control ids')

Solution: Try to keep same control definition in all template

Note: Try to not include ItemTemplate in your FormView

Monday, November 8, 2010

Backup ALL your SQL Server 2005 databases using ONE script

DECLARE @DBName varchar(255)

DECLARE @DATABASES_Fetch int

DECLARE DATABASES_CURSOR CURSOR FOR
select
DATABASE_NAME = db_name(s_mf.database_id)
from
sys.master_files s_mf
where
-- ONLINE
s_mf.state = 0
-- Only look at databases to which we have access
and has_dbaccess(db_name(s_mf.database_id)) = 1

-- Not master, tempdb or model
and db_name(s_mf.database_id) not in ('Master','tempdb','model','ReportServer$SQL2K5','ReportServer$SQL2K5TempDB')
group by s_mf.database_id
order by 1

OPEN DATABASES_CURSOR
FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
declare @DBFileName varchar(256)
set @DBFileName = datename(dw, getdate()) + ' - ' +
replace(replace(@DBName,':','_'),'\','_')
exec ('BACKUP DATABASE [' + @DBName + '] TO DISK = N''E:\DatabaseBACKUP\' +
@DBFileName + ''' WITH NOFORMAT, INIT, NAME = N''' +
@DBName + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 100')

FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
END
CLOSE DATABASES_CURSOR
DEALLOCATE DATABASES_CURSOR

Thursday, October 14, 2010

ASP.NET Page Getting PostBack Twice

When Postback getting twice in a page life cycle. It means your page having a <TD>,<TR> or <BODY> tag with attribute BACKGOUND e.g. BACKGOUND="#ffffff" or an image tag with empty image source e.g. <img src="" />.
If you replace BACKGOUND to bgcolor and do not keep image source empty then you will not get postback twice.

Thursday, September 23, 2010

Differences between varchar and nvarchar in SQL Server

The broad range of data types in SQL Server can sometimes throw people through a loop, especially when the data types seem to be highly interchangeable. Two in particular that constantly spark questions are VARCHAR and NVARCHAR: what's the difference between the two, and how important is the difference?

VARCHAR is an abbreviation for variable-length character string. It's a string of text characters that can be as large as the page size for the database table holding the column in question. The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters. This in turn limits the maximum size of a VARCHAR to 8,000 bytes.

The "N" in NVARCHAR means uNicode. Essentially, NVARCHAR is nothing more than a VARCHAR that supports two-byte characters. The most common use for this sort of thing is to store character data that is a mixture of English and non-English symbols — in my case, English and Japanese.

The key difference between the two data types is how they're stored. VARCHAR is stored as regular 8-bit data. But NVARCHAR strings are stored in the database as UTF-16 — 16 bits or two bytes per character, all the time — and convert

Friday, September 17, 2010

Export to Excel with proper fomatting:

Hope from above example now one can easily export data from GridView. But an important concern is to setthe formatting to the target file. In this reagard mso-number-format ease our life. Lets we need todisplay date & time in the GridView but we wants short date format when exporting. To do the one can use mso-number-format in the following way. Modify your export button click event by the following code segment.

string datestyle = @"<style>.date { mso-number-format:'Short Date'; }</style>";
foreach(GridViewRow oItem in gvEdit.Rows)
oItem.Cells[4].Attributes.Add("class","date");
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
Response.Write(datestyle);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();
-------------------------------------




List of some useful mso-number-format:

FormatDescription
mso-number-format:"0"NO Decimals
mso-number-format:"0\.000"3 Decimals
mso-number-format:"\#\,\#\#0\.000Comma with 3 dec
mso-number-format:"mm\/dd\/yy"Date7
mso-number-format:"mmmm\ d\,\ yyyy"Date9
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM"Date -Time AMPM
mso-number-format:"Short Date"04/07/2008
mso-number-format:"Medium Date"04-Jun-08
mso-number-format:"d\-mmm\-yyyy"04-Jun-2008
mso-number-format:"Short Time"4:49
mso-number-format:"Medium Time"4:49 am
mso-number-format:"Long Time"4:49:13:00
mso-number-format:"Percent"Percent with two dec.
mso-number-format:"0%"Percent with no dec.
mso-number-format:"0\.E+00"Scientific Notation
mso-number-format:"\@"Text
mso-number-format:"\#\ ???/???"Fractions up to 3 digits
mso-number-format:"\0022£\0022\#\,\#\#0\.00"£10.52
mso-number-format:"0\.0000";font-weight:700;4 dec.+multiple format


Note:
If you do not find your required format from above list then try creating a spreadsheet with a single cell entry according to your required format. Then from file menu select the 'Save as Web Page' option to create a html file. Read & examine the code for this and findout the mso-number-format from the style declarations.

Saturday, July 10, 2010

How to update login of a database?

To update login information of a database use following sql statement:

sp_change_users_login 'Update_One', 'UserNamePatn', 'csurvey'

where 'Update_One' is action,UserNamePatn is user's name pattern and csurvey is login name

Thursday, July 8, 2010

What are SQL Server Constraints?













 



Using Microsoft SQL Server Constraints








Introduction


In this article, I want to tell you about SQL Server constraints: what
a constraint is, when it is used and for which purposes. You can find
in this article some examples of constraint creation and SQL Server 2000
constraints enhancements.


General Concepts


A constraint is a property assigned to a column or the set of columns
in a table that prevents certain types of inconsistent data values from
being placed in the column(s). Constraints are used to enforce the data
integrity. This ensures the accuracy and reliability of the data in the
database. The following categories of the data integrity exist:



  • Entity Integrity

  • Domain Integrity


  • Referential integrity

  • User-Defined Integrity




  • Entity Integrity ensures that there are no duplicate rows in a table.

    Domain Integrity enforces valid entries for a given column by restricting the type,
    the format, or the range of possible values.

    Referential integrity ensures that rows cannot be deleted, which are used by
    other records (for example, corresponding data values between tables will be vital).


    User-Defined Integrity enforces some specific business rules that do not fall
    into entity, domain, or referential integrity categories.



    Each of these categories of the data integrity can be enforced by the
    appropriate constraints. Microsoft SQL Server supports the following constraints:



  • PRIMARY KEY

  • UNIQUE

  • FOREIGN KEY

  • CHECK

  • NOT NULL




  • A PRIMARY KEY constraint is a unique identifier for a row within a database
    table. Every table should have a primary key constraint to uniquely identify
    each row and only one primary key constraint can be created for each table.
    The primary key constraints are used to enforce entity integrity.



    A UNIQUE constraint enforces the uniqueness of the values in a set of
    columns, so no duplicate values are entered. The unique key constraints
    are used to enforce entity integrity as the primary key constraints.



    A FOREIGN KEY constraint prevents any actions that would destroy link
    between tables with the corresponding data values. A foreign key in one
    table points to a primary key in another table. Foreign keys prevent
    actions that would leave rows with foreign key values when there are
    no primary keys with that value. The foreign key constraints are used
    to enforce referential integrity.



    A CHECK constraint is used to limit the values that can be placed in a
    column. The check constraints are used to enforce domain integrity.



    A NOT NULL constraint enforces that the column will not accept null
    values. The not null constraints are used to enforce domain integrity,
    as the check constraints.



    You can create constraints when the table is created, as part of the
    table definition by using the CREATE TABLE statement.



    Examples


    The following example creates a check_sale CHECK constraint on an employee table:




    CREATE TABLE employee(
    EmployeeId INT NOT NULL,
    LName VARCHAR(30) NOT NULL,
    FName VARCHAR(30) NOT NULL,
    Address VARCHAR(100) NOT NULL,
    HireDate DATETIME NOT NULL,
    Salary MONEY NOT NULL CONSTRAINT check_sale CHECK (salary > 0)
    )


    You can add constraints to an existing table by using the ALTER TABLE
    statement. The following example adds a pk_employee primary key constraint
    on an employee table:




    ALTER TABLE employee
    ADD CONSTRAINT pk_employee PRIMARY KEY (EmployeeId)


    You can add the primary or unique key constraint into an existing
    table only when there are no duplicate rows in the table. You can
    drop constraints in an existing table by using the ALTER TABLE statement.
    The following example drops the pk_employee primary key constraint in the
    employee table:




    ALTER TABLE employee
    DROP CONSTRAINT pk_employee


    Sometimes you need to perform some actions that require the FOREIGN KEY
    or CHECK constraints be disabled, for example, your company do not hire
    foreign employees, you made the appropriate constraint, but the situation
    was changed and your boss need to hire the foreign employee, but only
    this one. In this case, you need to disable the constraint by using the
    ALTER TABLE statement. After these actions will be performed, you can
    re-enable the FOREIGN KEY and CHECK constraints by using the ALTER TABLE
    statement.



    The following example disables the check_sale constraint in the employee
    table and enables this constraint later:




    -- disable the check_sale constraint in the employee table
    ALTER TABLE employee NOCHECK CONSTRAINT check_sale



    -- enable the check_sale constraint in the employee table
    ALTER TABLE employee CHECK CONSTRAINT check_sale


    SQL Server 2000 Constraints Enhancements


    SQL Server 2000 introduces many new features. Some of them fall into the
    constraints area. Now you can control the actions SQL Server 2000 takes
    when you attempt to update or delete a key to which existing foreign keys
    point. You can control it by using the new ON DELETE and ON UPDATE clauses
    in the REFERENCES clause of the CREATE TABLE and ALTER TABLE statements.
    For example, in the previous versions of SQL Server if you wanted to do a
    cascade delete from the referenced table when the appropriate record in
    the parent table is deleted, you had to create a trigger which executed
    on delete of the parent table, but now you can simply specify the ON DELETE
    clause in the REFERENCES clause.



    The following example is used to create the Books and the Authors tables
    and create a foreign key constraint which will perform the cascade delete
    action, therefore, when a row in the Authors table is deleted, the
    corresponding rows in the Books are also deleted:




    CREATE TABLE Books (
    BookID INT NOT NULL PRIMARY KEY,
    AuthorID INT NOT NULL,
    BookName VARCHAR(100) NOT NULL,
    Price MONEY NOT NULL
    )
    GO

    CREATE TABLE Authors (
    AuthorID INT NOT NULL PRIMARY KEY,
    Name VARCHAR(100) NOT NULL
    )
    GO

    ALTER TABLE Books
    ADD CONSTRAINT fk_author
    FOREIGN KEY (AuthorID)
    REFERENCES Authors (AuthorID) ON DELETE CASCADE
    GO


    Conclusion



    Constraints are the built-in mechanism for enforcing data integrity. Using
    constraints is preferred to using triggers, rules, and defaults because
    built-in integrity features use much less overhead and perform faster than
    the ones you can create. When you write your own code to realize the same
    actions the constraints can make you can make some errors, so the constraints
    are not only faster, but also are more consistent and reliable. So, you
    should use triggers and rules only when the constraints do not provide all
    the needed functionality.














     










    Thursday, June 10, 2010

    What is Web Services?

    Web Services are the underpinning of Microsoft's .NET strategy. The concepts and the innovations behind this initiative have struck a chord with developer's building the next generation of Internet applications.

    In this month's column, we're going to take a look at the features within ASP.NET to enable Web Services. Before we dig into the technical details let's start with an overview of Web Services.

    Web Services Overview
    A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.

    Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

    Soap Message

    A SOAP message consists of several elements, most notably an envelope. The envelope encapsulates the data transmitted within the SOAP message. Below is a simple SOAP message complete with HTTP headers:





    POST /demo/MSDN/PerfCounter.asmx HTTP/1.1
    Connection: Keep-Alive
    Content-Length: 150
    Content-Type: text/xml
    Host: localhost
    User-Agent: MS Web Services Client Protocol 1.0.2204.19
    SOAPAction: "http://tempuri.org/PerfCounters"

    <?xml version="1.0"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <soap:Body>
    <PerfCounters xmlns="http://tempuri.org/"/>
    </soap:Body>
    </soap:Envelope>

    In the example above, we see the HTTP headers for the request, including the HTTP SOAPAction header, which is optionally used by the server for routing the SOAP message. Following the HTTP headers we find the body of the HTTP message. The body of the HTTP message is the SOAP request for a PerfCounters Web Service, which we are going to build.

    Unfortunately we don't have nearly enough room in this column to discuss SOAP in depth. To learn more about SOAP, please see the SOAP Developer Resources page. Here you can find the public specification for SOAP 1.1 as well as articles and other relevant resources.

    ASP.NET Web Services

    Web Services are simple and easy to understand. It is possible, in fact, to author a simple application that surfaces data as XML conforming to the SOAP specification. It would also be relatively straightforward to build an application capable of receiving SOAP messages over HTTP and deriving meaningful value out of it. For those of you familiar with PERL, this could simply be a matter of using RegEx to parse the value out of the XML result; it's just another string.

    However, just as we use frameworks such as ASP and ASP.NET to build Web applications, we would much rather use a framework for building Web Services. The reasoning is quite logical. We don't need to reinvent the plumbing—that is, at a high level, the capability to serialize our data as XML, transport the data using HTTP, and de-serialize the XML back to meaningful data. Instead, we want a framework that makes building Web Services easy, allowing us to focus on the application logic not the plumbing. ASP.NET provides this framework for us.

    From a developer's point of view, if you have ever written application logic, you have the required skills to author ASP.NET Web Services. More importantly, if you're at all familiar with ASP or ASP.NET application services, (application state memory, and so on) you can also leverage these skills when you build ASP.NET Web Services.

    Exposing

    For the purpose of example, we're going to write a Web Service that exposes Web application performance counters. Performance counters provide us with details about the behavior of our application, such as the number of active sessions or the number of requests served. We don't always have local server access to our Web server, and if we have a farm of servers we might want to expose the performance counters from all these servers and aggregate them in a central location.

    Starting with a Simple Example

    Rather than jumping straight into the Performance Counters example, let's start with some very simple application logic so we can see what we need to do to expose our logic as a Web Service. We'll use an Add() method that accepts two Integers and returns their sum. Below is this simple Visual Basic logic:






    Public Class MyMath
    Public Function Add(a As Integer, b As Integer) As Integer
    Return a + b
    End Function
    End Class



    We could use this class and its method as follows:





    Dim mymath As new MyMath
    Dim result As Integer
    result = mymath.Add(10, 20)



    To expose the above class, MyMath, as an ASP.NET Web Service we need to move the application logic into a *.asmx file. Just as we use the extension *.aspx for ASP.NET Pages, we use *.asmx to tell ASP.NET that the file is an ASP.NET Web Service.

    After we created the *.asmx source file and add our application logic, we need to make a few more small changes:







    <%@ WebService Language="VB" Class="MyMath" %>
    Public Class MyMath
    Public Function <WebMethod()>Add(a As Integer, b As Integer) As Integer
    Return a + b
    End Function
    End Class



    Changes to our source

    The changes we've made to the *.asmx file include adding a WebService directive that names both the Language as well as the Class we're exposing as a Web Service. The WebService directive is required, as we must tell ASP.NET the class that contains the application logic. Next, we've added a attribute to our Add() function declaration. An attribute is a declarative code element that lets us change the behavior of our application logic without necessarily writing more code. In the case of the attribute, this tells ASP.NET that the method with this attribute is to be treated as 'Web callable'. Web callable in the sense that ASP.NET does the necessary work for this method to support SOAP.

    Now that we've seen what needs to be done to enable application logic as Web callable, let's look at a more relevant sample.
    Performance Counter Web Service

    Below is application logic that gives us access to the Windows® performance counters, with the changes for ASP.NET Web Services. The file we've created is PerfCounter.asmx:





    <%@ WebService language="VB" class="PerfCounters" %>
    Imports System.Xml.Serialization
    Imports System.Web.Services
    Imports System.Diagnostics

    Public Class PerfCounters
    Inherits WebService

    ' Returns a Counter class
    Public Function GetCounters() As Counters
    Dim c As new Counters

    ' Application Name
    c.ApplicationName �� = IISAppName

    ' System specific
    c.WorkerProcessRestarts = Poll(0, "Worker Process Restarts")
    c.WorkerProcessRunning = Poll(0, "Worker Process Running")
    c.ApplicationsRunning = Poll(0, "Applications Running")
    c.RequestsQueued = Poll(0, "Requests Queued")

    ' Application Specific
    c.RequestsTotal = Poll(1, "Requests Total")
    c.RequestsFailed = Poll(1, "Requests Failed")
    c.RequestsSucceeded = Poll(1, "Requests Succeeded")
    c.ActiveSessions = Poll(1, "Sessions Active")

    Return c
    End Function

    Private Function Poll(counterType As Integer, counter As String) As Integer
    Dim PerfCounter As PerformanceCounter

    If (counterType = 0)
    PerfCounter = new PerformanceCounter("ASP Plus System", counter, "")
    Else
    PerfCounter = new PerformanceCounter("ASP Plus Applications", counter, IISAppName)
    End If

    Return PerfCounter.NextValue().ToInt32()
    End Function

    Private Function IISAppName() As String
    Dim AppName As String

    AppName = Context.Request.ServerVariables("APPL_MD_PATH")
    AppName = AppName.Replace("/"C, "_"C)

    Return AppName
    End Function
    End Class

    Public Class Counters
    Public ApplicationName As String
    Public WorkerProcessRestarts As Integer
    Public WorkerProcessRunning As Integer
    Public ApplicationsRunning As Integer
    Public RequestsQueued As Integer
    Public RequestsTotal As Integer
    Public RequestsFailed As Integer
    Public RequestsSucceeded As Integer
    Public ActiveSessions As Integer
    End Class


    Again we see that we've declared a WebService directive at the top of the file noting both the language and the class. The class that contains the Web callable method is PerfCounters. Within PerfCounters we find a single method, GetCounters(), with the attribute. GetCounters() returns an instance of another class, Counters.

    When we call GetCounters(), the method creates a new instance of the Counter class and begins to set its public members; note, these public members should be implemented as properties, but I chose to save the space for the purpose of the article.

    When the Counter class' members are set, we're setting them with the returned result of a call to a private method Poll(). Poll() is responsible for doing the actual work of polling the systems performance counters and returning a result.

    Finally, the last method, IISAppName(), returns the value of the server variable APPL_MD_PATH and replaces '/' characters with '_' characters; this value is used as the application name within the performance counters.

    Now that we've built the service, let's take a look at how we test it.

    Testing Web Services


    Now that we've authored this ASP.NET Web Service, how do we test it? The consumer of a Web Service is another application, but ASP.NET provides a simple browser interface to our Web Service that we can use for testing or documentation purposes.

    Since our service is exposed as a resource available from our Web server, we can simply open a browser and make a request for that resource. Doing so provides us with a nice HTML-based Web Service Help page that lets people learn about what our service provides:

    Figure 1. HTML-based Web Service Help page

    ASP.NET generates the above page for us, and we can use it to test our service (note the HTML Invoke button within the GetCounters Web Method section) and access the XML contract language used to describe what our service offers; we'll be coming back to the XML contract language momentarily.

    If we press the Invoke button, a new browser window is opened, and a request is made to our service using HTTP-Get; one of the three supported protocols used by ASP.NET Web Services:


    Figure 2. Example of the new browser window that is created when pressing the Invoke button.

    The XML returned is a valid XML document that describes all of the settings we identified in our Counters class. However, it is not SOAP. SOAP is the default protocol that is used when we do application-to-application communication.

    Although we didn't discuss it in this article, we can customize our help page quite extensively. This is done by making some changes to the ASP.NET configuration system, or modifying the DefaultSDLHelpGenerator.aspx. I would recommend not modifying the DefaultSDLHelpGenerator.aspx, as this is the template used for all our Web Services. Instead, make a copy of it and reference the copied version in the application's configuration that makes use of it.

    Now that we've discussed authoring and testing our Web Service, let's make use of it.

    Consuming


    We have several options for consuming Web Services. Since this article is about ASP.NET, we'll focus on .NET technologies that can consume Web Services. However, I should point out that any platform or framework that understands SOAP should be able to communicate with our Web Service. Building the Web Service with ASP.NET does not mean that the service is only available to other Microsoft applications.

    Consumers of a Web Service need to know what the service offers—for example, what its Web callable method look like. Therefore, all Web Services optionally share another common XML document: a contract (note, Web Services built with ASP.NET always have a contract provided automatically).

    Contract

    In the examples above when we discussed testing a Web Service, we didn't discuss the link found within Web Service Help Page: SDL Contract. If we were to follow that link, instead of pressing the Invoke button for the GetCounters() Web Method, we would be presented with the following XML document:

    Figure 3. XML document presented when following the link found within the Web Service Help Page

    This XML document is a contract that describes our Web Service. It details the protocols supported as well as the semantics for calling and returning values. It additionally defines an XML schema for our Counters class.

    Tools can use this XML schema to build proxy classes for our Web Service. A proxy class is a class that looks and feels like a local object, but it is in fact doing the work to serialize, send, receive, and de-serialize our method request to a SOAP endpoint.

    Note Beta 1 of .NET surfaces an "SDL—Service Description Language" contract, Beta 2 will switch to use the more recent "WSDL—Web Service Description Language" contract. Semantically they are very different. WSDL is the collaborative work of Microsoft, IBM, and several other companies to better standardize the XML contract language.

    We have various options for consuming Web Services, however, I'd like to call out three in particular:

    * Visual Studio .NET: —Visual Studio .NET does the work of creating the proxy from the SDL or WSDL and adds the appropriate code to our project. This is done by simply selecting Project | Web References, and then pointing at a valid contract. Note that for beta 1 the contract must be SDL.
    * Command Line Tools: —The .NET SDK ships with a tool called WebServiceUtil.exe that accepts an SDL contract and can generate the proxy source code for Visual Basic .NET, C#, or JScript.NET.
    * IE 5.5. Behavior: —A browser specific behavior that allows for rich client interaction with SOAP end-points. For those of you familiar with Remote Scripting, you're going to love this! To learn more about the IE 5.5 behavior, please see WebService Behavior.

    Unfortunately, we don't have the space to discuss these three options in detail. However, I thought it would be worthwhile to briefly cover building a proxy with the command line tool, as this is applicable to those who have installed .NET; not just those that have Visual Studio .NET.

    Command line tool

    .NET, whether you install it as part of Visual Studio .NET or the .NET SDK, includes a command line proxy generation tool called WebServiceUtil.exe. The path to this command line tool, as well as several other command line tools, is added to our path when we installed .NET.

    WebServiceUtil.exe allows us to name a SDL, or contract, as one of the command line arguments and the tool can then generate the source code for a proxy to our Web Service.

    If, for example, we were to save the SDL from our PerfCounters.asmx example, we could use WebServiceUtil.exe to generate a Visual Basic .NET proxy to this Web Service:






    WebServiceUtil.exe /command:proxy PerfCounter.sdl /language:VB


    This generates a source file PerfCounters.vb that we now need to compile.

    Using the VB.NET command line compiler, vbc.exe, we can compile our VB source file:






    vbc /t:library /r:system.web.dll /r:system.web.services.dll /r:system.xml.serialization.dll perfcounters.vb


    What we've done with the command line compiler is specify that we want to create a library (dll) rather than an executable (exe), and in addition to naming the source file to compile, we've specified some .NET assemblies (libraries containing classes our source file requires) as arguments to the compiler.

    The result is PerfCounters.dll, a complete proxy to our PerfCounters.asmx ASP.NET Web Service that we can now use in .NET applications to communicate via SOAP to our Web Service.

    Let's use this proxy to build a simple ASP.NET page that consumes and uses our Web Service.

    Using the Web Service

    First we need to deploy the compiled proxy, known as an assembly, to a Web application's \bin directory. Although we haven't discussed deploying compiled code in this column yet (yet another topic for a future column), suffice to say that to 'register' an assembly on the system simply requires copying the *.dll to a Web application's \bin directory. This is a feature of .NET, but the use of the \bin directory is specific for ASP.NET.

    To make things simple, we'll create a bin directory off of the server's root directory, c:\inetpub\wwwroot\bin for example. A \bin directory must exist in an application root, either the root of the Web or a folder marked as an application in IIS.

    Next, we copy our assembly, PerfCounters.dll, to our \bin directory. We can now author our ASP.NET page, which we'll deploy to c:\inetpub\wwwroot. We'll call it PerfCountersConsume.aspx:






    <Script runat="server">
    Public Sub Page_Load(sender As Object, e As EventArgs)
    Dim perfcounters As New PerfCounters
    Dim counters As Counters

    counters = perfcounters.GetCounters()

    webapp.InnerHtml = counters.ApplicationName
    restarts.InnerHtml = counters.WorkerProcessRestarts.ToString()
    procrunning.InnerHtml = counters.WorkerProcessRunning.ToString()
    apprunning.InnerHtml = counters.ApplicationsRunning.ToString()
    queued.InnerHtml = counters.RequestsQueued.ToString()
    totalrequests.InnerHtml = counters.RequestsTotal.ToString()
    failedrequests.InnerHtml = counters.RequestsFailed.ToString()
    succeededrequests.InnerHtml = counters.RequestsSucceeded.ToString()
    activesessions.InnerHtml = counters.ActiveSessions.ToString()
    End Sub
    </Script>
    Web Application: <B id="webapp" runat="server"/><BR>
    Process Restarts: <B id="restarts" runat="server"/><BR>
    Processes Running: <B id="procrunning" runat="server"/><BR>
    Applications Running: <B id="apprunning" runat="server"/><BR>
    Requests Queued: <B id="queued" runat="server"/><BR>
    Requests Total: <B id="totalrequests" runat="server"/><BR>
    Requests Failed: <B id="failedrequests" runat="server"/><BR>
    Requests Succeeded: <B id="succeededrequests" runat="server"/><BR>
    Active Sessions: <B id="activesessions" runat="server"/><BR>


    The code above creates an instance of our proxy class PerfCounters (available to us since it's a registered assembly in our \bin directory) calls its GetCounters() method and returns an instance of a Counters class. We then use the instance of the Counters class, counters, to request its member variables and populate ASP.NET server controls. The result is below:

    Figure 4. ASP.NET server controls

    Summary

    This column has taken a very high level overview of ASP.NET Web Services. There's quite a bit of detail that we either glossed over or didn't cover at all, for example security, use of session state, extensions, and so on. In next month's column we're going to look at a more advanced feature of ASP.NET Web Services, extensions, that we can use for building attributes that allow us to trace the request/response of our ASP.NET Web Service.
    Note: For more detail Click Here

    Wednesday, June 9, 2010

    What is Abstraction?

    Abstraction
    Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.
    Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
    So abstraction says expose only the details which are concern with the user (client) of your object. So the client who is using your class need not to be aware of the inner details like how you class do the operations? He needs to know just few details. This certainly helps in reusability of the code.
    As I have generally seen developers are not very much comfortable with the database programming. Let’s say you are designing a class that is used to interact with the database and to perform some of database operations. Now client of your class need not to be aware of database programming, he just need to be aware of some of the details of your class and easily can perform the database operations exposed by your class without deep knowledge of database programming.
    The best thing of abstract is that this decouples the user of the object and its implementation. So now object is easy to understand and maintain also. As if there is any change in the process of some operation. You just need to change the inner details of a method, which have no impact on the client of class.

    Friday, June 4, 2010

    How to get last date of a month using sql query

    Below statement will return the last date of the current month:

    SELECT DAY(DATEADD (m, 1, DATEADD (d, 1 - DAY(GETDATE()), GETDATE())) - 1)

    How to use sql ALTER TABLE statement

    The ALTER TABLE statement is used to add, delete or modify an sql existing table.

    To add a column in a table, use the following syntax:
        ALTER TABLE table_name
        ADD column_name datatype


    To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
        ALTER TABLE table_name
        DROP COLUMN column_name


    To change the data type of a column in a table, use the following syntax:
        ALTER TABLE table_name
        ALTER COLUMN column_name datatype

    Thursday, June 3, 2010

    How to enable the use of 'Ad Hoc Distributed Queries' by using sp_configure






    If you are planning to use OpenRowset queries in order to connet to remote database servers or if you have already implemented OpenRowset queries as a solution to remote connections as an alternative tp linked servers in Microsoft SQL Server 2005, you should first configure the database instance to enable Ad Hoc Distributed Queries in the installed SQL Server database instance where the Ad Hoc query will run.

    There are two ways that you can configure MS SQL Server 2005 or
    SQL Server 2008 Katmai instance for Ad Hoc Remote Queries:
  • You can either use SQL Server Surface Area Configuration Tool

  • Or you can use sp_configure stored procedure to enable the ad hoc connections to remote data sources

  • Although I'm sure I have configured all necessary configuration settings in the database server to let OpenRowset functions, after months later the application is released for the production site, I had the following error from an application recently:

    An error occured while trying to execute the query:

    - CODBCQuery.Open, SQLExecDirect 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server.

    A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQK Server Books Online. 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Could not use view or function '{0}' because of binding errors.



    In fact, the error message is self-explaining the situation.

    It is indicating that in order to run the OpenRowset and the OpenDatasource statements the turned off configuation settings for the related sql database server should be enabled.


    First, let's check the SQL 2005 configuration settings using sp_configure sql command.






    Now, we should connect to the related SQL Server as an administrator and open a new query window.


    After the query window is ready for running sql statements run the "sp_configure" sql statement.


    If sp_configure command only lists a limited number (~14) of sql configuation settings, where 'Ad Hoc Distributed Queries' does not exist in the returned result set, we should open/enable the 'show advanced options' configuration parameter.


    You can see 'show advanced options' in the list with run_value equals to "0" in such a situation.



    To set 'show advanced options' run_value equal to 1 or to enable it, run





    sp_configure 'show advanced options', 1

    reconfigure


    The return message from the above sql statements for a successful run is as;





    Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.



    After Advanced Options is enabled, you can again run sp_configure t-sql command and in the returned list of configuration settings, go to row where name is 'Ad Hoc Distributed Queries' and control its run_value.
    If 'Ad Hoc Distributed Queries' is turned off for considering server security run_value should be "0"

    But since we want to enable 'Ad Hoc Distributed Queries' component in order to run 'OpenRowset/OpenDatasource' sql statements, we should set the run_value to "1"



    The below sql code is a sample how you can enable a SQL Server configuration parameter.




    sp_configure 'Ad Hoc Distributed Queries', 1






    The returned message is :





    Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.



    A change with sp_configure comment will require reconfigure command to run in order to the new setting takes effect. So just run the "reconfigure" command:




    reconfigure


    Now you can see the run_value is set to 1 if you run the "sp_configure" command and control for the "Ad Hoc Distributed Queries" row.


    Now you can run your OpenRowset queries successfully from your SQL Server 2005 or SQL Server 2008 (Katmai) databases.



    Second, use the SQL Server Surface Area Configuration Tool to enable and/or disable "Ad Hoc Remote Queries".



    The OpenRowset and OpenDatasource functions support ad hoc connections to remote data sources without linked or remote servers.
    We can enable these functions by checking the "Enable OPENROWSET and OPENDATASOURCE support" checkbox.


    How to use OPENDATASOURCE

    Provides ad hoc connection information as part of a four-part object name without using a linked server name
    Syntax:
        OPENDATASOURCE ( provider_name, init_string )

    Arguments

    provider_name
    Is the name registered as the PROGID of the OLE DB provider used to access the data source. provider_name is a char data type, with no default value.

    init_string
    Is the connection string passed to the IDataInitialize interface of the destination provider. The provider string syntax is based on keyword-value pairs separated by semicolons, such as: 'keyword1=value;keyword2=value'.

    For specific keyword-value pairs supported on the provider, see the Microsoft Data Access SDK. This documentation defines the basic syntax. The following table lists the most frequently used keywords in the init_string argument.


    Keyword

    OLE DB property

    Valid values and description

    Data Source

    DBPROP_INIT_DATASOURCE

    Name of the data source to connect to. Different providers interpret this in different ways. For SQL Server Native Client OLE DB provider, this indicates the name of the server. For Jet OLE DB provider, this indicates the full path of the .mdb file or .xls file.

    Location

    DBPROP_INIT_LOCATION

    Location of the database to connect to.

    Extended Properties

    DBPROP_INIT_PROVIDERSTRING

    The provider-specific connect-string.

    Connect timeout

    DBPROP_INIT_TIMEOUT

    Time-out value after which the connection try fails.

    User ID

    DBPROP_AUTH_USERID

    User ID to be used for the connection.

    Password

    DBPROP_AUTH_PASSWORD

    Password to be used for the connection.

    Catalog

    DBPROP_INIT_CATALOG

    The name of the initial or default catalog when connecting to the data source.

    Integrated Security

    DBPROP_AUTH_INTEGRATED

    SSPI, to specify Windows Authentication



    Examples

    The following example creates an ad hoc connection to the Payroll instance of SQL Server on server London, and queries the AdventureWorks2008R2.HumanResources.Employee table. (Use SQLNCLI and SQL Server will redirect to the latest version of SQL Server Native Client OLE DB Provider.)
    ------------------
    SELECT *
    FROM OPENDATASOURCE('SQLNCLI',
    'Data Source=London\Payroll;Integrated Security=SSPI')
    .AdventureWorks2008R2.HumanResources.Employee

    ------------------
    The following example creates an ad hoc connection to an Excel spreadsheet in the 1997 - 2003 format.
    ------------------
    SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
    'Data Source=C:\DataFolder\Documents\TestExcel.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] ;
    ------------------
    Note: For more detail click here

    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);

    Friday, April 30, 2010

    How to skip javascript error.

    <script type="text/javascript">
    window.onerror=function(){
    alert('An error has occurred!')
    return true
    }
    </script>

    Friday, April 23, 2010

    Forms Authentication with Active Directory







    Using Forms Authentication with Active Directory


    Forms Authentication


    Forms Authentication is a system in which unauthenticated requests are redirected to a Web form
    where users are required to provide their credentials.



    Upon submitting the form, and being properly verified by your application, an authorization ticket is issued by Web application, in the form of a cookie.
    This authorization cookie contains the user's credentials or a key for reacquiring the user's identity
    (therefore making the user's identity persistent).
    In essence, Forms Authentication is a means for wrapping your Web application with a thin security layer,
    allowing you to have your own custom login interface and verification functionality.


    Active Directory


    Active Directory is an essential and inseparable element of the Windows 2000 network architecture
    that lets organizations efficiently share and manage information about network resources and users.
    It's essentially a single point of management for Windows-based user accounts, clients, and applications.
    It also helps organizations integrate non-Windows application with Windows-based applications and devices,
    thus consolidating directories and easing management of the entire network operating system.
    Organizations also use Active Directory to extend systems securely to the Internet by forcing their Web application users
    to authenticate them against their single-point Active Directory.


    Requirements


    Microsoft Windows® 2000


    Microsoft Visual Studio® .NET

    Knowledge of Microsoft Visual C#™


    Brief


    In this article I'll show how to implement form authentication using Active Directory warehouse credentials.
    The ASP.NET forms authentication allows users write their credentials (user name and password) in a web form to identify themselves.
    The Web application receives the credential, and it can authenticate the user verifying his user name and password in a data set available.
    This article describes how to authenticate users in Microsoft® Active Directory® directory service using the protocol LDAP
    (Light Data Access Protocol).
    It also describes how to store that information in a GenericPrincipal object and how to store it in HttpContext.Current.User property
    that follows the request throw the ASP.NET Web application.


    Creating the Login Page



    The first thing we have to do is to create a new solution in Visual Studio 2005.
    And add a new web site (if you like, you can download sample User Authentication with Active Directory Visual Studio 2005 project, used in this tutorial). The website must have a simple login page, like the one I show in the next image.
    The objective of this page is like every login page, to validate the username and password in a domain,
    the difference is that the validation process will validate against Active Directory.



    On the page load event of the login page you can add the following code to display the identity domain and username
    associated with the current Web request.


    if(!Page.IsPostback())


    {


       
    string domainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;



       
    string[] paramsLogin = domainUser.Split('\\');



        txtUser.Text =
    paramsLogin[1].ToString();



        txtDomain.Text =
    paramsLogin[0].ToString();


    }



    Configuring the application



    Now we have to configure the application in order that admits the authentication by Forms.
    You can do this trough the web.config file.
    You have to change the authentication mode in the web.config and add a secondary element to set the login page,
    the session timeout and the cookie that contains the authentication info.


    Also, you must add the <authorization> tag to allow only the authenticated users have access to the application.
    If the login process was not successful the user will be redirected to the login page.


    For that go to the application's virtual directory Properties,
    then on the security tab click on Anonymous access and authentication control group and clear the Anonymous access check box.


    After that a little modification in the web.config is needed.
    You will have to add an <identity> element beneath the <authorization> element in Web.config
    and set the impersonate attribute to true.
    This causes ASP.NET to impersonate the anonymous account specified earlier.



    So your configuration file should looks like this one:


          <authentication

    mode
    ="Forms">


            <forms

    loginUrl
    ="logon.aspx"

    name="adAuthCookie"
    timeout="60"
    path="/"
    />



          </authentication>


     


          <authorization>


            <deny

    users
    ="?"
    />



            <allow

    users
    ="*"
    />



          </authorization>


     

          <identity

    impersonate
    ="true"
    />


    As result of this configuration, every request directed to the application will be executed in the configured anonymous account
    security context.
    The user will provide credentials through the Web form to authenticate itself in Active Directory,
    but the account that will be used to have access to Active Directory will be the configured anonymous account.


    Implementing the Active directory validation


    Now it is time to implement the active directory authentication code.
    You will create a new class that will provide a method that receives a domain name,
    user name and password as parameter and returns a Boolean value indicating if there is a matching record in Active Directory.



    Yow could start creating a class library with a class that implements an authentication method against AD.
    You will have to add a new assembly reference to System.DirectoryServices.dll.
    This provides access to the namespace System.DirectoryServices which contains administered types as it helps in
    the consultation and treatment in Activate Directory.


    The connection to active directory is through LDAP.
    You have to specify the connection path,
    it is highly recommended to store this path in a configuration file so the application's administrator could change anytime he wants.
    For the searching process AD will need a filter attribute.


    Initially, the method tries to connect with Active Directory using the provided credentials.
    If it is successful, the method uses the administered class DirectorySearcher to search the specified user object.
    If exists, the path is updated so that it aims at the user object,
    and the filter attribute is updated with the user object's common name attribute.


    Your class should looks like the next one


    using
    System.Text;



    using
    System.Collections;



    using
    System.DirectoryServices;



     


    private
    string _path;



    private

    string _filterAttribute;



     


    public
    Class LdapAuthentication



    {


     


    public
    LdapAuthentication(string path)



    {


          _path = path;


    }


     


    public
    bool IsAuthenticated(string
    domain, string username,
    string pwd)



    {


         
    string domainAndUsername = domain +
    @"\" + username;



          DirectoryEntry
    entry = new DirectoryEntry( _path,



         
    domainAndUsername, pwd);



         
    try



          {


         
    // Bind to the native AdsObject to force
    authentication.



          Object obj =
    entry.NativeObject;



         
    DirectorySearcher search = new
    DirectorySearcher(entry);



          search.Filter =
    "(SAMAccountName=" + username +
    ")";



         
    search.PropertiesToLoad.Add("cn");



          SearchResult
    result = search.FindOne();



         
    if(null ==
    result)



          {


         
    return false;



          }


         

    // Update the new path to the user in the directory



          _path =
    result.Path;



          _filterAttribute
    = (String)result.Properties["cn"][0];



          }


         
    catch (Exception ex)



          {


         
    throw new
    Exception("Error authenticating user. " +
    ex.Message);



          }


         
    return true;



    }


     
    }



    Implementing the authentication process


    In this step you are going to develop the fully authentication process
    that will be launched when the user clicks on the login button using
    the class you build up before.


    For the authenticated users, a form authentication credential will be created
    and the user will be redirected to the original page that he asked for.


    You should add on the login button event handler some code to create a new active directory validation class instance
    so that it aims at Active Directory in LDAP server.
    The authentication process will do the following:


    a. Authenticate the user against Activates Directory.

    b. Create a FormsAuthenticationTicket credential that identifies the user.

    c. Encrypt the credential.

    d. Create a new cookie that contains the ticket.

    e. Add the cookie to the list of cookies that are given back to the user's explorer.


    // Path
    to you LDAP directory server.



    //
    Contact your network administrator to obtain a valid path.



    string
    adPath = "LDAP://localhost”;



    LdapAuthentication
    adAuth = new LdapAuthentication(adPath);



     


     


    try


    {


         
    if(true ==
    adAuth.IsAuthenticated(txtDomainName.Text,                       

    txtUserName.Text,txtPassword.Text))



          {


               
    // Create the authetication ticket



               
    FormsAuthenticationTicket authTicket =



               
    new FormsAuthenticationTicket(1,

    // version



               
    txtUserName.Text,



               
    DateTime.Now,



               
    DateTime.Now.AddMinutes(60), False , groups);



               
    // Now encrypt the ticket.



               
    string encryptedTicket =
    FormsAuthentication.Encrypt(authTicket);



               
    // Create a cookie and add the encrypted ticket to the



               
    // cookie as data.



                HttpCookie
    authCookie =



               
    new
    HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);



               
    // Add the cookie to the outgoing cookies collection.



               
    Response.Cookies.Add(authCookie);



               
    // Redirect the user to the originally requested page



               
    Response.Redirect(



               
    FormsAuthentication.GetRedirectUrl(txtUserName.Text,false));



          }


         
    else



          {


               
    lblError.Text = ”Authentication failed, check username and password.";



          }


    }


    catch
    (Exception ex)



    {


          lblError.Text =
    "Error authenticating. " + ex.Message;


    }


    Remember that you must change the access path so that aims at the AD Server,
    and the cookie's name must be the same name that you specified before in the web.config file.



    Implementing an authentication request controller


    Now the question is how the application to knows if the user is authenticated or not every time the application makes a request.


    You can do this procedure in the global.asax file.
    You have to implement an event handler named Application_AuthenticateRequest on it.
    Remember that in previous steps we generate a cookie whit an authentication ticket on it.
    In this event handler you must extract that cookie information and create a GenericPrincipal object identifying the authenticated user.


    Finally, the GenericPrincipal object will be associated with the current HttpContext object created for each web request.


    using
    System.Web.Security;



    using
    System.Security.Principal;



     


    //
    Extract the forms authentication cookie



    string
    cookieName = FormsAuthentication.FormsCookieName;



    HttpCookie authCookie
    = Context.Request.Cookies[cookieName];



    if(null

    == authCookie)



    {


    // There
    is no authentication cookie.



    return;


    }


     



    FormsAuthenticationTicket authTicket = null;



    Try


    {


          authTicket =
    FormsAuthentication.Decrypt(authCookie.Value);



    }


    catch
    (Exception ex)



    {


         
    // Log exception details (omitted for simplicity)



         
    return;



    }


    if
    (null == authTicket)



    {


         
    // Cookie failed to decrypt.



         
    return;



    }


     


    //
    Create an Identity object



    GenericIdentity id =
    new GenericIdentity(authTicket.Name,"LdapAuthentication");



     


    // This
    principal will flow throughout the request.



    GenericPrincipal
    principal = new GenericPrincipal(id,
    null);



     


    //
    Attach the new principal object to the current HttpContext object




    Context.User = principal;


    Testing the application


    We already finished the authentication process and it is time to test it.
    Enter a valid domain name, user name, and password and then click Log On,
    if you are successfully authenticated, you should be redirected back to the page you set as default.
    If you try to change the url manually before login,
    you will get the same result as a invalid login,
    the application will note that there is no authenticated user so it will be redirected to login page again.


    I suggest you to debug the application so you can understand how it is working.