Tuesday, June 23, 2009

Asp.Net questions&Ans

What are the parts of the .NET Framework?
.NET Framework has two main parts:
The common language runtime (CLR)
The .NET Framework class library
What are the ways to persistent data in a web application?
Data can be persisted in the web application using any of the following mechanism.
ApplicationState
SessionState
ViewState.
How does classes are organized in the .NET Framework?
The .NET Framework has organized its classes using namespaces.
What is the point to remember about Transfer method in ASP.NET?
Transfer method can't be used with HTML pages. It works only with .aspx pages.
What are the different exception-handling approaches in ASP.NET Web applications?
Exceptions can be handled using any of the following approaches:
Try, Catch, and Finally keywords in VB.NET or the try, catch, and finally keywords in C#.
Error event procedures at the Global, Application, or Page levels.
Describe the purpose of error pages and why they are needed.
Error page is used to trap exceptions occur outside the scope of the application.
The exceptions of these types are identified by HTTP response codes.
These exceptions are handled by IIS by displaying custom error pages listed in your application’s Web.config file.
Explain how tracing helps in handling exceptions.
Tracing helps developer by recording an unusual event while application is running. The developer can trace the unexpected events in the trace log, thus can fix the problem.
Difference between Windows and Forms authentication user lists in Web.config
User lists for Windows authentication are included in the element of Web.config.
User lists for Forms authentications are included in the element of Web.config.
Explain how to require authentication using the Web.config file in ASP.NET.
We can include element to require authentication as shown below:



What is the difference between the Debug and Trace classes?
Code using the Debug class is stripped out of release builds.
Code using the Trace class is left in.
Write a directive to cache responses for a Web form for 30 seconds.
<%@ OutputCache Duration=”30” VaryByParam=”me” %>
Explain how to detect when application data is about to be removed from the cache.
We can detect using onRemoveCallback delegate.
CurrentCulture property vs. Current¬UICulture property.
The CurrentCulture property states how the .NET Framework handles dates, currencies, sorting, and formatting issues.
The CurrentUICulture property determines which satellite assembly is used when loading resources.
What is the purpose of MVC patter?
MVC pattern separates the GUI from the data. It helps in providing multiple views for the same data.
Explain how to enable and disable connnection pooling.
Set pooling = true in the connectionstring. By default, it is true.
Set pooling = false to disable connection pooling.
Dataset.clone vs. Dataset.copy
Dataset.clone copies the structure only whereas dataset copy copies both structure and data.
Explain how to configure WebGarden in ASP.NET.
WebGarden can be configured using process model setting in "machine.config" or "web.config".
What is Webfarm?
Webform consist of two or more web server of same configuration. When any request is made, the router logic of webform decides which web server from the farm handles the request.
Explain the advantages of having webfarm.
Webfarm allows the application to run even if a server is down, since request can be served by other web server of the farm.
What is windows service?
Windows service has the capability to start automatically when the computer boots. It can be manually paused, stopped or even restarted.
Explain how to remove anonymous access to the IIS web application.







How to enable tracing in ASP.NET
Tracing can be enabaled as shown below:
<%@Page Trace = "True"%>
Name the major events in Global.aspx file.
-Application_Init
-Application_Disposed
-Application_Error
-Application_Start
-Application_End
-Application_BeginRequest
-Application_EndRequest
-Application_PreRequestHandlerExecute
-Application_PostRequestHandlerExecute
-Application_PreSendRequestHeaders
-Application_PreSendContent
-Application_AcquireRequestState
-Application_ReleaseRequestState
-Application_ResolveRequestCache
-Application_UpdateRequestCache
-Application_AuthenticateRequest
-Application_AuthorizeRequest
-Session_Start
-Session_End
What are authentication techniques in ASP.NET?
-Windows authentication
-Passport authentication
-Forms authentication
Authentication vs. authorization
-Authentication is varying the identity of the user.
-Authorization is the process of allowing an authenticated user access to resources.
Explain the uses of Global.asax file.
-using this we can set application-level variables
-we can use application-level events.
How many types of validation controls are provided by ASP.NET? Explain them.
There are 6 validation controls in ASP.NET:
1. RequiredFieldValidator: It is for mandatory field.
2. RegularExpressionValidator: It checks the match with a given regularexpression.
3. CompareValidator: It checks that the value in the validated control matches with the value of another control or with a specific value.
4. RangeValidator: It checks the validated control value with a specified range.
5.. CustomValidator: Require to do custom validation on any control after writing required code.
6. ValidationSummary:This control is used to display a summary of all validation errors raised in a particular Web page.
What is impersonation in ASP.NET?
Impersonation is used to decide whether a user request in an ASp.NET application can run under the authenticated identity received from IIS or under a specific identity specified in web.config file when impersonation is enabled.When it is disabled the user request will run under the ASPNET account( the process identity of the application worker process) .By default it is disabled.

