Feeds:
Posts
Comments

Archive for the ‘Sql Server’ Category

        In my recent project I need to identify all columns on which full text index is created. You can find that in management studio from Database – Storage – Full Text Catalogs and right click on catalog name and select property. It display all tables and columns as shown below,

Full Text Index

Fig – (1) All columns on which full-text index is created.

      An alternative is to use query to find all columns on which full-text index is created.

SELECT tbl.[Name] TableName,clm.[Name] ColumnName FROM
Sys.Tables tbl INNER JOIN Sys.Columns clm
ON tbl.[object_id] = clm.[object_id]
INNER JOIN sys.fulltext_index_columns fic
ON clm.[column_id] = fic.[column_id]
WHERE tbl.[Type] = ‘U’

Happy Programming !!!!

Chirag Darji

ASP.NET Consultant & Trainer

Read Full Post »

Today while working in SQL Server 2008, I encounter an interesting problem which does not allow me to change design of any table in particular database. Each time when I try to change table columns or resize the I receive following message,

Saving changes is not permitted. The changes you made require following tables to be dropped and re-created. You have either made changes to a table that can’t be recreated or enabled the option prevent saving changes that require the table to be re-created. 

blog1

Fig – (1) SQL Server 2008 – Saving changes is not permitted

         You will receive this message when you restore database created on other server. SQL Server 2008 by default prevent changes for database which are created on another server by enabling “Prevent saving changes that require table re-creation” from Tools – Options.

blog2

Fig – (2) Solution – SQL Server 2008 – Saving changes is not permitted

    To solve this go to Tools – Options and uncheck “Prevent saving changes that require table re-creation” option.

Happy Programming !!!

Chirag Darji

Read Full Post »

            While reading MSDN today I came across very interested topic. This is very use full specially in interview. Link shows maximum character allow in NVARCHAR(MAX), NTEXT, VARCHAR(MAX), Maximum cluster index per table, maximum columns per table, Maximum columns per Foreign Key, Maximum Columns in Group By and so on. Here is the link from MSDN OR you can read here copied from MSDN.

The following table specifies the maximum sizes and numbers of various objects defined in SQL Server databases or referenced in Transact-SQL statements.

SQL Server Database Engine object Maximum sizes/numbers SQL Server (32-bit) Maximum sizes/numbers SQL Server (64-bit)

Batch size1

65,536 * Network Packet Size

65,536 * Network Packet Size

Bytes per short string column

8,000

8,000

Bytes per GROUP BY, ORDER BY

8,060

8,060

Bytes per index key2

900

900

Bytes per foreign key

900

900

Bytes per primary key

900

900

Bytes per row8

8,060

8,060

Bytes in source text of a stored procedure

Lesser of batch size or 250 MB

Lesser of batch size or 250 MB

Bytes per varchar(max), varbinary(max), xml, text, or image column

2^31-1

2^31-1

Characters per ntext or nvarchar(max) column

2^30-1

2^30-1

Clustered indexes per table

1

1

Columns in GROUP BY, ORDER BY

Limited only by number of bytes

Limited only by number of bytes

Columns or expressions in a GROUP BY WITH CUBE or WITH ROLLUP statement

10

10

Columns per index key7

16

16

Columns per foreign key

16

16

Columns per primary key

16

16

Columns per nonwide table

1,024

1,024

Columns per wide table

30,000

30,000

Columns per SELECT statement

4,096

4,096

Columns per INSERT statement

4096

4096

Connections per client

Maximum value of configured connections

Maximum value of configured connections

Database size

524,272 terabytes

524,272 terabytes

Databases per instance of SQL Server

32,767

32,767

Filegroups per database

32,767

32,767

Files per database

32,767

32,767

File size (data)

16 terabytes

16 terabytes

File size (log)

2 terabytes

2 terabytes

Foreign key table references per table4

253

253

Identifier length (in characters)

128

128

Instances per computer

50 instances on a stand-alone server for all SQL Server editions except for Workgroup. Workgroup supports a maximum of 16 instances per computer.

SQL Server supports 25 instances on a failover cluster.

50 instances on a stand-alone server.

25 instances on a failover cluster.

Length of a string containing SQL statements (batch size)1

65,536 * Network packet size

