Posts RSS Comments RSS 133 Posts and 258 Comments till now

Traversing Database Server using SQL SMO

SQL SMO (SQL Management Object) is a collection of assemblies that shipped together with SQL 2005. This collection of assemblies is all that you need to control your SQL Server. Be it SQL 2005, or SQL 2000, you can control/manipulate it programmatically using SQL SMO.

 

Since SQL SMO gave you the ability to treat the database elements such as Table, Database, Stored Procedure, and Trigger as an object, interacting with them should be relatively easy and practical. Additionally, you might want to check out this list of things that make SQL SMO exciting.

 

OK, lets get our hand dirty with the project. The first step would be importing the references into your project. If you use Visual Studio 2005, look for Microsoft.SqlServer.Smo in the list of .NET assembly when you open ‘Add References’ window.
If you already have MS SQL 2005 installed, you can find the DLLs in the SDK\Assemblies folder of your MS SQL 2005 installation folder.
If you don’t have MS SQL 2005 installed in your computer, you might want to download the Express edition HERE.

 

Next, you could use the following code as reference.

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Configuration;
using System.Data.SqlClient;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //Assuming that you include a Configuration file to your
            //project and set the key 'DataSource'
            //as the connection string
            SqlConnection conn = new SqlConnection(
                      ConfigurationManager.AppSettings["DataSource"]
            );
           //Instantiate the connection to the server
	   ServerConnection dbConn = new ServerConnection(conn);
	   //Instantiate the Database Server Object
	  Server dbServer = new Server(dbConn);			

          //Traverse the Database Objects
          foreach (Database db in dbServer.Databases)
          {
              if (db.IsAccessible)
              {
                  //traverse the Stored Procedure Objects
                  foreach (StoredProcedure sp in db.StoredProcedures)
                  {
                      foreach (string str in sp.Script())
                          Console.WriteLine(str);
                  }
                  //Traverse the Table Objects
                  foreach (Table tb in db.Tables)
                  {
                      foreach (string str in tb.Script())
                          Console.WriteLine(str);
                  }
                  //Traverse the View Objects
                  foreach (View vw in db.Views)
                  {
                      foreach (string str in vw.Script())
                          Console.WriteLine(str);
                  }
              }
          }
      }
  }
}

 

Make sure in your app.config you have the DataSource key. You can follow this template for the configuration file:



  
    
  

 

Have fun!

 

Prevent Error Caused By Null-Value in Your Stored Procedure

Consider you have a stored procedure that perform a SELECT operation for an object which is characterized by the ‘Start Date’ and ‘End Date’. Let’s assume we have the following TABLE:

Table Name: Events

Columns:
EventID int
EventName Varchar(64)
EventDesc Varchar(512)
EventStartDate DateTime
EventEndDate DateTime


And let’s assume that we have the following stored procedure:

 

CREATE PROCEDURE [dbo].[ListFilteredEvents]
	-- Add the parameters for the stored procedure here
	@StartDate datetime,
	@EndDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

        -- Insert statements for procedure here
	SELECT
		Events.EventID,
		Events.EventName,
		Events.EventDesc,
		Events.EventStartDate,
		Events.EventEndDate
	FROM
		Events
	WHERE
		Events.EventStartDate>= @StartDate AND
                Events.EventEndDate<= @EndDate
	ORDER BY
		Events.EventStartDate
END

 

Now what will happen if somehow the SP caller will pass blank value as the StartDate and/or EndDate? Error (Exception will be thrown) of course. If we have access to the source code of the application that execute this stored procedure, we could easily error-prevention at the application level. But if our access is only limited to database level, we could do the following:

 

CREATE PROCEDURE [dbo].[ListFilteredEvents]
	-- Add the parameters for the stored procedure here
	@StartDate datetime,
	@EndDate datetime
AS
BEGIN
   IF @StartDate IS NULL
   BEGIN
      -- Set it with the smallest value of DateTime data type
      SET @StartDate=CAST('1753-01-01' as DATETIME)
   END

   IF @EndDate IS NULL
   BEGIN
      -- Set it with the biggest value of DateTime data type
      SET @EndDate=CAST('9999-12-31' as DATETIME)
   END

   BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

        -- Insert statements for procedure here
	SELECT
		Events.EventID,
		Events.EventName,
		Events.EventDesc,
		Events.EventStartDate,
		Events.EventEndDate
	FROM
		Events
	WHERE
		Events.EventStartDate>= @StartDate AND
                Events.EventEndDate<= @EndDate
	ORDER BY
		Events.EventStartDate
   END
END

 

This way we could prevent Error/Exception being thrown whenever a blank value is passed into the stored procedure.

 

Important Update: Saturday, 21 April 2007 13.43 PM — Thanks for Bro MCA for pointing out a better solution =)

 

CREATE PROCEDURE [dbo].[ListFilteredEvents]
	-- Add the parameters for the stored procedure here
	-- Set it with the smallest value of DateTime data type
        @StartDate DateTime='1753-01-01',
	-- Set it with the biggest value of DateTime data type
        @EndDate DateTime='9999-12-31'
AS
BEGIN
   -- SET NOCOUNT ON added to prevent extra result sets from
   -- interfering with SELECT statements.
   SET NOCOUNT ON;

   -- Insert statements for procedure here
   SELECT
	Events.EventID,
	Events.EventName,
	Events.EventDesc,
	Events.EventStartDate,
	Events.EventEndDate
   FROM
	Events
   WHERE
	Events.EventStartDate>= @StartDate AND
        Events.EventEndDate<= @EndDate
    ORDER BY
    Events.EventStartDate
END

How to Install DotNetNuke

