Wednesday, January 16, 2013

Indexers

Indexers allow your class to be used just like an array. On the inside of a class, you manage a collection of values any way you want.

using System;

///
///
     A simple indexer example.
///

class IntIndexer
{
    private string[] myData;

    public IntIndexer(int size)
    {
        myData =
new string[size];

        for (int i=0; i < size; i++)
        {
            myData[i] = "empty";
        }
    }

    public
string this[int pos]
    {
        get
       {
            return myData[pos];
        }
        set
       {
            myData[pos] =
value;
        }
    }

    static
void Main(string[] args)
    {
        int size = 10;

        IntIndexer myInd =
new IntIndexer(size);

        myInd[9] = "Some Value";
        myInd[3] = "Another Value";
        myInd[5] = "Any Value";

        Console.WriteLine("\nIndexer Output\n");

        for
(int i=0; i < size; i++)
        {
            Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
        }
    }
}

Partial Class

Partial type definitions allow the definition of a class, struct or interface to be split into multiple files.

In File1.cs:
namespace PC
{
    partial class A { }
}
In File2.cs:
namespace PC
{
    partial class A { }
}
 
Splitting a class, struct or interface type over several files can be useful when working with large projects, or with automatically generated code such as that provided by the Windows Forms Designer. For more information, see Partial Classes.

Sunday, January 13, 2013

New features in SQl Server 2008.

1.Compressed Storage of Tables and Indexes
 SQL Server 2008 supports both row and page compression for both tables and indexes. Data compression can be configured for the following database objects:

  •     A whole table that is stored as a heap.
  •     A whole table that is stored as a clustered index.
  •     A whole nonclustered index.
  •     A whole indexed view.
2. FILESTREAM Storage
FILESTREAM in SQL Server 2008 enables SQL Server-based applications to store unstructured data, such as documents and images, on the file system. VARBINARY(MAX)
Standard VARBINARY(MAX) data is limited to 2 GB.

3. Sparse Columns
Sparse columns are ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values. Consider using sparse columns when the space saved is at least 20 percent to 40 percent.

CREATE TABLE dbo.T1
(
  keycol INT                   NOT NULL PRIMARY KEY,
  col1   VARCHAR(20)           NOT NULL,
  col2   INT            SPARSE     NULL,

  col3   CHAR(10)       SPARSE     NULL,

  col4   NUMERIC(12, 2) SPARSE     NULL
);


4. IntelliSense for Query Editing

5.Query Editor Regions

6.Filtered Indexes 
SQL Server 2008 introduces filtered indexes and statistics. You can now create a nonclustered index based on a predicate, and only the subset of rows for which the predicate holds true are stored in the index B-Tree. Similarly, you can manually create statistics based on a predicate.


CREATE NONCLUSTERED INDEX idx_currate_notnull
  ON Sales.SalesOrderHeader(CurrencyRateID)
  WHERE CurrencyRateID IS NOT NULL;

7. DDL Trigger Enhancements 

In SQL Server 2008, the type of events on which you can now create DDL triggers is enhanced to include stored procedures that perform DDL-like operations. This gives you more complete coverage of DDL events that you can capture with triggers.

Many stored procedures perform DDL-like operations. Before SQL Server 2008, you could not capture their invocation with a trigger. Now you can capture many new events that fire as a result of calls to such procedures. For example, the stored procedure sp_rename now fires a trigger created on the new RENAME event. 

 8.Grouping Sets

SQL Server 2008 introduces several extensions to the GROUP BY clause that enable you to define multiple groupings in the same query. 