or

or

Explain how a web application works.
Answer - A web application resides in the server and serves the client™s requests over internet. The client access the web page using browser from his machine. When a client makes a request, it receives the result in the form of HTML which are interpreted and displayed by the browser.

A web application on the server side runs under the management of Microsoft Internet Information Services (IIS). IIS passes the request received from client to the application. The application returns the requested result in the form of HTML to IIS, which in turn, sends the result to the client.
Application State
Data stored in the application object can be shared by all the sessions of the application. Application object stores data in the key value pair.
Session State
Session State stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application's configuration settings. By default, SessionID values are stored in a cookie.
ASP.NET session vs Classic ASP
ASP session variables are recycled when IIS restarts. ASP.NET session is maintained even if IIS reboots.
With ASP session, we can’t have web farms. ASP.NET session supports multiple servers since it can be stored in state server and SQL server.
ASP session is compatible to only those browsers that support cookies.
What is event bubbling?
In ASP.NET, we can have child controls inside server control like Datagrid, Datalist, Repeater. Example, combo box can be placed inside Datagrid. The child can’t raise their events by himself; they send events to their parent which pass to the page as “Itemcommand” event. This processing is called event bubbling.

Monday, June 22, 2009

SQL Qustion and Answers

What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

What is normalization?
Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What are different normalization forms?

1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form
A model free from all modification anomalies.

Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database.

What is Stored Procedure?
A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.

Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index.
Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself.

What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.

A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

What are the different index configurations a table can have?
A table can have one of the following index configurations:

No indexes
A clustered index
A clustered index and many nonclustered indexes
A nonclustered index
Many nonclustered indexes

What is cursors?
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.

In order to work with a cursor we need to perform some steps in the following order:

Declare cursor
Open cursor
Fetch row from the cursor
Process fetched row
Close cursor
Deallocate cursor

What is the use of DBCC commands?
DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC – To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP – Checks all tables file group for any damage.

What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.
Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width.

What are different type of Collation Sensitivity?
Case sensitivity
A and a, B and b, etc.

Accent sensitivity
a and á, o and ó, etc.

Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.

Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.

What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

What is a NOLOCK?
Using the NOLOCK query optimiser hint is generally considered good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay(blocking).

What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE can not be Rolled back using logs.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.

DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back using logs.
DELETE is DML Command.
DELETE does not reset identity of the table.

Difference between Function and Stored Procedure?
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset operations.

When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

What types of Joins are possible with Sql Server?
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. HAVING criteria is applied after the the grouping of rows has occurred.

What is sub-query? Explain properties of sub-query.
Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword.

A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used.

Properties of Sub-Query
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator, and
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.

What are types of sub-queries?
Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.

What is SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process takes place over a long period of time.

What is User Defined Functions?
User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type.

What kind of User-Defined Functions can be created?
There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.

Scalar User-Defined Function
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.

Inline Table-Value User-Defined Function
An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port number.both on client and the server.

What are the authentication modes in SQL Server? How can it be changed?
Windows mode and mixed mode (SQL & Windows).

To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.

Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.

Which command using Query Analyzer will give you the version of SQL server and operating system?
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'),
What is SQL server agent?
SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.

Can a stored procedure call itself or recursive stored procedure? How many level SP nesting possible?
Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels.

What is @@ERROR?
The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there was no error, @@ERROR returns zero. Because @@ERROR is reset after each Transact-SQL statement, it must be saved to a variable if it is needed to process it further after checking it.

What is Raiseerror?
Stored procedures report errors to client applications via the RAISERROR command. RAISERROR doesn’t change the flow of a procedure; it merely displays an error message, sets the @@ERROR automatic variable, and optionally writes the message to the SQL Server error log and the NT application event log.

What is log shipping?
Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval.

What is the difference between a local and a global variable?
A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.

A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
What command do we use to rename a db?
sp_renamedb ‘oldname’ , ‘newname’
If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode.

What is sp_configure commands and set commands?
Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.

What are the different types of replication? Explain.
The SQL Server 2000-supported replication types are as follows:

Transactional
Snapshot
Merge
Snapshot replication distributes data exactly as it appears at a specific moment in time and does not monitor for updates to the data. Snapshot replication is best used as a method for replicating data that changes infrequently or where the most up-to-date values (low latency) are not a requirement. When synchronization occurs, the entire snapshot is generated and sent to Subscribers.

Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data modifications are made at the Publisher, the individual transactions are captured and propagated to Subscribers.