Apparently installing DotNetNuke is quite tricky. I did make a few mistakes which wasted a few minutes. So hopefully this post will save you from hassle.

  1. Get your Internet Information Server (IIS) up and running
    IIS is by default available on Windows 2000 all version, Windows XP Professional, Windows Server 2003. If you have Windows XP Home Edition, don’t worry. This hack should help to get IIS installed on Windows XP Home Edition. To confirm your installation click this HERE.
  2. Install .NET Framework 2.0
    Get your .NET Framework 2.0 HERE. The trick is always to get .NET Framework installed after your IIS confirmed up and running. You can’t do it the other way round. For most Windows XP installation, usually .NET Framework is already installed by default. If you happen to have such condition, you need to uninstall your .NET Framework, confirm that your IIS is up and running and then you proceed to install .NET Framework.
  3. Download DotNetNuke
    Although I recommended .NET Framework 2.0 at step 2, DotNetNuke older version is running on .NET Framework 1.1. So if you haven’t upgrade your .NET Framework to 2.0 and you don’t have intention to do so, download the DotNetNuke version 3.x. Otherwise, download version 4.x. The download page is HERE.
  4. Setup the Folder
    Extract the archive you download in Step 3. In this example we will assume the installation folder is C:\DotNetNuke. Right-click on C:\DotNetNuke folder, click Properties. On the General tab, make sure the Read-Only checkbox is not ticked. On the Security tab, add user “ASPNET” and give it Full Control access rights. You might want to add user “IUSER_YOURCOMPUTERNAME” (the IIS guest account) and give it non-Write access rights.
  5. Setup the Virtual Directory

    Open the IIS Management Console. You could do it by Start-Run-type “C:\Windows\System32\inetserv\iis.msc“-OK, or by Start-Run-type “compmgmt.msc“-OK continued by browsing to the IIS section. Right-click on the Default Web Site, New -> Virtual Directory. A wizard window will show up, click Next. Put DotNetNuke in the Alias text box, click Next. Browse to “C:\DotNetNuke”, click Next. Tick Read and Run Scripts only, click Next. Click Finish.
  6. Install Database
    Although DotNetNuke supports not only MS SQL Database, I have yet to research them. In this opportunity, I will only discuss about MS SQL. Hopefully someday I will have time to test DotNetNuke installation with other type of Databases and report it there. Okay, first you need to download your copy of MS SQL Express Edition. You can downloaded it HERE.
  7. Setup Database

    Open your SQL Server Management Studio (Start -> All Programs -> Microsof SQL Server 2005 -> SQL Server Management Studio). Click Connect. Above Database, Right-click -> New Database. Give the database a name, in this case we will name it MyDNN and click OK.


    Go to Security -> Logins. Above Logins, Right-click -> New Login. Type the Login Name –we will call it myDNNuser and then change the radio-button into SQL Server Authentication, and then type the password and confirm it, and then select the Default Database (i.e. MyDNN), and finally click OK.


    Go back to the MyDNN Database -> Security -> MyDNNuser -> Right-click -> Properties. Make sure db_owner on the “Schemas owned by this user is ticked”

  8. Edit Configuration File
    On the folder “C:\DotNetNuke” you will find web.config, edit it. If you could not find web.config, rename release.config into web.config. Look for a tag called <connectionStrings>. Inside it, comment the first child tag and uncomment the second one. Make sure you put the correct value in that tag. (i.e. value=”Server=YOUR_ComputerName\SQLEXPRESS; Database=myDNN; uid=myDNNuser; pwd=the_password;”). Do the same on the other tag called <appSettings>

After this you need to point your browser to “http://localhost/DotNetNuke/Install/install.aspx”. The installation should be automatic. Problems? Critics? Suggestions? Just drop your opinion on the comments. :-)

 

MS-SQL Stored Procedure for Absolute Beginner, Part 1

Currently I am reading a book about MS SQL Stored Procedure. I need to read the book as an anticipation that i will be accepted to an Insurance Company. Just to make sure my brain is not rusty :-P. I believe in-order to understand this guide, you need to know the basic Data Creation and Data Modification commands in T-SQL. I will use this posting to share with you what i *roughly* get from the book :)

1. What is Stored Procedure?

Stored procedure is a collection of queries/commands encapsulated in a function stored in the database server. The function may receive parameters which later can be used as the paremeters of the queries/commands. More definition.

2. Why Stored Procedure (SP) is useful?

Because SP will encapsulated your queries/commands into a parameterized queries/data definitions/data modifications. Thus you can standardize the exchange of information between the database server and its users. At the same time you will reduce the debugging-time on Application development since all the business logic are stored in the database. SP also able to help you maintaining security by classifying which users are permitted and which users prohibited to call the Stored Procedures.

3. Why we need Stored Procedure (SP) ?

Because we want to achieve result mentioned on number 2. We can achieve this by replacing the Stored Procedure as a library of functions stored outside the database server. But it will hinder the flexibility of type of Application that using the same business logic. For example, the current business application is using Web-based interface; If we want to create a Desktop-based/Smart Client Application we will be using more time to translate the business logic into different programming language/framework. We also will have major headache if we need to upgrade the Application but not the Business Logic.

4. Why we DON’T need Stored Procedure (SP) ?

Because SP is less powerful compared to the programming language that we use on the Web Application/Desktop Application/Smart Client. It also possible that we will locked into only one RDBMS vendor. Thus reducing our flexibility in managing IT budget.

5. When a Stored Procedure is suited Us best?

When you are confident that the current RDBMS will be deployed in your organization long enough compared to the time to develop the stored procedure. Extending the application into multiple platform/programming language is mentioned in your Application’s Development Roadmap.

Close
E-mail It
Socialized through Gregarious 42