SELECT custid, empid, YEAR(orderdate) AS orderyear, SUM(qty) AS qty
FROM dbo.Orders
GROUP BY GROUPING SETS (

  ( custid, empid, YEAR(orderdate) ),


The following statements are equivalent:
SELECT customer, year, SUM(sales)
FROM T
GROUP BY GROUPING SETS ((customer), (year))
SELECT customer, NULL as year, SUM(sales)
FROM T 
GROUP BY customer
UNION ALL
SELECT NULL as customer, year, SUM(sales)
FROM T 
GROUP BY year

 9. MERGE Statement

The new MERGE statement is a standard statement that combines INSERT, UPDATE, and DELETE actions as a single atomic operation based on conditional logic.

 MERGE INTO dbo.Customers AS TGT
USING dbo.CustomersStage AS SRC
  ON TGT.custid = SRC.custid
WHEN MATCHED THEN
  UPDATE SET
    TGT.companyname = SRC.companyname,
    TGT.phone = SRC.phone,
    TGT.address = SRC.address
WHEN NOT MATCHED THEN
  INSERT (custid, companyname, phone, address)
  VALUES (SRC.custid, SRC.companyname, SRC.phone, SRC.address)

10. Table Types 

SQL Server 2008 introduces table types and table-valued parameters that help abbreviate your code and improve its performance. 

 You use the CREATE TYPE statement to create a new table type. For example, the following code defines a table type called OrderIDs in database:

CREATE TYPE dbo.OrderIDs AS TABLE ( pos INT NOT NULL PRIMARY KEY,
  orderid INT NOT NULL UNIQUE );

DECLARE @T AS dbo.OrderIDs;
INSERT INTO @T(pos, orderid) VALUES(1, 51480),(2, 51973),(3, 51819);

SELECT pos, orderid FROM @T ORDER BY pos;

11. Large UDTs

In SQL Server 2005, user-defined types (UDTs) in the CLR were limited to 8,000 bytes. SQL Server 2008 lifts this limitation and now supports large UDTs. Similar to the built-in large object types that SQL Server supports, large UDTs can now reach up to 2 GB in size.

12. Date and Time Data Types

 Before SQL Server 2008, date and time improvements were probably at the top of the list of the most requested improvements for SQL Server—especially the request for separate date and time data types, but also for general enhanced support for temporal data. SQL Server 2008 introduces four new date and time data types—including DATE, TIME, DATETIME2, and DATETIMEOFFSET—as well as new functions that operate on the new types and enhancements to existing functions. 

13. CONVERT Function

The CONVERT function is enhanced to allow conversions between binary and character hexadecimal values.

14. Spatial:  Two new spatial data types have been added--GEOMETRY and GEOGRAPHY--which you can use to natively store and manipulate location-based information, such as Global Positioning System (GPS) data.

15. HIERARCHYID

While hierarchical tree structures are commonly used in many applications, SQL Server has not made it easy to represent and store them in relational tables. In SQL Server 2008, the HIERARCHYID data type has been added to help resolve this problem. It is designed to store values that represent the position of nodes of a hierarchal tree structure.

For example, the HIERARCHYID data type makes it easier to express these types of relationships without requiring multiple parent/child tables and complex joins.

  •     Organizational structures
  •     A set of tasks that make up a larger projects (like a GANTT chart)
  •     File systems (folders and their sub-folders)
  •     A classification of language terms
  •     A bill of materials to assemble or build a product
  •     A graphical representation of links between web pages 
16. Roll UP

It will do get the sum of group by columns in another row.

SELECT Country,[State],City,
SUM ([Population (in Millions)]) AS [Population (in Millions)]
FROM tblPopulation
GROUP BY Country,[State],City WITH ROLLUP





Friday, January 11, 2013

SQL Server Log Files


1. SQL Server Setup Log
You might already be familiar with the SQL Server 2005 Setup log, which is located at %ProgramFiles%\Microsoft SQL Server\90\Setup Bootstrap\LOG\Summary.txt. If the summary.txt log file shows a component failure, you can investigate the root cause by looking at the component’s log, which you’ll find in the %Program-Files%\Microsoft SQL Server\90\Setup Bootstrap\LOG\Files directory.

2. SQL Server Profiler Log
SQL Server Profiler, the primary application-tracing tool in SQL Server 2005, captures the system’s current database activity and writes it to a file for later analysis. You can find the Profiler logs in the log .trc file in the %ProgramFiles%\Microsoft SQL Server\MSSQL.1\MSSQL\LOG directory.

3. SQL Server Agent Log
SQL Server 2005’s job scheduling subsystem, SQL Server Agent, maintains a set of log files with warning and error messages about the jobs it has run, written to the %ProgramFiles%\Microsoft SQL Server\MSSQL.1\MSSQL\LOG directory. SQL Server will maintain up to nine SQL Server Agent error log files. The current log file is named SQLAGENT .OUT, whereas archived files are numbered sequentially. You can view SQL Server Agent logs by using SQL Server Management Studio (SSMS). Expand a server node, expand Management, click SQL Server Logs, and select the check box for SQL Server Agent.

4. Windows Event Log
An important source of information for troubleshooting SQL Server errors, the Windows Event log contains three useful logs. The application log records events in SQL Server and SQL Server Agent and can be used by SQL Server IntegrationServices (SSIS) packages. The security log records authentication information, and the system log records service startup and shutdown information. To view the Windows Event log, go to Administrative Tools, Event Viewer.

5. SQL Server Error Log
The Error Log, the most important log file, is used to troubleshoot system problems. SQL Server retains backups of the previous six logs, naming each archived log file sequentially. The current error log file is named ERRORLOG. To view the error log, which is located in the %Program-Files%\Microsoft SQL Server\MSSQL.1MSSQL\LOG\ERRORLOG directory, open SSMS, expand a server node, expand Management, and click SQL Server Logs.

Anonymous Methods.

An anonymous method is a method without a name - which is why it is called anonymous. You don't declare anonymous methods like regular methods. Instead they get hooked up directly to events.

>> Because you can hook an anonymous method up to an event directly, a couple of the steps of working with delegates can be removed.

>> An anonymous method uses the keyword, delegate, instead of a method name. This is followed by the body of the method. Typical usage of an anonymous method is to assign it to an event.

By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

Example:

       Button btnHello = new Button();
        btnHello.Text = "Hello";

        btnHello.Click +=
            delegate
            {
                MessageBox.Show("Hello");
            };

        Controls.Add(btnHello);


Using Parameters with Anonymous Methods:

        Button btnHello = new Button();
        btnHello.Text = "Hello";

        btnHello.Click +=
            delegate
            {
                MessageBox.Show("Hello");
            };

        Button btnGoodBye = new Button();
        btnGoodBye.Text = "Goodbye";
        btnGoodBye.Left = btnHello.Width + 5;
        btnGoodBye.Click +=
            delegate(object sender, EventArgs e)
            {
                string message = (sender as Button).Text;
                MessageBox.Show(message);
            };

        Controls.Add(btnHello);
        Controls.Add(btnGoodBye);




What is impersonation?

Impersonation is commonly used in applications that rely on Microsoft Internet Information Services (IIS) to authenticate the user.   


you must include an tag in the Web.config file of this application and set the impersonate attribute to true. For example:

configuration
  system.web
    identity impersonate="true"
  system.web
configuration
 
When impersonation is enabled, only your application code runs under the context of the impersonated user. Applications are compiled and configuration information is loaded using the identity of the ASP.NET process.

You can also add support for specific names to run an application as a configurable identity, as shown in the following example:

  
identity impersonate="true"   userName="contoso\Jane"   password="********" 

What is Jagged Arrays?

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.


int[][] jaggedArray = new int[3][];
 
Before you can use jaggedArray, its elements must be initialized.
You can initialize the elements like this: 

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
 
 
Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };