7/22/2011

Beginning SQL Server Reporting Services Part 1

Ref: Steve Joubert

Building and deploying basic reports

If ever there was job for "real" developers to shuffle to their juniors, it is building reports. It's not real development anyway; it's more like glorified formatting. Besides, the esoteric tools that you use to build reports try to provide an abstraction layer, which often prevents you from having any real control over the report. I've heard all these arguments before. If this sounds like a conversation you've had by the water cooler, then I invite you to take a closer look at SQL Server 2005 Reporting Services (SSRS).
SSRS 2005 is the latest version of SQL Reporting Services, and ships with all versions of SQL Server 2005. SSRS allows you to quickly and easily create reports from multiple database sources. The finished reports can be presented directly from the reporting services website, or they can be displayed in your web- or Windows-based applications. Reports can be exported to multiple formats, including comma delimited text, XML, portable document format (pdf) and Microsoft Excel.
This article is the first of four parts, which will provide in-depth coverage of SQL Server 2005 Reporting Services:
  • Part 1 covers the basics of the SSRS. It demonstrates how to build quick, simple reports and will familiarize you with the basic Report Designer environment
  • Part 2 will cover use of custom functions, aggregate functions, sub-reporting, the matrix control, drill-downs, and sorting.
  • Part 3 will take an in-depth look at the charting control
  • Part 4 digs into the actual Report Definition Language (RDL) and the new Report Builder tool.

Installing and configuring Reporting Services