Merge replication is the process of distributing data from Publisher to Subscribers, allowing the Publisher and Subscribers to make updates while connected or disconnected, and then merging the updates between sites when they are connected.

What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)

What are three SQL keywords used to change or set someone’s permissions?
GRANT, DENY, and REVOKE.

What does it mean to have quoted_identifier on? What are the implications of having it off?
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers.

What is the STUFF function and how does it differ from the REPLACE function?
STUFF function to overwrite existing characters. Using this syntax, STUFF(string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string.
REPLACE function to replace existing characters of all occurance. Using this syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string.

Using query analyzer, name 3 ways to get an accurate count of the number of records in a table?
SELECT *
FROM table1
SELECT COUNT(*)
FROM table1
SELECT rows
FROM sysindexes
WHERE id = OBJECT_ID(table1)
AND indid < 2
How to rebuild Master Database?
Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This is located in the Program Files\Microsoft SQL Server\80\Tools\Binn directory.
In the Rebuild Master dialog box, click Browse.
In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in the shared network directory from which SQL Server 2000 was installed, and then click OK.
Click Settings. In the Collation Settings dialog box, verify or change settings used for the master database and all other databases.
Initially, the default collation settings are shown, but these may not match the collation selected during setup. You can select the same settings used during setup or select new collation settings. When done, click OK.
In the Rebuild Master dialog box, click Rebuild to start the process.
The Rebuild Master utility reinstalls the master database.
To continue, you may need to stop a server that is running.
Source: http://msdn2.microsoft.com/en-us/library/aa197950(SQL.80).aspx

What is the basic functions for master, msdb, model, tempdb databases?
The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.

What are primary keys and foreign keys?
Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys and constraints. A table can have only one Primary key.
Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables.

What is data integrity? Explain constraints?
Data integrity is an important feature in SQL Server. When used properly, it ensures that data is accurate, correct, and valid. It also acts as a trap for otherwise undetectable bugs within applications.

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 links 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.
When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties �> Port number.both on client and the server.

What is Identity?
Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers, the value of this cannot be controled. Identity/GUID columns do not need to be indexed.

XML Question & Ans

Where should I use XML?
Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML has been designed for ease of implementation and for interoperability with both SGML and HTML.
Despite early attempts, browsers never allowed other SGML, only HTML (although there were plugins), and they allowed it (even encouraged it) to be corrupted or broken, which held development back for over a decade by making it impossible to program for it reliably. XML fixes that by making it compulsory to stick to the rules, and by making the rules much simpler than SGML.
But XML is not just for Web pages: in fact it's very rarely used for Web pages on its own because browsers still don't provide reliable support for formatting and transforming it. Common uses for XML include:
Information identification
because you can define your own markup, you can define meaningful names for all your information items. Information storage
because XML is portable and non-proprietary, it can be used to store textual information across any platform. Because it is backed by an international standard, it will remain accessible and processable as a data format. Information structure
XML can therefore be used to store and identify any kind of (hierarchical) information structure, especially for long, deep, or complex document sets or data sources, making it ideal for an information-management back-end to serving the Web. This is its most common Web application, with a transformation system to serve it as HTML until such time as browsers are able to handle XML consistently. Publishing
The original goal of XML as defined in the quotation at the start of this section. Combining the three previous topics (identity, storage, structure) means it is possible to get all the benefits of robust document management and control (with XML) and publish to the Web (as HTML) as well as to paper (as PDF) and to other formats (e.g. Braille, Audio, etc) from a single source document by using the appropriate style sheets. Messaging and data transfer
XML is also very heavily used for enclosing or encapsulating information in order to pass it between different computing systems which would otherwise be unable to communicate. By providing a lingua franca for data identity and structure, it provides a common envelope for inter-process communication (messaging). Web services
Building on all of these, as well as its use in browsers, machine-processable data can be exchanged between consenting systems, where before it was only comprehensible by humans (HTML). Weather services, e-commerce sites, blog newsfeeds, AJAX sites, and thousands of other data-exchange services use XML for data management and transmission, and the web browser for display and interaction.
Why is XML such an important development?

It removes two constraints which were holding back Web developments:
1. dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for;
2. the complexity of full SGML, whose syntax allows many powerful but hard-to-program options.
XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
Describe the role that XSL can play when dynamically generating HTML pages from a relational database.
Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules.
What is SGML?
SGML is the Standard Generalized Markup Language (ISO 8879:1986), the international standard for defining descriptions of the structure of different types of electronic document. There is an SGML FAQ from David Megginson at http://math.albany.edu:8800/hm/sgml/cts-faq.htmlFAQ; and Robin Cover's SGML Web pages are at http://www.oasis-open.org/cover/general.html. For a little light relief, try Joe English's ‘Not the SGML FAQ’ at http://www.flightlab.com/~joe/sgml/faq-not.txtFAQ.
SGML is very large, powerful, and complex. It has been in heavy industrial and commercial use for nearly two decades, and there is a significant body of expertise and software to go with it.
XML is a lightweight cut-down version of SGML which keeps enough of its functionality to make it useful but removes all the optional features which made SGML too complex to program for in a Web environment.
Aren't XML, SGML, and HTML all the same thing?
Not quite; SGML is the mother tongue, and has been used for describing thousands of different document types in many fields of human activity, from transcriptions of ancient Irish manuscripts to the technical documentation for stealth bombers, and from patients' clinical records to musical notation. SGML is very large and complex, however, and probably overkill for most common office desktop applications.
XML is an abbreviated version of SGML, to make it easier to use over the Web, easier for you to define your own document types, and easier for programmers to write programs to handle them. It omits all the complex and less-used options of SGML in return for the benefits of being easier to write applications for, easier to understand, and more suited to delivery and interoperability over the Web. But it is still SGML, and XML files may still be processed in the same way as any other SGML file (see the question on XML software).
HTML is just one of many SGML or XML applications—the one most frequently used on the Web.
Technical readers may find it more useful to think of XML as being SGML-- rather than HTML++.
Who is responsible for XML?
XML is a project of the World Wide Web Consortium (W3C), and the development of the specification is supervised by an XML Working Group. A Special Interest Group of co-opted contributors and experts from various fields contributed comments and reviews by email.
XML is a public format: it is not a proprietary development of any company, although the membership of the WG and the SIG represented companies as well as research and academic institutions. The v1.0 specification was accepted by the W3C as a Recommendation on Feb 10, 1998.
Why is XML such an important development?
It removes two constraints which were holding back Web developments:
1. dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for;
2. the complexity of full question A.4, SGML, whose syntax allows many powerful but hard-to-program options.
XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

Why should I use XML?
Here are a few reasons for using XML (in no particular order). Not all of these will apply to your own requirements, and you may have additional reasons not mentioned here (if so, please let the editor of the FAQ know!).
* XML can be used to describe and identify information accurately and unambiguously, in a way that computers can be programmed to ‘understand’ (well, at least manipulate as if they could understand).
* XML allows documents which are all the same type to be created consistently and without structural errors, because it provides a standardised way of describing, controlling, or allowing/disallowing particular types of document structure. [Note that this has absolutely nothing whatever to do with formatting, appearance, or the actual text content of your documents, only the structure of them.]
* XML provides a robust and durable format for information storage and transmission. Robust because it is based on a proven standard, and can thus be tested and verified; durable because it uses plain-text file formats which will outlast proprietary binary ones.
* XML provides a common syntax for messaging systems for the exchange of information between applications. Previously, each messaging system had its own format and all were different, which made inter-system messaging unnecessarily messy, complex, and expensive. If everyone uses the same syntax it makes writing these systems much faster and more reliable.
* XML is free. Not just free of charge (free as in beer) but free of legal encumbrances (free as in speech). It doesn't belong to anyone, so it can't be hijacked or pirated. And you don't have to pay a fee to use it (you can of course choose to use commercial software to deal with it, for lots of good reasons, but you don't pay for XML itself).
* XML information can be manipulated programmatically (under machine control), so XML documents can be pieced together from disparate sources, or taken apart and re-used in different ways. They can be converted into almost any other format with no loss of information.
* XML lets you separate form from content. Your XML file contains your document information (text, data) and identifies its structure: your formatting and other processing needs are identified separately in a stylesheet or processing system. The two are combined at output time to apply the required formatting to the text or data identified by its structure (location, position, rank, order, or whatever).
Describe the differences between XML and HTML.
It's amazing how many developers claim to be proficient programming with XML, yet do not understand the basic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below.
Differences Between XML and HTML
Table 1.
XML HTML
User definable tags Defined set of tags designed for web display
Content driven Format driven
End tags required for well formed documents End tags not required
Quotes required around attributes values Quotes not required
Slash required in empty tags Slash not required

Describe the role that XSL can play when dynamically generating HTML pages from a relational database.
Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules.
Give a few examples of types of applications that can benefit from using XML.
There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.
What is DOM and how does it relate to XML?
The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.
What is SOAP and how does it relate to XML?
The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.
Can you walk us through the steps necessary to parse XML documents?
Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response.
Give some examples of XML DTDs or schemas that you have worked with.
Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project where no standard existed.
Using XSLT, how would you extract a specific attribute from an element in an XML document?
Successful candidates should recognize this as one of the most basic applications of XSLT. If they are not able to construct a reply similar to the example below, they should at least be able to identify the components necessary for this operation: xsl:template to match the appropriate XML element, xsl:value-of to select the attribute value, and the optional xsl:apply-templates to continue processing the document.
Extract Attributes from XML Data
Example 1.

Attribute Value:




When constructing an XML DTD, how do you create an external entity reference in an attribute value?
Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.
How would you build a search engine for large volumes of XML data?
The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data.
Obviously, some important areas of XML technologies were not included in this list -- namespaces, XPointer, XLink, and so on -- and should be added to the interviewer's set of questions if applicable to the particular position that the candidate is applying for. However, these questions in conjunction with others to assess soft skills (communication skills, ability to work on teams, leadership ability, etc.) will help determine how well candidates understand the fundamental principles of XML.
What is Xpath?



What is Xpath?
XPath is used to navigate through elements and attributes in an XML document.

What is XSL?

XSLT - a language for transforming XML documents
XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.

XPath - a language for navigating in XML documents
XSL-FO - a language for formatting XML documents

How Schemas Differ from DTDs?
The first, and probably most significant, difference between XML Schemas and XML DTDs is that XML Schemas use XML document syntax. While transforming the syntax to XML doesn’t automatically improve the quality of the description, it does make those descriptions far more extensible than they were in the original DTD syntax. Declarations can have richer and more complex internal structures than declarations in DTDs, and schema designers can take advantage of XML’s containment hierarchies to add extra information where appropriate — even sophisticated information like documentation. There are a few other benefits from this approach. XML Schemas can be stored along with other XML documents in XML-oriented data stores, referenced, and even styled, using tools like XLink, XPointer, and XSL.

The largest addition XML Schemas provide to the functionality of the descriptions is a vastly improved data typing system. XML Schemas provide data-oriented data types in addition to the more document-oriented data types XML 1.0 DTDs support, making XML more suitable for data interchange applications. Built-in datatypes include strings, booleans, and time values, and the XML Schemas draft provides a mechanism for generating additional data types. Using that system, the draft provides support for all of the XML 1.0 data types (NMTOKENS, IDREFS, etc.) as well as data-specific types like decimal, integer, date, and time. Using XML Schemas, developers can build their own libraries of easily interchanged data types and use them inside schemas or across multiple schemas.

The current draft of XML Schemas also uses a very different style for declaring elements and attributes to DTDs. In addition to declaring elements and attributes individually, developers can create models — archetypes — that can be applied to multiple elements and refined if necessary. This provides a lot of the functionality SOX had developed to support object-oriented concepts like inheritance. Archetype development and refinement will probably become the mark of the high-end schema developer, much as the effective use of parameter entities was the mark of the high-end DTD developer. Archetypes should be easier to model and use consistently, however.

XML Schemas also support namespaces, a key feature of the W3C’s vision for the future of XML. While it probably wouldn’t be impossible to integrate DTDs and namespaces, the W3C has decided to move on, supporting namespaces in its newer developments and not retrofitting XML 1.0. In many cases, provided that namespace-prefixes don’t change or simply aren’t used, DTD’s can work just fine with namespaces, and should be able to interoperate with namespaces and schema processing that relies on namespaces. There will be a few cases, however, where namespaces may force developers to use the newer schemas rather than the older DTDs.

Friday, June 12, 2009

Validation - RegularExpression

Validation:
.Net inbuilt validation control custmaization
1)Create .cs class
#region LoadREVforLongText1
public RegularExpressionValidator LoadREVforLongText1(string controlName, string errorMsg, bool isValidationSummary, string valGroup)
{
RegularExpressionValidator revControl = new RegularExpressionValidator();
revControl.ValidationGroup = valGroup;
revControl.ControlToValidate = controlName;
revControl.ValidationExpression = @"(?!.*?\b\w{31,}).*";
revControl.ErrorMessage = "Please enter " + errorMsg + " words length max 30";

if (isValidationSummary == true)
{
revControl.Display = ValidatorDisplay.None;
}

return revControl;
}
#endregion

2)Create a instance for the class on .aspx.cs/.ascx.cs
ValidationControls vc = new ValidationControls();
protected void RegisterValidationControls()
{
RegularExpressionValidator revFullName = vc.LoadREVforLongText1 ("txtFullName", "full name", true, "2");
div_fullname.Controls.Add(revFullName);
}
3)call the above method on the page load event.