65,536 * Network packet size

Locks per connection

Maximum locks per server

Maximum locks per server

Locks per instance of SQL Server5

Up to 2,147,483,647

Limited only by memory

Nested stored procedure levels6

32

32

Nested subqueries

32

32

Nested trigger levels

32

32

Nonclustered indexes per table

999

999

Number of distinct expressions in the GROUP BY clause when any of the following are present: CUBE, ROLLUP, GROUPING SETS, WITH CUBE, WITH ROLLUP

32

32

Number of grouping sets generated by operators in the GROUP BY clause

4,096

4,096

Parameters per stored procedure

2,100

2,100

Parameters per user-defined function

2,100

2,100

REFERENCES per table

253

253

Rows per table

Limited by available storage

Limited by available storage

Tables per database3

Limited by number of objects in a database

Limited by number of objects in a database

Partitions per partitioned table or index

1,000

1,000

Statistics on non-indexed columns

30,000

30,000

Tables per SELECT statement

Limited only by available resources

Limited only by available resources

Triggers per table3

Limited by number of objects in a database

Limited by number of objects in a database

Columns per UPDATE statement (Wide Tables)

4096

4096

User connections

32,767

32,767

XML indexes

249

249

1Network Packet Size is the size of the tabular data stream (TDS) packets used to communicate between applications and the relational Database Engine. The default packet size is 4 KB, and is controlled by the network packet size configuration option.

2The maximum number of bytes in any index key cannot exceed 900 in SQL Server. You can define a key using variable-length columns whose maximum sizes add up to more than 900, provided no row is ever inserted with more than 900 bytes of data in those columns. In SQL Server, you can include nonkey columns in a nonclustered index to avoid the maximum index key size of 900 bytes.

3Database objects include objects such as tables, views, stored procedures, user-defined functions, triggers, rules, defaults, and constraints. The sum of the number of all objects in a database cannot exceed 2,147,483,647.

4Although a table can contain an unlimited number of FOREIGN KEY constraints, the recommended maximum is 253. Depending on the hardware configuration hosting SQL Server, specifying additional FOREIGN KEY constraints may be expensive for the query optimizer to process.

5This value is for static lock allocation. Dynamic locks are limited only by memory.

6If a stored procedure accesses more than 8 databases, or more than 2 databases in interleaving, you will receive an error.

7If the table contains one or more XML indexes, the clustering key of the user table is limited to 15 columns because the XML column is added to the clustering key of the primary XML index. In SQL Server, you can include nonkey columns in a nonclustered index to avoid the limitation of a maximum of 16 key columns. For more information, see Index with Included Columns [ http://msdn.microsoft.com/en-us/library/ms190806.aspx ] .

8 SQL Server supports row-overflow storage which enables variable length columns to be pushed off-row. Only a 24-byte root is stored in the main record for variable length columns pushed out of row; because of this, the effective row limit is higher than in previous releases of SQL Server. For more information, see the "Row-Overflow Data Exceeding 8 KB" topic in SQL Server Books Online.

The following table specifies the maximum sizes and numbers of various objects defined in SQL Server Replication.

SQL Server Replication object Maximum sizes/numbers SQL Server (32-bit) Maximum sizes/numbers SQL Server (64-bit)

Articles (merge publication)

256

256

Articles (snapshot or transactional publication)

32,767

32,767

Columns in a table1 (merge publication)

246

246

Columns in a table2 (SQL Server snapshot or transactional publication)

1,000

1,000

Columns in a table2 (Oracle snapshot or transactional publication)

995

995

Bytes for a column used in a row filter (merge publication)

1,024

1,024

Bytes for a column used in a row filter (snapshot or transactional publication)

8,000

8,000

1If row tracking is used for conflict detection (the default), the base table can include a maximum of 1,024 columns, but columns must be filtered from the article so that a maximum of 246 columns is published. If column tracking is used, the base table can include a maximum of 246 columns. For more information on the tracking level, see the "Tracking Level" section of How Merge Replication Detects and Resolves Conflicts [ http://msdn.microsoft.com/en-us/library/ms151749.aspx ] .

2The base table can include the maximum number of columns allowable in the publication database (1,024 for SQL Server), but columns must be filtered from the article if they exceed the maximum specified for the publication type.

Happy Programming !!!

Chirag Darji

Read Full Post »

        You may receive “Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc” while connection to database.  I got the error when I tried to connect to SQL Server 2005 from Visual studio 2008 using server explorer. The exact error is,

Could not load file or assembly ‘Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91′ or one of its dependencies. The system cannot find the file specified.

     To solve this error you need to download following three updates from Microsoft.

  • Microsoft SQL Server System CLR Types
  • Microsoft SQL Server 2008 Management Objects
  • Microsoft SQL Server 2008 Native Client

I found the solution form here. Thanks to Ahmed !!!

Read Full Post »

       I will discuss how to integrate youtube video in asp.net. Youtube provides the API to access the its huge database of videos. It also provides search facility and customized player for integration.

       First thing you need is to get developer key for accessing youtube service. You can get it from here. Once you get the developer you can use the API URL to retrieve youtube videos. The URL is,

   1: http://www.youtube.com/api2_rest

Fig – (1) Youtube API URL

       There specific parameters that you need to pass in query string to get desire result from youtube. See the list below,

   1: Parameter    Description
   2: =============================================================================================
   3: method       youtube.videos.list_by_tag (only needed as an explicit parameter for REST calls)
   4: dev_id       Your developer ID .
   5: tag          Search keyword
   6: page         The "page number" of results you want to retrieve (e.g. 1, 2, 3)
   7: per_page     The number of results you want to retrieve per page (default 20, maximum 100)

Fig – (2) Parameters for youtube querystring

       So from fig – (1) and (2) if you need to search video for asp.net and you need 10 records per page and page should display 3rd page the the URL will be,

   1: http://www.youtube.com/api2_rest?method=youtube.videos.list_by_tag&dev_id=YOURDEVELOPERID&tag=asp.net&page=3&per_page=10
   2:  

Fig – (3) Querystring for youtube video

      Use page=-1 and per_page=-1 to display all the videos on same page without paging. You will get reply in XML format from this URL. You can retrieve that XML as XML document and use XQuery to to get the desire result. OR you can generate dataset from that XML using ReadXML method. I have used ReadXML method.

      This will create three tables (1) ut_response , (2) video_list and (3) video. in dataset. ut_response table contains the information whether the supplied DeveloperId is correct? If yes, the status field contains “ok”. video_list contains total number of videos returned. video table contains the information about the videos.

   1: private void GetYoutubeVedio()
   2: {      
   3:         
   4:         StringBuilder stbURL = new StringBuilder("http://www.youtube.com/api2_rest?");
   5:         stbURL.Append("method=youtube.videos.list_by_tag");
   6:         stbURL.Append("&dev_id=" + DEVELOPERKEY);
   7:         stbURL.Append("&tag=" + txtSearch.Text.Trim());
   8:         stbURL.Append("&page=-1&per_page=-1"); // you can add custom paging if desired
   9:         
  10:         DataSet ds = new DataSet();
  11:         ds.ReadXml(stbURL.ToString());
  12:  
  13:         dlYoutube.DataSource = ds.Tables[2];
  14:         dlYoutube.DataBind();
  15:         
  16:         
  17: }

Fig – (4)  Function to retrieve youtube video in ASP.NET

     You can retrieve youtube videos using above function in ASP.NET. Youtube also provides player integration details.

      Lets have a look at the code below. This code displays all youtube videos played in same asp.net page.

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetYouTubeVedios.aspx.cs"
   2:     Inherits="Youtube_GetYouTubeVedios" %>
   3:  
   4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   5: <html xmlns="http://www.w3.org/1999/xhtml">
   6: <head runat="server">
   7:     <title>Get Youtube Vedios</title>
   8: </head>
   9: <script src="swfobject.js" type="text/jscript"></script>
  10:     <script type="text/javascript">
  11:  
  12:     var params = { allowScriptAccess: "always" };
  13:     var atts = { id: "myytplayer" };
  14:     
  15:  
  16:   </script>
  17: <body>
  18:     <form id="form1" runat="server">
  19:         <div>
  20:             <table >
  21:                 <tr>
  22:                     <td>
  23:                         Sample application to fetch vedios from Youtube. 
  24:                     </td>                    
  25:                 </tr>
  26:                 <tr>
  27:                     <td>
  28:                         First you need to create developer account in youtube to get developer key. You can get 
  29:                         <a href="http://youtube.com/signup?next=/my_profile_dev" target="_blank">here</a>.
  30:                     </td>                    
  31:                 </tr>
  32:                 <tr>
  33:                     <td>
  34:                         Enter Seach text :
  35:                         <asp:TextBox ID="txtSearch" runat="server" ></asp:TextBox>
  36:                         <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
  37:                     </td>
  38:                 </tr>
  39:                 <tr>
  40:                     <td>
  41:                         <br />
  42:                     </td>
  43:                 </tr>
  44:                 <tr>
  45:                     <td width="80%">
  46:                         <asp:DataList ID="dlYoutube" runat="server" CellPadding="4" ForeColor="#333333" OnItemDataBound="dlYoutube_ItemDataBound">
  47:                             <ItemTemplate>
  48:                                 <table>
  49:                                     <tr>
  50:                                         <td colspan="2">
  51:                                             <asp:Label ID="lblTotle" Font-Bold="true" runat="server" Text='<%# Eval("title")%>'></asp:Label>
  52:                                         </td>
  53:                                     </tr>
  54:                                     <tr>
  55:                                         <td valign="top">
  56:                                             <%--<a id="aURL" style="text-decoration: none" runat="server" href='<%# Eval("url")%>'>
  57:                                                 <asp:Image ID="imgImage" runat="server" ImageUrl='<%# Eval("thumbnail_url")%>' />
  58:                                             </a>--%>
  59:                                             <div runat="server" id="player"></div>
  60:                                             <asp:Literal ID="ltrl" runat="server"></asp:Literal>
  61:                                         </td>
  62:                                         <td valign="top">
  63:                                             <table width="100%">
  64:                                                 <tr>
  65:                                                     <td>
  66:                                                         <asp:Label ID="lblAuthor" runat="server" Text="Author : "></asp:Label>
  67:                                                     </td>
  68:                                                     <td>
  69:                                                         <asp:Label ID="lblAuthorName" runat="server" Text='<%# Eval("author")%>'></asp:Label>
  70:                                                     </td>
  71:                                                 </tr>
  72:                                                 <tr>
  73:                                                     <td valign="top">
  74:                                                         <asp:Label ID="Label1" runat="server" Text="Description : "></asp:Label>
  75:                                                     </td>
  76:                                                     <td>
  77:                                                         <asp:Label ID="Label2" runat="server" Text='<%# Eval("description")%>'></asp:Label>
  78:                                                     </td>
  79:                                                 </tr>
  80:                                                 <tr>
  81:                                                     <td>
  82:                                                         <asp:Label ID="Label3" runat="server" Text="Rating : "></asp:Label>
  83:                                                     </td>
  84:                                                     <td>
  85:                                                         <asp:Label ID="Label4" runat="server" Text='<%# Eval("rating_avg")%>'></asp:Label>
  86:                                                     </td>
  87:                                                 </tr>
  88:                                             </table>
  89:                                         </td>
  90:                                     </tr>
  91:                                 </table>
  92:                             </ItemTemplate>
  93:                             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  94:                             <SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  95:                             <AlternatingItemStyle BackColor="White" ForeColor="#284775" />
  96:                             <ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
  97:                             <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  98:                         </asp:DataList>
  99:                     </td>
 100:                 </tr>
 101:             </table>
 102:         </div>
 103:     </form>
 104: </body>
 105: </html>

Fig – (5) Youtube asp.net aspx page.

   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Collections;
   5: using System.Web;
   6: using System.Web.Security;
   7: using System.Web.UI;
   8: using System.Web.UI.WebControls;
   9: using System.Web.UI.WebControls.WebParts;
  10: using System.Web.UI.HtmlControls;
  11: using System.Text;
  12:  
  13:  
  14: public partial class Youtube_GetYouTubeVedios : System.Web.UI.Page
  15: {
  16:     const string DEVELOPERKEY = "YOUR DEVELOPER KEY";
  17:  
  18:     protected void Page_Load(object sender, EventArgs e)
  19:     {
  20:         
  21:     }
  22:  
  23:     private void GetVedio()
  24:     {      
  25:         
  26:         StringBuilder stbURL = new StringBuilder("http://www.youtube.com/api2_rest?");
  27:         stbURL.Append("method=youtube.videos.list_by_tag");
  28:         stbURL.Append("&dev_id=" + DEVELOPERKEY);
  29:         stbURL.Append("&tag=" + txtSearch.Text.Trim());
  30:         stbURL.Append("&page=-1&per_page=-1"); // you can add custom paging if desired
  31:         
  32:         DataSet ds = new DataSet();
  33:         ds.ReadXml(stbURL.ToString());
  34:  
  35:         dlYoutube.DataSource = ds.Tables[2];
  36:         dlYoutube.DataBind();
  37:         
  38:         
  39:     }
  40:  
  41:     protected void btnSearch_Click(object sender, EventArgs e)
  42:     {
  43:         GetVedio();
  44:     }
  45:     protected void dlYoutube_ItemDataBound(object sender, DataListItemEventArgs e)
  46:     {
  47:         if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  48:         {
  49:             HtmlControl div = (HtmlControl)e.Item.FindControl("player");
  50:             Literal objL = (Literal)e.Item.FindControl("ltrl");
  51:             objL.Text = "<script language='javascript' type='text\\javascript'>swfobject.embedSWF('http://www.youtube.com/v/" + Convert.ToString(DataBinder.Eval(e.Item.DataItem,"id")) + "&enablejsapi=1&playerapiid=ytplayer','" + div.ClientID + "', '425', '356', '8', null, null, params, atts);</script>";
  52:         }
  53:     }
  54: }

Fig – (6) Youtube asp.net aspx.cs page.

 

Happy Programming !!!

Read Full Post »

       I learn about CUBE and ROLLUP function today and I found it really usefull for generating reports. Let me give you one example where we can use ROLLUP and CUBE. Lets say you are developing the E-Commerce application and administrator wants the report which shows products purchased by all user group by product and buyer. You will say that’s really easy and can write the query as shown below,

   1: SELECT CustomerName,CustomerName,SUM(Quantity*PricePerItem)
   2: FROM Orders GROUP BY CustomerName,CustomerName

Fig – (1) Group By clause.

     Which will returns the result as shown below,

Fig – (2) Result of GROUP BY clause

    However what if you want result as display below,

Fig – (3) Desire result

       Here ROLLUP and CUBE comes into the picture and help us. The above result is generated using ROLLUP.  ROLLUP adds new row for each column used in GROUP BY clause. First have a look at the query and then we will discuss more,

   1: SELECT 
   2:     CASE 
   3:     WHEN GROUPING(customername) = 1 THEN 'All Customer' 
   4:     ELSE customername END CustomerName,
   5:     CASE WHEN GROUPING(itemname) = 1 THEN 'All Items' 
   6:     ELSE itemname END ItemName,
   7: SUM(Quantity*PricePerCase) 
   8: FROM orders GROUP BY customername,itemname
   9: WITH ROLLUP

Fig – (4) Query for output shown in fig – 3

       As you can see in query we have used ROLLUP after GROUP BY clause. Here ROLLUP has added new row at line 3,5 and 6 in fig 3. If you have used only one columns in GROUP BY clause then only row will have been added. The new clause in query is GROUPING. GROUPING clause add new column in result set. The value in new column can either be 0 or 1. If the new row is added by the ROLLUP or CUBE then the value of GROUPING column is 1 else 0.

       In fig – 3 we have total price by user name, wow lets assume you want the total price by item name also. Here you have to use CUBE as shown below,

   1: SELECT 
   2:     CASE 
   3:     WHEN GROUPING(customername) = 1 THEN 'All Customer' 
   4:     ELSE customername END CustomerName,
   5:     CASE WHEN GROUPING(itemname) = 1 THEN 'All Items' 
   6:     ELSE itemname END ItemName,
   7: SUM(Quantity*PricePerCase) 
   8: FROM orders GROUP BY customername,itemname
   9: WITH CUBE

Fig – (5) CUBE clause

Fig – (6) Result of CUBE

 

Happy Programming !!!!

Read Full Post »

     The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. To encrypt the connection string in above situation is advisable.

     ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.   

   1: <connectionStrings>
   2:   <add name="cn1" 
   3:           connectionString="Server=DB SERVER;
   4:                             database=TestDatabase;
   5:                             uid=UID;
   6:                             pwd=PWD;" />
   7:  </connectionStrings>

Fig – (1) Connection string section of web.config file

     To encrypt the connection string section follow the steps,

1. Go to Start -> Programm Files -> Microsoft Visual Studio 2005 -> Visual Tools
    -> Microsoft Visual Studio 2005 Command Prompt

2. Type following command,

    aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication

    -pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.

   If you are using IIS base web site the command will be,

   aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”

 -pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.   

   If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”

  Open your web.config file and you can see that connection string is encrypted,

   1: <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
   2:   <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
   3:    xmlns="http://www.w3.org/2001/04/xmlenc#">
   4:    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
   5:    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   6:     <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
   7:      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
   8:      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   9:       <KeyName>Rsa Key</KeyName>
  10:      </KeyInfo>
  11:      <CipherData>
  12:       <CipherValue>Ik+l105qm6WIIQgS9LsnF8RRxQtj2ChEwq7DbHapb440GynFEoGF6Y3EM3Iw/lyDV8+P8bIsketi5Ofy9gpZlCBir7n315Q6RPbdclUo79o/LKadhX4jHFpnSIQNIF/LhwjwkLFC0=</CipherValue>
  13:      </CipherData>
  14:     </EncryptedKey>
  15:    </KeyInfo>
  16:    <CipherData>
  17:     <CipherValue>JsLrQ5S8Pq3U72nQzmSl/XlLX72GM0O3EbPLaHRNvjTDgG9seDflGMjTfO10M1s7/mPh//3MhA7pr0dNHUJ143Svhu5YXODRC6z9CkR0uyE4H7uDvTKJ8eR3m9APhXoo1sT1K3tCLHD6a2BM+gqSk9d8PzCfbM8Gmzmpjz1ElIaxu62b4cg9SNxp8o86O9N3fBl2mq</CipherValue>
  18:    </CipherData>
  19:   </EncryptedData>
  20:  </connectionStrings>

Fig – (2) Encrypted connection string section

 

       You do not have to write any code to decrypt this connection string in your application, dotnet automatically decrypts it. So if you write following code you can see plaintext connection string.

   1: Response.Write(ConfigurationManager.ConnectionStrings["cn1"].ConnectionString);

 

    Now to decrypt the configuration section in web.config file use following command,

For File System Application,

aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication

For IIS based Application

aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication”

 

    If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,

aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication

     You can encrypt all the sections of web.config file except following using the method I displayed in this article,

<processModel>
<runtime>
<mscorlib>
<startup>
<system.runtime.remoting>
<configProtectedData>
<satelliteassemblies>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>

   To encrypt these section you needed to use Aspnet_setreg.exe tool.  For more detail about Aspnet_setreg.exe tool search Microsoft Knowledge Base article 329290, How to use the ASP.NET utility to encrypt credentials and session state connection strings.

 

Happy Programming !!!

Read Full Post »

        Today I came to know that we can use CASE with ORDER BY clause.  Its a nice functionality which helps you to avoid UNIOUN when you have to display the records in some specific order and still you need to sort them.

     As shown below I have created an Employee table with ID (Primary key),Name, Address and Phone columns.

Fig – (1) Employee  table.

         I have also inserted some temporary data as shown below,

   1: INSERT INTO Employee VALUES ('Chirag Darji','Ahmedabad','123456789')
   2: INSERT INTO Employee VALUES ('Dipak Patel','USA','123456789')
   3: INSERT INTO Employee VALUES ('Shailesh Patel','USA','123456789')
   4: INSERT INTO Employee VALUES ('Piyush Vadher','Gujarat','123456789')
   5: INSERT INTO Employee VALUES ('Mihir Panchal','Gujarat','123456789')
   6: INSERT INTO Employee VALUES ('Vishal Patel','Ahmedabad','123456789')

 Fig – (2)  Insert Statements

     Now consider that have to display the records of employee table order by Address however you want first it should display all the records with USA in address field then Ahmedabad then Gujarat and after that all. Here is the output that we want,

Fig – (3)  Result

      Below is the query that displays the result as shown in fig – (3),

   1: SELECT * FROM Employee ORDER BY
   2: CASE WHEN Address = 'USA' THEN 1
   3: WHEN Address = 'Ahmedabad' THEN 2
   4: WHEN Address = 'Gujarat' THEN 3
   5: ELSE 4
   6: END

 

Happy Programming !!!

Read Full Post »

         A very common question during the interview is to provide difference between IDENT_CURRENT, @@IDENTITY and SCOPE_IDENTITY().  All are used to retrieve the value of identity column after DML statement execution. All three functions return last-generated identity values. However, the scope and session on which last is defined in each of these functions differ:

  • IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
  • SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.

The IDENT_CURRENT function returns NULL when the function is invoked on an empty table or on a table that has no identity column.

I found a good article and an example which explains the difference very effectively. Here is the link for that.

Happy Programming !!!

Read Full Post »

       As we all know SQL Server 2005 has CLR integrated with it. This means one can write a code in manage application and execute it SQL Server. I read about this since Microsoft has launched SQL Server 2005, however I have never used it practically till last week.

       First question came in my mind when I read about CLR integration was why we require CLR in SQL. After searching on internet and reading some good articles I found the reason.  As we all know SQL server has performance issue with cursor and looping.  When we use recursive functions or a cursor in stored procedures we have to compromise with performance.  While integrating CLR we can write the looping and recursive functionalities in C# (or any other language). CLR stored procedures can take advantage of the built-in functionality provided by the classes in the .NET Framework, making it relatively easy to add functionality such as complex mathematical expressions or data encryption. Plus, since CLR stored procedure are compiled rather than interpreted like T-SQL, they can provide a significant performance advantage for code that’s executed multiple times. Here is the link which shows real time performance difference between T-SQL statements and CLR Procedure. The second reason can be (which is my observation) most of the developers are really good at programming however when it comes to deal with SQL sps and user defined functions they are not as smart as in programming.

       In this article I will show you how to create a CLR stored procedure and how to use in code.

      Open visual studio, click on new project and select SQL Server project from C# or VB projects and name it as LearnCLRIntegration,

Fig – (1) Creating new project.

         Right click on on project in solution explorer and select Add New Item and select stored procedure.

Fig –  (2) Create New Stored Procedure.

        This will generate a new class as shown in code snippiest,

   1: using System;
   2: using System.Data;
   3: using System.Data.SqlClient;
   4: using System.Data.SqlTypes;
   5: using Microsoft.SqlServer.Server;
   6:  
   7:  
   8: public partial class StoredProcedures
   9: {
  10:     [Microsoft.SqlServer.Server.SqlProcedure]
  11:     public static void StoredProcedure1()
  12:     {
  13:         // Put your code here
  14:     }
  15: };

Fig – (3) Code Snippiest for new CLR stored procedure.

       [Microsoft.SqlServer.Server.SqlProcedure] attributes tells the compiler that the fuction StoredProcedure1() will be the CLR stored procedure. You can have SqlFunction, Sqltrigger, SqlMethod, SqlUserDefinedType.. and more as options. You may have understand what this class is however let me describe it more. In this class we can write different methods as we write in normal class. The attribute on method helps compiler to identify that whether this method is a stored procedure or a function or a user defined type. So if you are creating a trigger you need to set the attribute to [Microsoft.SqlServer.Server.SqlTrigger].

       I have created a demo table “Employee” in my database and created a sp to insert a record in table. I know that using CLR stored procedure for insert , delete and update when you not have any complex logic before performing above operation is not advisable, however to keep the example simple I have used simple Insert example. Below code shows Insert SP,

   1: using System;
   2: using System.Data;
   3: using System.Data.SqlClient;
   4: using System.Data.SqlTypes;
   5: using Microsoft.SqlServer.Server;
   6:  
   7:  
   8: public partial class StoredProcedures
   9: {
  10:     [Microsoft.SqlServer.Server.SqlProcedure]
  11:     public static int sp_InsertEmployee(string FirstName, string LastName, string City)
  12:     {
  13:         using (SqlConnection cnn = new SqlConnection("context connection = true"))
  14:         {
  15:             cnn.Open();
  16:             SqlCommand cmd = new SqlCommand("Insert into Employee values ('" + FirstName + "','" + LastName + "','" + City + "')", cnn);
  17:             int intRowsAffetced = (int)cmd.ExecuteNonQuery();
  18:             return intRowsAffetced;
  19:         }
  20:     }
  21: };

Fig –  (4) Simple Insert SP

         We have used “context connection = true”. It means this CLR stored procedure will be executed in same connection by which the data access layer code has called this sp. Now, Compile the code, if it compiles successfully right click on project in solution explorer and click on Deploy. This will create a assembly in SQL server and creates a clr stored procedure automatically. You can do this task manually also. (If you have used class library as project type instead of SQL Server Project you have to follow steps mentioned below. If you have used SQL Server Project do ignore following 4 steps.) To do this follow steps,

(1) Create a signed assembly from you code. To do this, right click on project and click “properties”.  Select the “Sign the assembly” checkbox and select “<New>” from dropdown list.  Give a appropriate name to key and that’s it. Now when you compile the project it will generate signed assembly.

Fig – (5) Signing Assembly (Generating strong name for assembly)

(2) Enable CLR integration for selected database. To do this write following commands in query analyzer,

   1: sp_configure 'clr enabled',1
   2: GO
   3: reconfigure
   4: GO
   5: sp_configure 'clr enabled'

Fig – (6) Enabling CLR Integration

(3)  Create assembly in SQL Server.

   1: CREATE ASSEMBLY
   2:     LearnCLRIntegration -- Assembly name, you can write which you want
   3: FROM
   4:     'C:\LearnCLRIntegration.dll'  -- write appropriate path and DLL name
   5: WITH PERMISSION_SET = SAFE
   6: Go

Fig – (7) Create assembly in SQL Server

      There are three modes for Permission Set: SAFE, UNSAFE, EXTERNAL_ACCESS; SAFE – DLL can access only local resources (on same machine), EXTERNAL_ACCESS – DLL can access any resource on network and same machine. In both case it checks ACL for resource. UNSAFE – DLL can access anything without restriction. Choose appropriate permission set for your dll.

(4) Create a stored procedure from assembly,

   1: CREATE PROC clrsp_InsertEmployee
   2: (
   3: @FirstName varchar(50),
   4: @LastName varchar(50),
   5: @City varchar(50)
   6: )
   7: AS
   8: EXTERNAL NAME LearnCLRIntegration.StoredProcedures.sp_InsertEmployee -- write name as [assemblyName].[Namesace.ClassName].[FunctionName]
   9: Go

Fig – (8) Creating a stored procedure.

        Here you can see your DLL and stored procedure in SQL server as shown below,

Fig – (9) CLR stored procedure and assembly in SQL Server.

       You can use this SP as normal stored procedure in code or in query analyzer.  Below is the code that uses this SP for insert,

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Text;
   4: using Microsoft.Practices.EnterpriseLibrary.Data;
   5: using Microsoft.Practices.EnterpriseLibrary.Common;
   6: using System.Data.Common;
   7: using System.Data;
   8:  
   9: namespace DAL
  10: {
  11:     public static class EmployeeManagement
  12:     {
  13:         public static int InsertEmployee(string FirstName,string LastName,string City)
  14:         {
  15:             Database db = DatabaseFactory.CreateDatabase("ConnectionStr");
  16:             DbCommand cmd = db.GetStoredProcCommand("sp_InsertEmployee");
  17:             db.AddInParameter(cmd, "FirstName", DbType.AnsiString, FirstName);
  18:             db.AddInParameter(cmd, "LastName", DbType.AnsiString, LastName);
  19:             db.AddInParameter(cmd, "City", DbType.AnsiString, City);
  20:  
  21:             int intRetValue = (int)db.ExecuteNonQuery(cmd);
  22:  
  23:             return intRetValue;
  24:         }
  25:
  26:
  27:     }
  28: }

 Fig – (10) Code to use CLR stored procedure in Data Access Layer

Conclusion

         CLR stored procedures can not be used as replacement of T-SQL statements. Execution of normal T-SQL statement is much faster than CLR Stored Procedure. We can use CLR Stored Procedure to avoid cursors and complex computation.

Happy Programming !!!

Read Full Post »

Older Posts »