After much debate, we decided that full installation and configuration details were outside the scope of an article focused on how to build basic reports using SSRS, especially as there are already several online resources that treat this area in detail. See, for example:
http://msdn2.microsoft.com/en-us/library/ms143736.aspx
and
http://www.awprofessional.com/articles/article.asp?p=357694&seqNum=1&rl=1
Well worth reviewing are the details in the latter on the need to install SSL on any machine hosting SSRS.
---Editor's installation notes---In order to test the reports in this article, I went through a single-machine installation on Windows XP (meaning that SQL Server 2005, Reporting Services, and much more, are all installed on my poor laptop). Since I didn't install SSRS when I installed SQL Server 2005 (I didn't have IIS installed at the time), I had to first install IIS 5.1, and then Reporting Services (from the SS2005 disks). I then jumped immediately into Reporting Services Configuration Manager tool (All Programs ¬ SQL Server 2005 ¬ Configuration tools). The left panel acts as a sort of checklist of items to configure:

All went well until the Database Setup. Because I had not installed SSRS at the same time that I installed SQL Server, the ReportServer and ReportServerTempDB were not created by default. These databases hold all the report definitions and reporting server configuration information. Connecting to SQL Server using Service Credentials, the databases appeared to be created, but I received an error suggesting that I didn't have permissions to perform the requested task, and a red cross remained next to the Database Setup icon. This had me stumped for a while – eventually I appeared to solve it by hopping to the Server Status section, stopping the Report Server, opening SSMS and deleting both the ReportServer and ReportServerTempDB databases, and then restarting the Report Server and trying again! Even though I swear this didn't work the first time I tried it, it seemed to do the trick the second time (while I was on the phone moaning to Steve that I couldn't get it to work!). However, I'm still not clear why I had the problem in the first place – or why it suddenly went away.
This wasn't quite the end of my problems. Installing SSRS creates two new virtual directories under the default website on IIS. By default, they are named Reports and ReportServer. The ReportServer site hosts a web service for running and managing reports. The Reports site allows you upload reports from a browser and run reports over the web. When I tried to navigate to http://localhost/ReportServer I received the following error: "Failed to access IIS metabase". Fortunately, the information on the error page is quite useful (for a change) and this, coupled with a quick Google search, led me to grant access to the metabase to the ASPNET user account by executing the following from the directory housing the aspnet_regiis executable (WINDOWS\Microsoft.NET\Framework\v2.0.50727, in my case):
spnet_regiis -ga ASPNET
This did the trick, and I was up and running. I received some raised eyebrows here when I proposed to install SSRS. It made my long-suffering sys admin team particularly nervous. The 2000 version of SSRS seems to have a very bad reputation among the Red Gate team, both as a performance nightmare, and in one case for "completely annihilating" a developer's machine. However, the above slight quirks aside, the SSRS 2005 experience seems pretty smooth and I've had no real performance, or other, issues. So far.
-----End of Editor's note----
Once you've completed the installation and configuration process, the first thing to do is download the code file for this article (see the Code Download link in the speech bubble to the right of the article title). The code file contains a sample Visual Studio project and a SQL Script for creating the ReportDemo database. You will need this database if you want to follow the examples in this series of articles so go ahead and create the database using the ReportingDemoDatabaseScript.sql script or, alternatively, by restoring the provided ReportingDemo.bak file.
If you are using SQL Server Authentication on your SQL Server you will also need to set up a login with permissions to the ReportDemo database (for the examples, I set up a login called DemoUser as a DBO on my ReportDemo database).

Using the Report Wizard

There are two ways to create SSRS Reports. You can build the report manually, or you can use the Report Wizard to give yourself a head start. For this first report, we are going to take advantage of the wizard. Start a new Business Intelligence project in Visual Studio 2005. Then, from the menu, select Project > Add New Item. Select the Report Wizard option and call the file "FirstReportWZ.rdl". Click Add. Click Next on the Welcome screen and this will bring you to the Select the Data Source screen:

Select the New data source radio button and give the data source a name. Select Microsoft SQL Server as the type.
Note:Use of the Shared data source option is actually a better option in most cases but, for the sake of this example, we will just create a new data source. We're going to set up a shared data source later in this article.
Click the Edit button to bring up the Connection Properties dialog:

Enter or select a server name. The default is to log on using Windows Authentication. If you are using SQL Server Authentication, choose that setting, and enter the username and password. Finally, select a database, in this case ReportingDemo. Make sure you test the connection before you click OK.
Next up is the Design the Query screen. You can use the Query Builder by clicking the button at the top left, but in this case simply enter "Select * From Customer" into the Query string text box and click Next. On the Select the Report Type simply select the type you prefer (tabular or matrix) and hit Next.
This brings up the Design the Table screen:

Select State in the Available fields box and click the Group button. This will group the data in the result set by State. Select Next. On the Choose the Table Layout page, select the Stepped option and check the Enable Drilldown checkbox. On the next screen, choose a style for your report (I chose Ocean) and click Next.
This brings up the final screen, Completing the Wizard:

It shows a summary of your report options, and gives you an opportunity to rename the report and to preview it. Click Finish to end the wizard.
You should be shown the report in the standard Report Designer:

There are three tabs: Data, Layout and Preview. You should be on the Layout tab. Click on the Preview tab to view the report. Since this report doesn't take any arguments, it will run as soon as you click on the tab.

Use the +/- symbols next to the State abbreviations to expand and collapse the grouping of the report.

Manual report creation

The previous section, while perhaps overly simplistic, does show you how to get a report up and running with zero code and zero property setting. Obviously, such reports will not meet most development requirements, but do not discount this option as a starting point for more complicated reports. Once you've created a report with the Report Wizard, you are free to make any modifications to it.
In this section, we are going to create a more realistic report from scratch, including how to create and use a shared data source object, stored procedures, and how to format your report, set report properties and use report parameters.

Creating a shared data source

Before we start the report, we are going to build a shared data source i.e. a data source that is common to, and can be used by, all of the reports on a reporting server. While each report can contain its own connection information, it is good practice to use shared data sources, as it will save you a lot time and headaches. This way, you only have to set the connection information once. For example, let's say your company has Development, Test and Production environments. If you put the connection information into each report, you will have to change it each time when you publish to Development, Test and Production. If you use a shared data source, you still have to set up a data source object for each of three environments, but you can simply publish the report to each environment, and they will automatically use the connection information associated with that environment.
From the menu select Project > Add New Item > Select Data Source. On the General tab, call the data source "ReportsDB". Leave the Type as Microsoft SQL Server. Click the Edit button on the right, and enter the connection information for Reporting Demo, as before. Click OK on the Shared Data Source screen and the data source is done.

Add a new report

From the menu select Project > Add New Item. Select Report and name it "FirstReportMan.rdl". A new report will be added to the project, and the Report Designer will open at the Data tab. At this point, let's take a closer look at the Report Designer tool. At the top of the Report Designer window are three tabs: Data, Layout and Preview. The Data tab is used to build data sources for your report. The Layout tab is the physical report designer where you set up the header, the footer and the data presentation of the report. The Preview tab allows you to actually run the report from Visual Studio 2005, without having to publish it to a report server first. If your report takes parameters, the Preview tab will ask you to fill them out before it runs the report.
The first thing we need to do is get data into our report. At the top of the Data tab choose <New Dataset…> from the dropdown list:

The Dataset dialog opens:

Name the dataset "ReportData", and select the ReportsDB data source from the dropdown. Select StoredProcedure as the command type, and enter "spr_CustomerSelectAll" in the query string box. Click OK to close the dialog.
Note:
spr_CustomerSelectAll is a very simple, parameter-less stored procedure that selects all of the columns from the Customer table. The source code is included in the ReportingDemoDatabaseScript.sql script with the code download.
Test the dataset by clicking on the big red exclamation point at the top of the report designer. This executes the query and displays the results. You can repeat these steps if you wish to add multiple datasets to your report.

Setting up the report display

Next, switch to the Layout tab. This is where you actually build the report display. Start by dragging a table from the Toolbox, onto the Body section of the report. By default, the table shows a header row at the top, a detail row in the middle and a footer row at the bottom. You can add additional columns to the table by right-clicking on one of the columns and selecting one of the two Insert Column options.
Click on the Datasets tab under Toolbox on the left-hand side of the Visual Studio environment. You should see the ReportData dataset. Expand it, select FirstName and drag it to the first cell of the body row of the table. This will display the First Name field in the first column. Now put the LastName in the second column, and the CustomerStatus in the third:

Note that, when you drag the column FirstName into the body row of the table, SSRS make a guess as to what to call the row. It calls it "First Name". You can click on the Preview tab to view the report.

Adding formatting

OK, so we have a basic, very plain, report. Let's add some formatting to make it look good. Let's add the DateOfBirth column to the table. You can expand and shrink the size of the columns by highlighting and dragging:

If you wish to get rid of the footer row of the table and then click on any field in the table. You will see a grey box surround the table. Right-click on the icon at the beginning of the body row and then click the Table Footer option to deselect it.
The table header is next. To format all the cells in the header in the same way, click and drag over all the cells to select them. Open the Properties window and set background color, font, and so on.

Note, however, that if you wish to change the justification of the text or the size, then you do so using the main menu at the top, not via the properties window. Again, you can click on the Preview tab to view the report.

Add a report header

The table already has a header, but the report can also have a header and footer. Report headers and footers appear on every page of the report. Put the Report Designer in Layout mode and select Report > Page Header from the menu. A new band labeled Page Header appears on the report above the body. Drag a text box onto the header and click directly on it. Type "My First Report", not in the Properties window, but right on the control.

To adjust the text style and size of your heading, highlight the text box and use the option from the top menu.

Formatting

Each field can have formatting. Let's deal with that ugly Date of Birth field. The time information is superfluous, so let's format the date properly. Right-click on the cell that contains the date of birth, and choose Properties. Next, select the Format tab.

Click on the second button (labeled "…") to the right of the Format code field. When the dialog opens, use the standard options. Select Date in the list on the left, then choose the sample date format you want on the right. Click OK to close the dialog.

Click OK to close the Properties window and then click on the Preview tab to view the report.

Setting report properties

To access the report properties, you need to be on the Layout tab of the Report Designer. When you click on this tab, a new menu item, Report, activates. This menu gives you options for turning on and off the report header and footer sections (as we have seen), adding embedded images, setting report properties, and setting report parameters.
Setting up the report print settings is not intuitive, compared to other products. In the report Layout tab you see your report with a ruler across the top. That ruler is set up in inches. A standard sheet of paper is 8.5 x 11 inches. The default setting in SSRS is to have a 1-inch margin all the way around the content area. So, at 8.5 inches wide with a 1-inch margin on the left and another on the right, you have 6.5 inches for content. Any more, and the content beyond the 6.5 inches will spill over onto a second sheet of paper when printed. It will not automatically shift to Landscape.
To get Landscape reports, you have to make the proper report settings. Navigate to the Layout tab of the Report Designer. From the Report menu select Report Properties. Switch to the Layout tab of the dialog box. To switch to Landscape printing, you need to change Page width to 11in and the Page height to 8.5in.

On the same Layout tab, you can also get up your report to display the data in multiple columns, and you can control the margins. By default, all the margins are set at 1 inch. Remember, if your report width, plus the right and left margins, is greater than the width of the printer, you will get spill-over when you print out your report.

Using parameters

There are two ways to add parameters to your reports. The first is to use parameters in the queries in your data sources. The second is to set up parameters through the Report Parameters dialog box. We will do both.
Query parameters
First, we will set up parameters using a data source query. Navigate to the Data tab, and click the "…" button right next the Dataset dropdown box. The Dataset dialog box opens and allows you to edit the query for the dataset. Change the Query string from "spr_CustomerSelectAll" to "spr_CustomerSelectByState".
Note:spr_CustomerSelectByState accepts a parameter called StateCD that allows us to filter the data from the Customer table by State. Again, the source code is included in the ReportingDemoDatabaseScript.sql script with the code download.
Click OK and then run the query by clicking the red exclamation point (!) on the Data tab toolbar. You will be prompted to enter a parameter value for StateCD (the State code). Enter "CA" and click OK. The query should return all the customers that live in California.
Switch to the Preview tab. Instead of the report just running, there should be a place for you to enter a value for the "StateCD" and run the report. Enter "CA" and click the View Report button. You should see your report filtered by state.
To edit the parameters, or to add new ones, switch to the Layout tab of the Report Designer and open the Report Parameters dialog from the Report menu. First, we are going to make the "State code" prompt a little more friendly. Select StateCD in the Parameters list box then, in the Parameters Properties box, change the prompt to read "State". In the Available values section enter "California" and "CA" on the first line. Enter "Louisiana" and "LA" on the second line.

This will make the prompt for "State value" into a dropdown. You can also build additional datasets into your report, and use the values in those datasets as criteria for dropdowns.
Report parameters
Now let's add a parameter that is not used in a query. Click the Add button in the Report Parameters dialog from the Report menu. Give the new parameter the name "ReportTitle". Its Data type should be String. Set the Prompt to "Report Title". Click OK and close the dialog box.
Drag a new text box onto the report header area. Right-click on it and choose the Expression option. In the Edit Expression dialog select Parameters. Double-click on the ReportTitle parameter. This text box will now display the value you pass to the Report Title parameter.

Switch to the Preview tab and try it out.

Publishing your reports

Up to now, you have been running your reports in the Visual Studio 2005 environment but, to make them useful, you must publish them to a report server. The easiest way to do this is to have Visual Studio publish your reports.
Start by right-clicking on Project in the Project Explorer and choose Properties.

Set TargetServerURL to the URL of your report server. Use the TargetReportFolder property to set up a folder for your reports. If the folder does not exist, the Publisher will create it for you. The other key thing to pay attention to here is the OverwriteDataSources property. When this property is set to "True", it will automatically copy over all your data source objects when you publish. When set to "False", it will copy any new data source objects, but it will not overwrite existing ones. This is important when dealing with development, test and production servers. You can publish a set of data source objects to each server, pointed at the correct database, and never have to worry about what database your reports are hitting in each environment.
From the Build menu select Deploy Solution. This will publish the project to the selected folder on your report server. You can also deploy individual reports by right-clicking on the file in the Solution explorer and selecting Deploy.
Once your report has been published, you can access and run it on your server through the browser at http://<servername>/<reportservername>. From the Home page, you should be able to find the folder you published to, with the reports in it. Select a report to run. At the top of the page you can enter any values for report parameters, and then run the report. From here, you can also print or export the report.

Combine and minifier javascripts file using Microsoft AJAX Minifier library

Loading javascript/ scc files in your web app have some issue:
- Amount of data
- Sequence of files, some time process is broken because one javascript file is not loaded
Using AJAX Minifier library help us solve them:



public class JavascriptHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string file = context.Request["file"];
            var settings = new CodeSettings
            {
                MinifyCode = true,
                OutputMode = OutputMode.SingleLine,
                CollapseToLiteral = true,
                CombineDuplicateLiterals = true,
                EvalTreatment = EvalTreatment.MakeAllSafe,
                IndentSize = 10000,
                InlineSafeStrings = true,
                LocalRenaming = LocalRenaming.CrunchAll,
                MacSafariQuirks = true,
                PreserveFunctionNames = true,
                RemoveFunctionExpressionNames = true,
                RemoveUnneededCode = true,
                StripDebugStatements = true
            };
            var min = new Minifier();
            var path = context.Request.MapPath("/Scripts/" + file);
            StreamReader sr = new StreamReader(path);
            var minifieredData = min.MinifyJavaScript(sr.ReadToEnd());
            context.Response.ContentType = "text/javascript";
            context.Response.Write(minifieredData);
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
 
In client side, we just add script reference to our system to load javascript files.

<script src="JavascriptHandler.ashx?file=IntegerHelper.js" type="text/javascript"></script>


We can also use AJAX Minifier library to get css files.

7/21/2011

Some notes when write javascript

Avoid Using Eval() Function and With Statement

The eval() function executes a piece of code supplied as a string. For example, consider the eval() function call below:
eval("var myVar=100;alert(myVar);");
There is no way for the minifier tool to convert this string literal into a compact form. As a result the call will not be compacted. Similarly, using with statement also hampers the minification process.
var myVar = 100;
with(window) {
    alert(myVar);
} 
Since the minifier tool won't know whether myVar refers to the variable or to a member of window object the entire block will not be minified.

Try to Avoid Global Variables and Functions

Global variables and functions are never minified because there is a chance that they are used from some other part of the website. Consider the set of global variables and function below:
function MainFunction() {
    HelperFunction1();
    HelperFunction2();
}

function HelperFunction1() {
    alert("inside helper function 1");
}

function HelperFunction2() {
    alert("inside helper function 2");
}
Here, the functions HelperFunction1() and HelperFunction2() are used only by MainFunction() and are not used anywhere else. However, since they are in global scope, the minifier tool will not compact them. You can overcome this problem by modifying the code like this:
function MainFunction() {
    var HelperFunction1=function(){
        alert("inside helper function 1");
    }

    var HelperFunction2=function() {
        alert("inside helper function 2");
    }
    HelperFunction1();
    HelperFunction2();
}
Now, the minifier tool will compact both of the helper functions to smaller names and calls to them will also be substituted accordingly.

Use Shortcuts for Window and Document Objects

It is very common to use window and document JavaScript objects in the code. If you refer them as "window" and "document" at each and every place then you will be wasting bytes every time. Instead you can use them as shown below:
var w = window;
var d = document;
function MainFunction() {
    d.getElementById("Div1");
    w.setInterval(myCode, 1000);
}
You can even wrap frequently used methods of document object (such as getElementById) in a separate function like this:
function Get(id)
{
    return d.getElementById(id);
}
Then use the Get() function at all the places where you would have used getElementById() method.
function DoTest() {
 alert(Get("abc").id);
}

Microsoft Ajax Minifier

Using the Microsoft Ajax Minifier from the Command Line

After you install the Microsoft Ajax Minifier, you can use the tool from the command line. Open the Microsoft Ajax Minifier Command Prompt from the Microsoft Ajax Minifier program group. Next, enter the name of an input file and the name of an output file like this:

ajaxmin test.js -o test.min.js

Image

The Microsoft Ajax Minifier will report how much it was able to minify the file (for example, 43%).

You also can use the Microsoft Ajax Minifier to minify Cascading Style Sheet files. You use the same syntax:

ajaxmin test.css -o test.min.css

Using the Microsoft Ajax Minifier as a Build Task

You can integrate the Microsoft Ajax Minifier into your Visual Studio Build process. Every time you perform a build in a Visual Studio ASP.NET project, you can minify all of your JavaScript and Cascading Style Sheet files automatically.

You can use the Ajax Minifier with both ASP.NET Web Forms and ASP.NET MVC Web Application Projects (WAPs). However, you cannot use the minifier with ASP.NET Web Forms Websites.

Follow these steps:

1. Within Visual Studio, select the menu option Tools, Options, Projects and Solutions. Check the checkbox labeled Always show solution

Image

2. Within Visual Studio, right-click your project in the Solution Explorer window and select the menu option Unload Project

Image

3. Select the menu option Edit project name

4. Add the following code immediately above the closing <project> tag:

  1. <Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />  
  2. <Target Name="AfterBuild">  
  3. <ItemGroup>  
  4.   <JS Include="**\*.js" Exclude="**\*.min.js;Scripts\*.js" />  
  5. </ItemGroup>  
  6. <ItemGroup>  
  7.   <CSS Include="**\*.css" Exclude="**\*.min.css" />  
  8. </ItemGroup>  
  9. <AjaxMin   
  10.     JsSourceFiles="@(JS)"  JsSourceExtensionPattern="\.js$" JsTargetExtension=".min.js"  
  11.     CssSourceFiles="@(CSS)" CssSourceExtensionPattern="\.css$" CssTargetExtension=".min.css"  />  
  12. </Target>  

This code imports a custom MSBuild task named ajaxmin. The ajaxmin task is used to minify all of the JavaScript and CSS files contained in the project automatically. All JavaScript files are renamed with the extension .min.js and all CSS files are renamed with the extension .min.css.

5. Right-click your project in the Solution Explorer window and select the menu option Reload Project

After you complete these steps, all of the CSS and JavaScript files in your project will be minified whenever you do a build automatically. The minified files will not appear in the Solution Explorer window. To see the minified files, you must select the menu option Project, Show All Files.

Using the Microsoft Ajax Minifier with Source Control

The Microsoft Ajax Minifier generates the minified JavaScript and CSS files as the output of the build process. For this reason, we recommend that you handle the minified files in exactly the same way as you would handle the assemblies generated by the build process. In particular, we recommend that you do not include the minified files in your Visual Studio project and that you do not check the minified files into source control.

If you include the minified files in your project, and you use source control, then you will encounter problems. When files are checked out of source control, they are checked out with their read-only attributes set. If you attempt to do a build, the Microsoft Ajax Minifier will generate an error when it attempts to write to a read-only file.

Running Microsoft Ajax Minifier Tool from Visual Studio

Microsoft Ajax Minifier is a command line tool. Rather than opening the command prompt every time and then invoking the commands manually, wouldn't it be nice if you integrated it with Visual Studio IDE itself? Luckily you can do so with simple steps.
Open Visual Studio and select "External Tools" from its Tools menu.
Visual Studio: External Tools
Figure 4: Visual Studio: External Tools
This will open a dialog as shown below:
Visual Studio External Tools Dialog Box
Figure 5: Visual Studio External Tools Dialog Box
Specify the tool title as "Microsoft Ajax Minifier." Set Command to point to ajaxmin.exe. Add arguments as shown below:
$(ItemFileName)$(ItemExt)  -out $(ItemFileName).min$(ItemExt) -clobber
The $(ItemFileName) represents the file name of the currently opened file in the Visual Studio IDE. The $(ItemExt) represents its extension. You can also pick these arguments from the arguments menu. Set initial directory to $(ItemDir) i.e. the same folder as the opened file. Finally. check the "Use Output Window" checkbox so that output messages will be displayed there and click on the OK button. The Microsoft Ajax Minifier tool will now be displayed on the Tools menu.
The Microsoft Ajax Minifier Tool
Figure 6: The Microsoft Ajax Minifier Tool
Open any JavaScript file and run the tool on it. A sample message emitted by the tool as seen in the Output Windows is shown below:
Microsoft Ajax Minifier Tool Output Window
(Full Size Image)
Figure 7: Microsoft Ajax Minifier Tool Output Window
In order to see the minified file you will need to refresh the website in the Solution Explorer

7/20/2011

Enabling Gzip and Deflate HTTP Compression in ASP.NET pages

Ref: Faisal Khan
If your ASP.NET web application doesn't already contain a Global.asax file, create a new one using notepad. Then insert following code in it:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>


<script runat="server">
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
    HttpApplication app = sender as HttpApplication;
    string acceptEncoding = app.Request.Headers["Accept-Encoding"];
    Stream prevUncompressedStream = app.Response.Filter;

    if (!(app.Context.CurrentHandler is Page) ||
        app.Request["HTTP_X_MICROSOFTAJAX"] != null)
        return;

    if (acceptEncoding == null || acceptEncoding.Length == 0)
        return;

    acceptEncoding = acceptEncoding.ToLower();

    if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
    {
        // defalte
        app.Response.Filter = new DeflateStream(prevUncompressedStream,
            CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "deflate");
    } else if (acceptEncoding.Contains("gzip"))
    {
        // gzip
        app.Response.Filter = new GZipStream(prevUncompressedStream,
            CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");
    }
}
</script>

7/19/2011

Importing data from text file to specific columns using BULK INSERT (Dinesh Asanka)

Ref: Dinesh Asanka
Bulk insert is much faster than using other techniques such as  SSIS. However, when you are using bulk insert you can’t insert to specific columns. If, for example, there are five columns in a table you should have five values for each record in the text file you are importing from.
This is an issue when you are expecting default values to be inserted into tables.
Let us say you have table as below:

In this table, you are expecting ID, Status and CreatedDate to be updated automatically, so your text file may only have   FirstName  LastName  values as below:
Dinesh,Asanka
Saman,Liyanage
Ruwan,Silva
Susantha,Bathige
Jude,Peires
Sanjeewa,Jayawickrama
If you use bulk insert to this table like follows,

You will be returned an error:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (ID).
To avoid this you will need to create a view with the columns you are expecting to fill and use bulk insert against it.


If you check the table now, you will see table with values in the text file and the default values.






7/18/2011

Are You Using SSMS effectively ? (By Dinesh Asanka)

SQL Server Management Studio is an essential tool for DBAs and developers. But are you using it effectively? In this article, I will try examine a few tips and techniques which could well boost your efficiency using SSMS.

Object Filtering

The below screen is probably familiar to most DBAs – it lists all tables under a database. If you want to check something on the Address table, you need search the entire list. Things will be much more difficult if you have multiple schemas, since table is listed according to the order of schemas.

.

You can filter the objects, by following given steps.

First, right-click the Tables node and select Filter > Filter Settings:



Then you will receive below dialog enabling you to filter by any of four parameters – Name, Schema, Owner and Creation Date:

The below are are the operator and parameters you can use for filtering.

Operator

Parameter

Name

Equals, Contains, Does not contain

Schema

Equals, Contains, Does not contain

Owner

Equals, Does not contain

CreationDate

Equals, Less than, Less than or equal, Greater than, Greater than or equal, Between, Not between,

In this example we will use Contains > Address for filtering:

If you set a filter as above, you will end up with the below screen.

As you can see that, your table list now consists only of tables which contain Address.

Object Information

As developer, you will need information on your SQL Server objects. For example, you may need a row count for tables. There are numerous DMVs you can use and if your tables are small, you can simply use T-SQL such as COUNT(*) – I don’t recommend though . However, SSMS can also be used to get those details.

In the main menu, select Object Server Explorer:

Right-click the header, and you will be shown information you can select such as Data Space Used, Index Space Used , row count etc. You will be shown a view like below where all the information you selected is tabulated.

Register Server

How do you login into SQL Servers? Are you entering servername, userid , password every time? This won’t be an easy task if you are managing more than 10 servers. If you can remember back to SQL Server 2000, you had a tool called Enterprise Manager in which you are required to register your server. So when you are logging in again, the saved user name and password will be used. With the introduced of SQL Server 2005, what happened to that nice little feature? It is still there folks!

You can access all the servers that are registered by selecting View > Registered Servers as shown below. To add new servers to a group, simply right-click the group you wish to add a server to and select New Server Registration.

This not only it saves your credentials, but you also will have the option of querying among all your servers.

Let us say you want to list out all the databases.

You can right click any node in the registered server window. In this example I right-click the Dev node in the registered servers and select new query, note the query window is slightly different from one you normal see.

Not only is the color of the footer bar pink but you can see there is a 2/2 label which means that you are connected to two server out of two available.

Let me execute:

SELECT * FROM sysdatabases

This has the following output:

Now you can see all the databases in both servers are listed here. Logins, servers are other things you can list out like this.

Template Explorer

Let us say you want write a DDL trigger but you do not remember the correct syntax for creating a DDL Trigger (which is different than a regular trigger).

You can use the Template Explorer to assist you in this. The Template Explorer launched by selecting View > Template Explorer. This provides a very comprehensive listing of T-SQL templates for common tasks.

If you double click the template you want , relevant template will be opened.

By clicking Shift+Ctrl+M, you will get the option of entering template parameters, so that those can be entered in once place.

You can create your own template with parameters using the following format.

In the above example, database_name is the parameter name, sysname is the data type and the adventureworks is the default value.

Short Cuts

There are a few task that you will most likely perform daily such as viewing table structures or viewing indexes. You can create customized short cuts for these tasks. Select Tools > Options > Keyboard and you will be taken to following window.

By way of example, when analyzing your table structure, indexes you could do this by going to the object explorer and expanding the table. However, this is time consuming since to obtain the table structure, index information you need to navigate several pages. Instead simply hit ALT + F1 and you will see all the relevant information for that particular table. Note that for this short cut might have an issue, if you are using not default schema (ex:dbo), for these cases you need your objects to be enclosed with quotes. ( ‘ HumanResources].[Employee]’).

Ref: http://www.sql-server-performance.com/2011/using-ssms-effectively/