4)validating text should have div block. where the error message will display.

5)Need's to put validation summary in design page. set the properties ValidationGroup="2" DisplayMode="List"

Regular Expression:
for Phone no:
= @"^[\(\)\{\}\[\] a-zA-Z0-9''+,-]{0,100}$"
for Email with hypen
= @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
for Email without hypen
= @"^([0-9a-zA-Z]([.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
for Long text without space
= @"(?!.*?\b\w{31,}).*";

#region is Valid word
public bool isValid(string strText, int maxchars)
{
if (strText.Trim().Length > 0)
{
strText = strText.Trim();

string[] strLines = strText.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int cnt = 0;
for (int i = 0; i < strLines.Length; i++)
{
string[] strWords = strLines[i].Split(' ');
cnt += strWords.Length;
for (int j = 0; j < strWords.Length; j++)
{
if (strWords[j].Length > maxchars)
{
return false;
}
}
}
}
return true;
}
#endregion

SilverLight

What is Silverlight?

Silverlight is a new cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and Rich Interactive Applications(RIA) for the web. It runs in all popular browsers, including Microsoft Internet Explorer, Mozilla Firefox, Apple Safari, Opera. The plugin required to run Silverlight is very small in size hence gets installed very quickly.

It is combination of different technolgoies into a single development platform that allows you to select tools and the programming language you want to use. Silverlight integrates seamlessly with your existing Javascript and ASP.NET AJAX code to complement functionality which you have already created.

Silverlight aims to compete with Adobe Flash and the presentation components of Ajax. It also competes with Sun Microsystems' JavaFX, which was launched a few days after Silverlight.

Currently there are 2 major versions of Silverlight:

Silverlight 1.0 and Silverlight 2.0( previously referred to as version 1.1).

Silverlight 1.0 :

Silverlight 1.0 consists of the core presentation framework, which is responsible for UI, interactivity and user input, basic UI controls, graphics and animation, media playback, DRM support, and DOM integration.

Main features of Silverlight 1.0 :

1. Built-in codec support for playing VC-1 and WMV video, and MP3 and WMA audio within a browser.
2. Silverlight supports the ability to progressively download and play media content from any web-server.
3. Silverlight also optionally supports built-in media streaming.
4. Silverlight enables you to create rich UI and animations, and blend vector graphics with HTML to create compelling content experiences.
5. Silverlight makes it easy to build rich video player interactive experiences.

Silverlight 2.0 :

Silverlight 2.0 includes a version of the .NET Framework, with the full Common Language Runtime as .NET Framework 3.0; so it can execute any .NET language including VB.NET and C# code. Unlike the CLR included with .NET Framework, multiple instances of the CoreCLR included in Silverlight can be hosted in one process. With this, the XAML layout markup file (.xaml file) can be augmented by code-behind code, written in any .NET language, which contains the programming logic.

This version ships with more than 30 UI controls(including TextBox, CheckBox, Slider, ScrollViewer, and Calendar controls), for two-way databinding support, automated layout management (by means of StackPanel, Grid etc) as well as data-manipulation controls, such as DataGrid and ListBox. UI controls are skinnable using a template-based approach.

Main features of Silverlight 2.0 :

1. A built-in CLR engine that delivers a super high performance execution environment for the browser. Silverlight uses the same core CLR engine that we ship with the full .NET Framework.
2. Silverlight includes a rich framework library of built-in classes that you can use to develop browser-based applications.
3. Silverlight includes support for a WPF UI programming model. The Silverlight 1.1 Alpha enables you to program your UI with managed code/event handlers, and supports the ability to define and use encapsulated UI controls.
4. Silverlight provides a managed HTML DOM API that enables you to program the HTML of a browser using any .NET language.
5. Silverlight doesn't require ASP.NET to be used on the backend web-server (meaning you could use Silverlight with with PHP on Linux if you wanted to).
6. Silverlight 2 includes Deep Zoom, a technology derived from Microsoft Live Labs Seadragon. It allows users to zoom into, or out of, an image (or a collage of images), with smooth transitions, using the mouse wheel. The images can scale from 2 or 3 megapixels in resolution into the gigapixel range, but the user need not wait for it to be downloaded entirely; rather, Silverlight downloads only the parts in view, optimized for the zoom level being viewed.
7. Silverlight 2 also allows limited filesystem access to Silverlight applications. It can use the operating system's native file dialog box to browse to any file (to which the user has access).


How Silverlight would change the Web:

