Monday, December 19, 2011

Remove SQL Server database from single-user mode to Multi-User Mode

This query should be executed in Master Database(System Database)...
select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame
  from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid
 where d.name = 'db_Name'
GO

kill sp_id

exec sp_dboption 'db_Name', 'single user', 'FALSE'

Wednesday, November 30, 2011

Finding Duplicates data in one Table with SQLsql server

duplicates in a table. Suppose you want to find all email addresses in a table that exist more than once:

SELECT email,
 COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

You could also use this technique to find rows that occur exactly once:

SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

Tuesday, October 11, 2011

How to count number of tables,sps,function or views exist in Database.....

/* Count Number Of Tables In A Database */
SELECT COUNT(*) AS TABLE_COUNT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

/* Count Number Of Views In A Database */
SELECT COUNT(*) AS VIEW_COUNT FROM INFORMATION_SCHEMA.VIEWS

/* Count Number Of Functions In A Database */
SELECT COUNT(*) AS FUNCTION_COUNT FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'FUNCTION'

/* Count Number Of Stored Procedures In A Database */
SELECT  COUNT(*) AS PROCEDURE_COUNT FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'PROCEDURE'

Sunday, October 2, 2011

How to unlock tables which is lock in SQL SERVER or how to Kill SPID=-2

If your tables are locked in SQL SERVER using some SSIS or SSRS or some other tools.
For unlock we need to kill process id from sql server .

if your table is locked then SPID=-2 stored in syslockinfo table .

you can't delete directly this process id (SPID=-2)
use this query and kill whatever you got from this query result.

select req_transactionUOW
from master..syslockinfo
where req_spid = -2

KILL '030C2647-E265-4860-817D-5240D9A720D8'

Thanks,
Kapil.



Friday, September 30, 2011

Rollback in SSIS Package Level...

If you are using SSIS package for transaferring data from one database to other database.In case of any failure or any exception on any data flow task or component level .We have to rollback our old transactional in other tables where data  is already inserted.

You can set the transaction option to 'required' at package level...and 'supported' for the the components(Data) that you want to rollback in case of failure.
alternatively, put the required components in a (sequence) container and set the property to required at container level..and supported for the components within.

Thanks,
Kapil.

Saturday, July 16, 2011

SQL Server Performance Coding Standards (How to incerase speed of Sql server database things like SP,Function...etc)

1. Avoid using “*” in SELECT queries
Always specify the required list of columns in the select list. This will ensure that only the columns required by the query are returned to avoid unnecessary I/O and processing.

2. Always use variables of the appropriate data type and size
Use appropiate data types to avoid implicit data type conversion being perfromed by SQL Server and appropiate sizes to avoid excess usage of memory.

For example, assigning an integer type to a varchar is allowed but SQL Server will implicitly convert the integer data type to varchar which causes additional overhead.

For a column/variable like Age a data type of type integer is required. For this int, smallint or tinyint types can be used. But using int or smallint would require 4 and 2 bytes respectively of memory which is very large to accommodate the Age variable. Hence using tinyint would be a better choice, which would occupy 1 byte and provide a range between 0 and 255.

3. Keep transactions as small as possible
Try and avoid using large transactions. Using large transactions across an entire batch can cause other processes to be locked/blocked and the resources involved in the transaction cannot use them until the transaction is completed (committed or rolled back) causing performance issues in the database or even causing deadlocks.

4. Avoid excessive usage of temp tables
Excessive usage of temp tables may cause tempdb contention which can degrade the overall performance of the system. You can use table variables instead of temp tables, as this can use the memory allocated to that process and avoid usage of tempdb. It is recommended to use temp tables when dealing with considerably large amounts of intermediate data.

When using temp tables avoid using the SELECT INTO clause to create and insert data into temp tables. This will lock the entire tempdb and will cause blocking issues with other processes trying to use the tempdb resources. Always use the CREATE TABLE statement to create the temp table and then use INSERT INTO statement to insert data into the temp table. This wwill avoid tempdb contention and allow other process to use the tempdb resources.

5. Environmental settings
Always use “SET NOCOUNT ON” in stored procedures to avoid unnecessary data traffic on the network.

6. Avoid usage of cursors
Cursors are CPU intensive and make round trips to the CPU for every execution, degrading the overall performance of the batch. Instead use while loops to loop through the data rows. In SQL Server 2005, a CTE can be used to loop through data rows.

7. Never use a function towards left side in the WHERE clause
Using a function towards the left side in the WHERE clause can prevent SQL Server using an index. If needed use the function call on the right side in the WHERE clauses which allows the index to be used for the query.

8. Avoid using the DISTINCT clause
If you need to return a distinct set of rows, use a GROUP BY clause instead of DISTINCT. As the GROUP BY clause is evaluated before the DISTINCT clause.

9. Always restrict the size of SP or UDF
SQL Server maintains a data/execution plan in cache of 300 sec. If a SP/UDF is executed its execution and context plan is cached by SQL Server for 300 sec, and if a call happens to the same SP/UDF within 300 sec the cached execution plan (context plan may be same or changed depending on the parameters) is used by SQL Server for execution else it will reload the entire SP/UDF and then execute it. If the size of the SP/UDF is large then the time take for loading it into memory is more and hence there is a performance hit. If the SP/UDF is smaller enough to load faster, it adds up to the performance gain. Generally restrict the size of the SP/UDF to be around 4-5KB.

10. High Read intensive queries
High read intensive queries i.e. queries which retrun large amount of data (rows) from a database will require more I/O then CPU. Such queries should be run on a single processor rather than spanning it across multiple processors. Either set the “Max Degree of Parallelism” to 1 using sp_configure (this affects entire database) or use the MAXDOP option to restrict the particular query to use only one processor.

11. Always use UDF instead of SP when it is supposed to return a scalar value
When deciding between an SP and a UDF to return a scalar value, it is recommended to use a UDF. Performance wise both an SP and UDF are equal. A UDF provides the facility to be used within a SELECT query and in a WHERE clause.

12. Use Locking hints / Isolation Levels as required
Use the locking hints especially NOLOCK with read only queries to avoid locking/blocking other processes using the same object(s). When a batch/SP needs to be run under non-blocking condition use the transaction isolation (read uncommitted) level. This also improves the performance of the queries as SQL Server does not have to cater the lock resources.

13. Avoid using OR in WHERE/JOIN clauses in a Query
Using the OR clause in a WHERE or JOIN would make SQL Server not use correct indexes. It is sometimes ok to use the OR in WHERE but it’s dangerous to use OR in a JOIN. If it’s a mandate (depends on the requirement) to use OR in the JOIN then divide the query in two parts and combine the data using UNION or UNION ALL. This will provide a drastic improvement in the performance.

14. Avoid using IN and NOT IN clauses
The usage of IN and NOT IN clauses in WHERE conditions will make SQL Server check for all the values within the IN clause, and this will degrade the performance if the number of values within the IN are too many. (IN clause query can be replaced using JOINs.) Instead of IN/NOT IN use EXITS/NOT EXITS which will check for the very first existence and continue with the query, improving the performance.

15. Always have a CLUSTERED INDEX defined on a table
When designing (Normalization) a table it is recommended to have CLUSTRED INDEX created on the table. Having a clustered index sorts the data w.r.t. the column data and any subsequent non-clustered index on that table will use this clustered index (sorted) to seek the data. Also it will help reduce fragmentation within the data/index pages. Consider having a clustered index on a primary key column(s) or define an identity column for the table and qualify that for the PK and clustered index.

When planning for a Index (clustered or non-clustered), and depending on the table functionality (high read or write intensive) specify a FILLFACTOR. If the table is more write intensive specify a fillfactor between 85-90% depending on the size of the row that would be inserted. For read only tables (OLAP) its not required to have a fill factor. Having a proper fill factor would minimize the page splits avoiding SQL Server time to service the page splits.

16. Turn off the AUTO SHRINK
For databases with more write operations, always ensure that the AUTO SHRINK property is turned OFF. Database shrink operation shrinks the database files and also causes fragmentation of indexes which will hinder the over all performance.  Always run the database shrink operation during off peak hours immediately followed by a defragmentation of indexes.

17. Run UPDATE STATISTICS regularly
For databases with more write operations, the statistics will go out of date causing SQL Server to use old statistics causing performance problems. Hence always have a scheduled job (off peak hours) to update the statistics of all the tables (or transactional tables) regularly. 

Friday, July 1, 2011

Comma seperated values using SQL Server using Query...

How to get comma seperated string from table.
I have table called TableName and I have colum name "Age"
Using simple query I get 
Age 
===
12
23
45
56
67
78
78
but I want the output like this
12,23,45,56,67,78,78
Then use this query to get output in this format...


You can use this query but first comma will be display...
========================================
 select ', ' + columname from -- create comma separated values
(
 select  ColumName from TableName--Your query here
 ) AS T FOR XML PATH('')

OR

If you want to remove first comma also then use this query
========================================
select  STUFF(
(
 select ', ' + ColumName from -- create comma separated values
(
 select  ColumName from TableName--Your query here
 ) AS T FOR XML PATH('')
)
,1,1,'') AS [Name]

SQL Server Connection Pooling (ADO.NET)

Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

Only connections with the same configuration can be pooled. ADO.NET keeps several pools at the same time, one for each configuration. Connections are separated into pools by connection string, and by Windows identity when integrated security is used. Connections are also pooled based on whether they are enlisted in a transaction.

Pooling connections can significantly enhance the performance and scalability of your application. By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application. You can also supply several connection string modifiers to control connection pooling behavior. For more information, see "Controlling Connection Pooling with Connection String Keywords" later in this topic.

Note

When connection pooling is enabled, and if a timeout error or other login error occurs, an exception will be thrown and subsequent connection attempts will fail for the next five seconds, the "blocking period". If the application attempts to connect within the blocking period, the first exception will be thrown again. After the blocking period ends, another connection failure by the application will result in a blocking period that is twice as long as the previous blocking period.  Subsequent failures after a blocking period ends will result in a new blocking periods that is twice as long as the previous blocking period, up to a maximum of five minutes.

Pool Creation and Assignment

When a connection is first opened, a connection pool is created based on an exact matching algorithm that associates the pool with the connection string in the connection. Each connection pool is associated with a distinct connection string. When a new connection is opened, if the connection string is not an exact match to an existing pool, a new pool is created. Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity. Connection strings must also be an exact match; keywords supplied in a different order for the same connection will be pooled separately.

In the following C# example, three new SqlConnection objects are created, but only two connection pools are required to manage them. Note that the first and second connection strings differ by the value assigned for Initial Catalog.

using (SqlConnection connection = new SqlConnection(
  "Integrated Security=SSPI;Initial Catalog=Northwind"))
    {
        connection.Open();     
        // Pool A is created.
    }

using (SqlConnection connection = new SqlConnection(
  "Integrated Security=SSPI;Initial Catalog=pubs"))
    {
        connection.Open();     
        // Pool B is created because the connection strings differ.
    }

using (SqlConnection connection = new SqlConnection(
  "Integrated Security=SSPI;Initial Catalog=Northwind"))
    {
        connection.Open();     
        // The connection string matches pool A.
    }

If MinPoolSize is either not specified in the connection string or is specified as zero, the connections in the pool will be closed after a period of inactivity. However, if the specified MinPoolSize is greater than zero, the connection pool is not destroyed until the AppDomain is unloaded and the process ends. Maintenance of inactive or empty pools involves minimal system overhead.

Removing Connections

The connection pooler removes a connection from the pool after it has been idle for a long time, or if the pooler detects that the connection with the server has been severed. Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid. Invalid connections are removed from the connection pool only when they are closed or reclaimed.

If a connection exists to a server that has disappeared, this connection can be drawn from the pool even if the connection pooler has not detected the severed connection and marked it as invalid. This is the case because the overhead of checking that the connection is still valid would eliminate the benefits of having a pooler by causing another round trip to the server to occur. When this occurs, the first attempt to use the connection will detect that the connection has been severed, and an exception is thrown.

Clearing the Pool

ADO.NET 2.0 introduced two new methods to clear the pool: ClearAllPools and ClearPool. ClearAllPools clears the connection pools for a given provider, and ClearPool clears the connection pool that is associated with a specific connection. If there are connections being used at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool.

Transaction Support

Connections are drawn from the pool and assigned based on transaction context. Unless Enlist=false is specified in the connection string, the connection pool makes sure that the connection is enlisted in the Current context. When a connection is closed and returned to the pool with an enlisted System.Transactions transaction, it is set aside in such a way that the next request for that connection pool with the same System.Transactions transaction will return the same connection if it is available. If such a request is issued, and there are no pooled connections available, a connection is drawn from the non-transacted part of the pool and enlisted. If no connections are available in either area of the pool, a new connection is created and enlisted.

When a connection is closed, it is released back into the pool and into the appropriate subdivision based on its transaction context. Therefore, you can close the connection without generating an error, even though a distributed transaction is still pending. This allows you to commit or abort the distributed transaction later.

Controlling Connection Pooling with Connection String Keywords

The ConnectionString property of the SqlConnection object supports connection string key/value pairs that can be used to adjust the behavior of the connection pooling logic. For more information, see ConnectionString.

Pool Fragmentation

Pool fragmentation is a common problem in many Web applications where the application can create a large number of pools that are not freed until the process exits. This leaves a large number of connections open and consuming memory, which results in poor performance.

Pool Fragmentation Due to Integrated Security

Connections are pooled according to the connection string plus the user identity. Therefore, if you use Basic authentication or Windows Authentication on the Web site and an integrated security login, you get one pool per user. Although this improves the performance of subsequent database requests for a single user, that user cannot take advantage of connections made by other users. It also results in at least one connection per user to the database server. This is a side effect of a particular Web application architecture that developers must weigh against security and auditing requirements.

Pool Fragmentation Due to Many Databases

Many Internet service providers host several Web sites on a single server. They may use a single database to confirm a Forms authentication login and then open a connection to a specific database for that user or group of users. The connection to the authentication database is pooled and used by everyone. However, there is a separate pool of connections to each database, which increase the number of connections to the server.

This is also a side-effect of the application design. There is a relatively simple way to avoid this side effect without compromising security when you connect to SQL Server. Instead of connecting to a separate database for each user or group, connect to the same database on the server and then execute the Transact-SQL USE statement to change to the desired database. The following code fragment demonstrates creating an initial connection to the master database and then switching to the desired database specified in the databaseName string variable.

// Assumes that command is a SqlCommand object and that
// connectionString connects to master.
command.Text = "USE DatabaseName";
using (SqlConnection connection = new SqlConnection(
  connectionString))
  {
    connection.Open();
    command.ExecuteNonQuery();
  }

Application Roles and Connection Pooling

After a SQL Server application role has been activated by calling the sp_setapprole system stored procedure, the security context of that connection cannot be reset. However, if pooling is enabled, the connection is returned to the pool, and an error occurs when the pooled connection is reused. For more information, see the Knowledge Base article, "SQL application role errors with OLE DB resource pooling."

Monday, June 27, 2011

ASP.NET MVC(Model-VIew-Controller) Overview architecture

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
MVC design pattern

mvc_DesignPatternMVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.
The MVC framework includes the following components:
  • Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.
    In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
  • Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.
  • Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.
The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.
The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework.
You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)
Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.

Advantages of an MVC-Based Web Application

The ASP.NET MVC framework offers the following advantages:
  • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
  • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
  • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller.
  • It provides better support for test-driven development (TDD).
  • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application

The Web Forms-based framework offers the following advantages:
  • It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
  • It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller.
  • It uses view state on server-based forms, which can make managing state information easier.
  • It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
  • In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.
The ASP.NET MVC framework provides the following features:
  • Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
  • An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI enables you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.
  • Extensive support for ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
  • Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
  • Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Wednesday, June 15, 2011

Detecting changes in web form or web pages (Dirty Form) using JQuery Plugins

Hi ,

If you want to give a alert mesage to user's while you naivagate away from one page to other page or any where. Then you need to use Dirty Form using Jquery.
If we use this plugin then we can prevent loss of any unsaved data from your web form.

This functinality invoke while 
1. Click on menu items
2. Back button,forward button
3. And any other action which will navigate away from your current page.

It will detect the changes happend in your web form and give an prompt message for user like you have some unsaved data .you want to navigate from here or not ?

Using this  task user may not loss any kind of data.


JQuery has a set of plug-ins which helps in watching the form for modifications and notifying the user when he navigates away from a webpage so that user will not lose unsaved information.

a)      LiveQuery: This plug-in helps in handling the dynamic updates scenario on the webpage. So even if DOM is manipulated using DHTML techniques, the     changes in the form values will be properly tracked.Live Query (formerly Behavior) utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

Example :    $('a')
    .livequery('click', function(event) {
        alert('clicked');
        return false;
    });

b)      DirtyForm:
This is a project for watching containers of inputs and notifying the user of unsaved changes.This plug-in actually does the task of     tracking changes to form values.Dirty Forms is a flexible jQuery plugin to help prevent users from losing data when editing forms.

Dirty Forms will alert a user when they attempt to leave a page without submitting a form they have entered data into. It alerts them in a modal popup box, and also falls back to the browser’s default onBeforeUnload handler for events outside the scope of the document such as, but not limited to, page refreshes and browser navigation buttons.

Oh, and it’s pretty easy to use.
$('form').dirtyForms();


Sample webpage (How to use Dirty Flag)

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Index</title>

    <!-- Step1 -->

    <!-- Reference to core JQuery library -->

    <script src="../../Scripts/jquery-1.4.2.js" type="text/javascript"></script>

    <!-- Reference to dirty form JQuery plug-in -->
    <script src="../../Scripts/jquery.dirtyform.js" type="text/javascript"></script>

    <!-- Reference to live query JQuery plug-in -->
    <script src="../../Scripts/jquery.livequery.js" type="text/javascript"></script>



    <script type="text/javascript">

       

        //Step2

        //Flag variable which helps in identifying whether any modifications have been done

        on the form

        var isDirty = false;
       

        //Step3

        //Intercepts any navigation away from webpage. This event handler will display alert

        message if there are unsaved changes on form

        window.onbeforeunload = function() {

            if (isDirty) {

                return 'You have unsaved changes on this page.';

            }

        }

        //JQuery ready function executes after the complete html DOM has been loaded in the

        web-browser

        $(document).ready(function() {

       

            //Step4

            //Configures Dirty form plugin to observe for changes on the form

            $("#myForm").dirty_form().dirty(function(event, data) {

                isDirty = true;

            });

             //Step5

            //Cancel button action navigates to a different webpage

            $("#btnCancel").click(function() {

                window.location.href = "http://www.google.com"

            });



            //Step6

            //Form submit handler. In this case we want to suppress the alert message.

            //The trick is to turn off the isDirty flag and then continue with post operation.

            $("#btnSubmit").click(function() {

                isDirty = false;

                return true;

            });

        });
      

    </script>

</head>

<body>

    <form id="myForm" action="" method="post">

        Message:

        <input type="text"/>

        <input type="submit" value="Submit" id="btnSubmit" />

        <input type="button" value="Cancel" id="btnCancel" />

        <!-- Clicking this hyperlink will alert user of any unsaved data on the form -->

        <a href="http://www.google.com">Goto Google</a>

    </form>

</body>

</html>


Steps followed in above sample are:

 Step1: Add references to core jquery library, livequery and dirty form jquery plug-ins

Step2: Use a global variable isDirty to track form changes

Step3: Use onbeforeunload event to trap navigations away from current webpage and notify user of unsaved changes.

Step4: Configure Dirty form plug-in to observe for changes on the form

Step5: Configure event handler for Cancel button

Step6: Configure event handler for Submit button to suppress alert message during submit operation

Sunday, June 12, 2011

A potentially dangerous Request.Form value was detected from the client

Everytime a user posts something containing < or > in a page in webapp, you will get this exception thrown.
so for this issue you need to  Put

1. validateRequest="false" in your page directive or web.config file.

The .NET framework is throwing up an error because it detected something in the entered text which looks like an HTML statement. The text doesn't need to contain valid HTML, just anything with opening and closing angled brackets ("<...>").
The reason behind the error is as a security precaution. Developers need to be aware that users might try to inject HTML (or even a script) into a text box which may affect how the form is rendered. For further details see www.asp.net/learn/whitepapers/request-validation/.


In your web.config file

2. <httpRuntime requestValidationMode="2.0"/>
<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>
 
3.  
[Post, ValidateInput(false)]
public ActionResult Edit(string message) {
    ...
} 
4.
[AcceptVerbs(HttpVerbs.Get)]
[ValidateInput(false)]
public ActionResult List(string message)
{
}
If you are using MVC3.0 you can use [AllowHtml]
public class XMLModel
    {
        [AllowHtml]
        public string msg { get; set; }
    }
 
Thanks

Saturday, June 11, 2011

Speeding Up jQuery Javascript & CSS Download Times

Now-days, jQuery are becoming so popular in client-side of web development. jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. jQuery itself is composed by "one" file called jquery-x.x.x.min.js. With only one Javascript there is no performance problem. But with jQuery has been appeared some "addons/plugins" that uses this library. An example could be jQueryUI http://jqueryui.com/ but more can be found at http://plugins.jquery.com/. Each of these addons contain their own Javascript file. For example jQueryUI contains apart from jQuery file, jquery-ui-x.x.x.custom.min.js and one CSS file, so in this case in a web page two Javascript and a CSS elements are defined. As more and more extensions are used, more Javascript files are required. And more scripts imply more connections to server, so for example if three Scripts and one CSS are defined, four connections from browser to server are required.

Because of these amounts of connections, downloading time is increased; content negotiation and the fact that normally there will be only two concurrent connections to the same host, produces an overhead that results in a long page loading time. For example, it is faster to serve a 8KB script file than  eight of 1KB.

Jquery Dialog events and methods - how to use those methods.

Hi All,

The jQuery UI framework offers up a functional Dialog widget that allows resizing and also the ability to display forms. The basic dialog window is an overlay positioned within the viewport and is protected from page content (like select elements) shining through with an iframe. It has a title bar and a content area, and can be moved, resized and closed with the ‘x’ icon by default.
for creating a dialog :

$("#DivID").dialog({
autoOpen: false,
height: 270,
width: 550,
modal: true,
title: 'Name of the title',
draggable: true,//You can drag any where on a page
resizable: false,//Size can be increase or decrease.
closeOnEscape: false//while press Escape button
});

This is simple dialog properties.

1. pass it as parameter in dialog is used for hiding close (x) in dialog:
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
Another method for hidinh close(x)button in right corner is

$("#DivID").dialog().parent('.ui-dialog').find('.ui-dialog-titlebar-close').hide();

2.We have event Close event , while colse the dialog is there any functnality you want then you need to pass like

$('#DivID').dialog({
close: function(event, ui) {
var urlString1 = '<%=Url.Action("Action", "Controller") %>';
var urlString = urlString1;
urlString = Url.decode(urlString);
urlString = String.format(urlString);
try { location.href = urlString; } catch (e) { }
}});

3. We have event beforeclose

$("#DivID").dialog({
beforeclose: function(event, ui) {
if (cancel == false) {
if (dirtyFlag == true) {
return any URL or some thing.
}
}
}
});

If you want to some more information please refer :
jQuery UI Dialog

Thanks.

Jquery dynamic validation for Phone,ZipCode,Pager and Fax. 9/5 digit validate for Zipcode US .

Hi All,
If you want validate your Zipcode,phone or fax number as per US rule.
Because phone number has 10 digit and zipcode has total 9 digit.but 5 digit also valid zip number in US.
So we need to validate both(All)the scenario.
If you will used masked(Masking) input for this type of input that's very good for you.

================================================

jQuery.validator.addMethod("ZipCodeRule", function(zip) {
var i;
for (i = 1; i <= 9; i++) { zip = zip.replace(/([_])/, ""); } if (zip.length == 0 || (zip.length == 1 && zip.charAt(0) == "-") || zip.match(/^\d{5}([- ]?\d{4})?$/) || zip.match(/^\\d{5}$/) || zip.length == 6) { return true; } return false; }, "Enter valid Zip Code");

================================================

/*If Phone is not mandatory*/ jQuery.validator.addMethod("PhoneNumberRule", function(Phone, element) { Phone = Phone.replace(/\s+/g, ""); for (i = 1; i <= 10; i++) { Phone = Phone.replace(/([_])/, ""); } if (Phone.length == 0 || (Phone.length == 3 && Phone.charAt(1) == ")")) return true; else return this.optional(element) || Phone.length > 9 &&
Phone.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Phone Number");

================================================

/*If FaxNumber is not mandatory*/
jQuery.validator.addMethod("FaxNumberRule", function(Fax, element) {
Fax = Fax.replace(/\s+/g, "");
for (i = 1; i <= 10; i++) { Fax = Fax.replace(/([_])/, ""); } if (Fax.length == 0 || (Fax.length == 3 && Fax.charAt(1) == ")")) return true; else return this.optional(element) || Fax.length > 9 &&

Fax.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Fax Number");

================================================

/*If Pager is not mandatory*/
jQuery.validator.addMethod("PagerNumberRule", function(Pager, element) {
Pager = Pager.replace(/\s+/g, "");
for (i = 1; i <= 10; i++) { Pager = Pager.replace(/([_])/, ""); } if (Pager.length == 0 || (Pager.length == 3 && Pager.charAt(1) == ")")) return true; else return this.optional(element) || Pager.length > 9 &&
Pager.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Pager Number");

================================================


Thanks

split function for more than one parameter...

Hi All,

As you know that we have split function for split based on a particular character
Like
string str="This is very good string and every | bode can use it"

//string strPhrase = child.Phrase.Split('|');
Then it will give two values.
But suppose I have string like this
string str="This is very good string and every || bode can use it"
Now in this happened we will get three string's because we can not split this string based on || this .
for multiple charcter split you need to use this type of method
string str="This is very good string and every bode can use it"

string[] strPhrase = str.Split(new string[1] { "{every}" },StringSplitOptions.None);
string str1= strPhrase[0];

if this is not working then use this one

string[] res = str.Split(new string[] { "every" }, StringSplitOptions.None);
string str1 = res[1];

Now in this time we will retrieve two string after split based on "every".

Thanks

XMl Parsing Error Resolved special character & , ', %,$ #,<>

Hi All,
this is very good idea to resolving to this type of error. you do not need to convert to all the characters into some other to HTML user friendly character.
Some time what happend if you are using <,>,%,& ' this character this given a lot of problem while parsing XML.
This is a very simple method (trick)to resolved this issue.

You need to pass your values inside ![CDATA[{ANY CHARACTER YOU WANT}]]
this should be passed between angular brackets < and >.

Thanks

Wednesday, May 25, 2011

jQuery UI Widget : Progressbar

This widget is used to display the progress of a process. The bar is coded to be flexibly sized through CSS and will scale to fit inside it's parent container by default.
This is a determinate progress bar, meaning that it should only be used in situations where the system can accurately update the current status complete.
The following code line is used to place a progress bar inside a element like div :
$("#progressbar").progressbar({ value: 37 }); For options, events ,method and theming click here For options, events ,method and theming click here
EXAMPLE :
progressbar.html
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8
/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4
/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8
/jquery-ui.min.js"></script>

<script>
$(document).ready(function() {
$("#progressbar").progressbar({ value: 37 });
});
</script>
</head>
<body style="font-size:62.5%;">

<div id="progressbar"></div>

</body>
</html>
Output :

Download Source Code

jQuery UI Widget : Slider

The jQuery UI Slider plugin makes selected elements into sliders. There are various options such as multiple handles, and ranges. The handle can be moved with the mouse or the arrow keys.
You can implement slider as :
$("#slider").slider(); here 'slider' is the div element name.
For options, events ,method and theming click here
EXAMPLE :
slider.html
<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/
1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        
<script src="http://ajax.googleapis.com/ajax/
libs/jquery/1.4/jquery.min.js"></script>
        
<script src="http://ajax.googleapis.com/ajax/
libs/jqueryui/1.8/jquery-ui.min.js"></script>
        
<style type="text/css">
 #slider { margin: 10px; }
</style>
<script>
  $(document).ready(function() {
    $("#slider").slider();
  });
</script>
</head>
<body style="font-size:62.5%;">
  
<div id="slider"></div>

</body>
</html>
Output :

Download Source Code

jQuery UI Widget : Tabs

Tabs are generally used to break content into multiple sections that can be swapped to save space, much like an accordion.
By default a tab widget will swap between tabbed sections onClick, but the events can be changed to onHover through an option. Tab content can be loaded via Ajax by setting an href on a tab.
You can implement tab as :
$("#tabs").tabs(); EXAMPLE :
tabs.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>jQuery UI Tabs</title>
<link type="text/css" href="tab/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="tab/jquery-ui-1.8.4.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#tabs").tabs();
});
</script>
</head>
<body>

<div class="demo">

<div id="tabs">
<ul>
<li><a href="#tabs-1">jQuery</a></li>
<li><a href="#tabs-2">Ajax</a></li>
<li><a href="#tabs-3">Java Script</a></li>
</ul>
<div id="tabs-1">
<p>jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML.It was released in January 2006 at BarCamp NYC by John Resig. Used by over 31% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.
jQuery is free, open source software, dual-licensed under the MIT License and the GNU General Public License, Version jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plugins on top of the JavaScript library. Using these facilities, developers are able to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. This contributes to the creation of powerful and dynamic web pages.</p>
</div>
<div id="tabs-2">
<p>Ajax is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.</p>
</div>
<div id="tabs-3">
<p>JavaScript is an implementation of the ECMAScript language standard and is typically used to enable programmatic access to computational objects within a host environment. It can be characterized as a prototype-based object-oriented[5] scripting language that is dynamic, weakly typed and has first-class functions. It is also considered a functional programming language like Scheme and OCaml because it has closures and supports higher-order functions.</p>
</div>
</div>

</div>
<font color="#FF4500">
<p>Click tabs to See Content of Title</p>
</font>

</body>
</html>
Output :

Download Source Code

jQuery UI Widget : Dialog

This widget is used to create a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the '+' icon by default.
f the content length exceeds the maximum height, a scrollbar will automatically appear.
A bottom button bar and semi-transparent modal overlay layer are common options that can be added.
A call to $(foo).dialog() will initialize a dialog instance and will auto-open the dialog by default. If you want to reuse a dialog, the easiest way is to disable the "auto-open" option with: $(foo).dialog({ autoOpen: false }) and open it with $(foo).dialog('open'). To close it, use $(foo).dialog('close').
To create a dialog box containing text of a element like div, we use :
 $("#dialog").dialog();

For options, events ,method and theming click here
EXAMPLE :
dialog.html
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs
/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">
</script>
<script>
$(document).ready(function() {
$("#dialog").dialog();
});
</script>
</head>
<body style="font-size:62.5%;">

<div id="dialog" title="Dialog Title">This is a dialog box</div>

</body>
</html>
Output :

Download Source Code

jQuery UI Widget : Datepicker

You can datepicker to your web page for inputting date. The language and date format can be customize. By default, the datepicker calendar opens in a small overlay on Focus and closes automatically on Blur or when a date is selected.
The datepicker is very useful on the website. In this example you will learn how to use jQuery datepicker component.
You can use keyboard shortcuts to drive the datepicker:
  • page up/down - previous/next month
  • ctrl+page up/down - previous/next year
  • ctrl+home - current month or open when closed
  • ctrl+left/right - previous/next day
  • ctrl+up/down - previous/next week
  • enter - accept the selected date
  • ctrl+end - close and erase the date
  • escape - close the datepicker without selection
For options, events ,method and theming click here
EXAMPLE :
datepicker.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Datepicker</title>
<style type="text/css">
@import "DatePicker/flora.datepick.css";
</style>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="DatePicker/jquery.datepick.js"></script>
<script type="text/javascript">
$(function() {
$('#popupDatepicker').datepick();

});
</script>
</head>
<body bgcolor="#ADFF2F">
<h1><font color="green">jQuery popup Date picker</font></h1>
<font color="green">
<p>Enter Date &nbsp;<input type="text" id="popupDatepicker"></p>
</font>
</body>
</html>
Output :
When you click inside input box :

Download Source Code

Query UI Widget : Autocomplete

Using autocomplete widget , you can add autocomplete feature to your input  field. In this field when you will start type something , it will provide a list of related possible values (starting from that letter which you already typed). When you click on any of these , it will auto complete the remaining text.
For options, events ,method and theming click here
EXAMPLE :
autocompleteUI.html
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui
/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4
/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8
/jquery-ui.min.js"></script>

<script>
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
});
});
</script>
</head>
<body style="font-size:62.5%;">
<h3><font color="red">Fill the below Field</font></h3>
Type your language proficiency :
<input id="autocomplete" />
</body>
</html>
Output :
When you type something , for ex. java , it will show :

Download Source Code