1. Highest Quality Video Experience : prepare to see some of the best quality videos you have seen in your life, all embedded in highly graphical websites. The same research and technology that was used for VC-1, the codec that powers BluRay and HD DVD, is used by Microsoft today with its streaming media technologies.
2. Cross-Platform, Cross-Browser : Finally build web applications that work on any browser, and on any operating system. At release, Silverlight will work with Mac as well as Windows! The Mono project has also already promised support for Linux!.
3. Developers and Graphic Designers can play together! : Developers familiar with Visual Studio, Microsoft.net will be able to develop amazing Silverlight applications very quickly, and they will work on Mac's and Windows. Developers will finally be able to strictly focus on the back end of the application core, while leaving the visuals to the Graphic Design team using the power of XAML.
4. Cheaper : Silverlight is now the most inexpensive way to stream video files over the internet at the best quality possible. Licensing is dead simple, all you need is IIS in Windows Server, and you’re done.
5. Support for 3rd Party Languages : Using the power of the new Dynamic Language Runtime, developers will now be able to use Ruby, Python, and EcmaScript! This means a Ruby developer can develop Silverlight applications, and leverage the .net Framework!
6. Cross-Platform, Cross-Browser Remote Debugging : If you are in the need to debug an application running on a Mac, no problem! You can now set breakpoints, step into/over code, have immediate windows, and all that other good stuff that Visual Studio provides.
7. The best development environment on the planet : Visual Studio is an award winning development platform! As it continues to constantly evolve, so will Silverlight!
8. Silverlight offers copy protection : Have you noticed how easy it is to download YouTube videos to your computer, and save them for later viewing ? Silverlight will finally have the features enabling content providers complete control over their rich media content! Streaming television, new indie broadcast stations, all will now be possible!
9. Extreme Speed :There is a dramatic improvement in speed for AJAX-enabled websites that begin to use Silverlight, leveraging the Microsoft .net framework.

Thursday, June 11, 2009

Excel File Import to Gridview (HTML Format/normal)

Excel file directly read and fill the value into Gridview.
below code read the file from application physicalpath/upload control posted file.

DataSet ds = new DataSet();

void BindtheGrid()
{
string path = "C\\Projects\\LogicTest\\Report.xls";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + path + "Extended Properties='Excel 8.0;IMEX=1;'";
//You must use the $ after the object you reference in the spreadsheet
//OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Report$] ", strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter();
DataTable dt;
try
{
myCommand.Fill(ds, "Report");
dt = ds.Tables["Report"];
}
catch (Exception ex)
{
//when the excel file could not read ie file is not in format
/* HttpPostedFile httpUploadedCSV = uploadgroup.PostedFile;
StreamReader sr = new StreamReader(httpUploadedCSV.InputStream); if the file is posed by file control*/

string filename = Server.MapPath("Report.xls"); // it is reading directly from the server location
StreamReader sr = default(StreamReader);
sr = File.OpenText(filename);


string s = sr.ReadToEnd();

DataSet ds = ConvertHTMLTablesToDataSet(s);
//dt = ds.Tables[0];
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
Some time imported file may be HTML format it would have been stored. needs to read and get the proper dataset/datatable:

protected DataSet ConvertHTMLTablesToDataSet(string HTML)
{
//' Declarations

try
{



MatchCollection Tables = Regex.Matches(HTML, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);

// ' Get a match for all the tables in the HTML

foreach (Match table in Tables)
{


// ' Reset the current row counter and the header flag
iCurrentRow = 0;
HeadersExist = false;

//' Add a new table to the DataSet
dt = new DataTable();

//' Create the relevant amount of columns for this table (use the headers if they exist, otherwise use default names)

if (table.Value.Contains(" {
// ' Set the HeadersExist flag
HeadersExist = true;

//' Get a match for all the rows in the table
MatchCollection Headers = Regex.Matches(table.Value, HeaderExpression, (RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase));

// ' Loop through each header element
foreach (Match Header in Headers)
{
dt.Columns.Add(Header.Groups[1].ToString());
}
}
else
{
for (int iColumns = 1; iColumns < Regex.Matches(Regex.Matches(Regex.Matches(table.Value, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).ToString(), RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).ToString(), ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Count; iColumns++)
{
dt.Columns.Add("Column " + iColumns);
}
}

//' Get a match for all the rows in the table
MatchCollection Rows = Regex.Matches(table.Value, RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);

//' Loop through each row element
foreach (Match Row in Rows)
{


// ' Only loop through the row if it isn't a header row

if (!(iCurrentRow == 0 & HeadersExist == true))
{

// ' Create a new row and reset the current column counter
dr = dt.NewRow();
iCurrentColumn = 0;

// ' Get a match for all the columns in the row
MatchCollection Columns = Regex.Matches(Row.Value, ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);

// ' Loop through each column element
foreach (Match Column in Columns)
{
if (Column.Groups[1].ToString().Trim() == " ")
{
dr[iCurrentColumn] = "";
}
else
{
dr[iCurrentColumn] = Column.Groups[1].ToString().Trim();
}
// ' Increase the current column
iCurrentColumn += 1;
}

// ' Add the DataRow to the DataTable
dt.Rows.Add(dr);

}

// ' Increase the current row counter
iCurrentRow += 1;
}


//' Add the DataTable to the DataSet
ds.Tables.Add(dt);

}

}
catch (Exception e)
{
//lblerr.Text = "File is not in the Expected Format. Save the File as 'Excel 97-2003 Workbook' Format, then try Import.";
if (ds.Tables.Count == 0)
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
}
}
return ds;
}

Tuesday, June 9, 2009

GridView Export into excel & Generate XML Dataset Values

DAL - Data Access Layer

static SqlConnection GetConnectionObject()
{
SqlConnection con = new SqlConnection();
string connectionstring;
try
{
connectionstring = ConfigurationManager.ConnectionStrings["logictest"].ConnectionString; ;
con.ConnectionString = connectionstring;

return con;
}
catch (Exception ex)
{
throw ex;
}

}

public static DataSet ExecuteSQLReturnDataSet(string strSQL)
{
DataSet ds = new DataSet("DataSet");
SqlConnection con = GetConnectionObject();
SqlDataAdapter da = new SqlDataAdapter(strSQL, con);
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
da.Dispose();
ds.Dispose();
}
}

GridView Export into excel:
Method to GeneratetheReport:

public void ReportGeneration(DataSet dset, string filename)
{

GridView gv = new GridView();
gv.DataSource = dset;
gv.DataBind(); //Read the grid value however the report format may be excel/pdf
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.OutputStream.Write(new byte[] { 0xef, 0xbb, 0xbf }, 0, 3);
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + "");
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
gv.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Write(oStringWriter.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

On btnclic/load event call the below method

void BindGridView()
{
DataSet ds = new DataSet();
ds = ExecuteSQLReturnDataSet("select * from tablename");
grd.DataSource = ds;
grd.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
ReportGeneration(ds, "Report.xls");
}
}
Generate XML Dataset Values:
public void XMLGenarate()
{
string XMLFileName = "C:/Projects/XMLGenerate" + DateTime.Now.ToString("dd-mm-yyyy") +""; // can set it in web.config
DataSet ds = new DataSet();
ds = ExecuteSQLReturnDataSet("select * from tableName"); // can pass it as a parameter of(string) / from Data Access Layer which has coding standard.
FileStream fs = null;
if (ds.Tables[0].Rows.Count > 0)
{
fs = new FileStream(XMLFileName + ".xml", FileMode.OpenOrCreate, FileAccess.Write);
ds.WriteXml(fs);
fs.Close();
}

}

on btnclick/load event call the above method.

Using the FOR XML Clause to Return Query Results as XML

SQL Server lets you retrieve data as XML by supporting the FOR XML clause, which can be included as part of your query. You can use the FOR XML clause in the main (outer) query as well as in subqueries. The clause supports numerous options that let you define the format of the XML data.

When you include the FOR XML clause in your query, you must specify one of the four supported modes—RAW, AUTO, EXPLICIT, or PATH. The options available to each mode vary according to that mode; however, many of the options are shared among the modes. In this article, I explain how to use each of these modes to retrieve data as XML and provide examples that demonstrate how they use the various options.

The RAW Mode

The RAW mode generates a single XML element for each row in the result set returned by the query.

To use the FOR XML clause in RAW mode, you simply append the clause and RAW keyword to your SELECT statement, as shown in the following example:

it return row's in a form of xml.

SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName
FROM HumanResources.Employee e INNER JOIN Person.Contact c
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Rob'
FOR XML RAW;

row's get the id basix (ie name)

SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName
FROM HumanResources.Employee e INNER JOIN Person.Contact c
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Rob'
FOR XML RAW ('Employee');

can specify only roots/ elements to

SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName
FROM HumanResources.Employee e INNER JOIN Person.Contact c
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Rob'
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS;

no elements are created for a column whose value is null. However, you can override this behavior by adding the XSINIL keyword to the ELEMENTS option:

SELECT e.EmployeeID, c.FirstName, c.MiddleName, c.LastName
FROM HumanResources.Employee e INNER JOIN Person.Contact c
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Rob'
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL;

Copyright © 2009 Angel