DCSIMG
May 2007 - Posts - Maor's Blog

May 2007 - Posts

Disabling Triggers To Support Data Generation With DB Dude

When deploying test data to database (such as insert statements script that executed at the Post Deployment Script into your sandbox database) that has triggers, you need that the triggers will be disabled before generating test data and then re-enabled after the data has been appropriately generated.

I wrote two scripts for this issue: DisableTriggers.sql , EnableTriggers.sql .

Execute this T-Sql before deploying test data:

IF EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'#AllTriggers') AND type in (N 'U'))
DROP TABLE #AllTriggers


--Getting all trigger names ad on what tables and schemas they reside: 
--Put the list in a temp tab
SELECT T.Name as TrigName, o.Name as TabName, s.Name as SchemaName
INTO #AllTriggers
FROM sys.triggers T join sys.objects o
ON T.parent_Id = o. object_ID
JOIN sys.schemas s
ON o.schema_Id = s.Schema_ID


--Disabling all triggers: A cursor to run over the temp table 
DECLARE TrigCurs Cursor
FOR SELECT TrigName, TabName, SchemaName FROM #AllTriggers

OPEN TrigCurs

DECLARE @TrigName varchar(250), @TabName varchar(250), @SchameName VarChar(250), @cmd varchar(1000)

FETCH Next FROM TrigCurs INTO @TrigName , @TabName , @SchameName 

WHILE @@Fetch_Status = 0 
BEGIN 
SET @cmd = 'disable trigger all on '+ @SchameName+ '.'+@TabName+';' 
EXEC (@cmd)

FETCH Next FROM TrigCurs INTO @TrigName , @TabName , @SchameName 
END
GO

I execute it from the Script.PreDeployment.sql  file.

Re-enable them after the data was generated. The T-Sql is:

--Enabling back all triggers: A cursor to run over the temp tab
DECLARE TrigCurs2 Cursor
FOR SELECT TrigName, TabName, SchemaName from #AllTriggers

OPEN TrigCurs2

DECLARE @TrigName varchar(250), @TabName varchar(250), @SchameName VarChar(250), @cmd varchar(1000)

FETCH Next from TrigCurs2 into @TrigName , @TabName , @SchameName 

WHILE @@Fetch_Status = 0
BEGIN
SET @cmd = 'enable trigger all on '+ @SchameName+ '.'+@TabName+';' 
EXEC (@cmd)

FETCH Next FROM TrigCurs2 INTO @TrigName , @TabName , @SchameName 
END

DROP TABLE #AllTriggers
GO

I execute it from the Script.PostDeployment.sql  file.

You can download both scripts: EnableTriggers.sql , DisableTriggers.sql

Public CTP for VSDBPro Service Release 1 is now available

The public CTP for the first service release of Visual Studio Team Edition for Database Professionals just released.
For all the details, please check out Gert's post right here.

C# attributes

I asked too much by .NET developers about attributes and their meaning. I hope that this post will help you to understand it better.

Introduction: what are attributes?

An attribute is a powerful .NET language feature that is attached to a target programming element (e.g., a class, method, assembly, interface, etc.) to customize behaviors or extract organizational information of the target at design, compile, or runtime. It is a clean approach to associate metadata with program elements and later use the metadata at design, compile or run time to accomplish some common objectives. Attributes come in two flavors: intrinsic and custom. Intrinsic attributes are supplied as part of the Common Language Runtime (CLR), and they are integrated into .NET. Custom attributes are attributes you create for your own purposes. As a thumb-rule, a class is said to be an attribute class, if it directly or indirectly derives from the System.Attribute class. 

Why we need attributes?

For example, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used. ; Attributes are also used extensively in securing .NET assemblies, forcing calling code to be evaluated against pre-defined security constraints. ; DllImportAttribute that allows a program to communicate with the Win32 libraries; and more...

Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.

Using attributes

Attributes are placed before the item that they will be "decorating" and they are put inside square braces [].

To understand the power of attributes, consider the serialization of an object. In .NET, you just need to mark a class Serializable to make its member variables as Serializable. Serializable attribute: (type of SerializableAttribute)

1
2
[Serializable()]
public class CustomerData

I didnt use the SerializableAttribute class when applying the attribute to the class. The only time that you can leave off the Attribute portion of the name is when you are applying the Attribute to a class.

1
2
3
4
5
6
7
8
9
10
11
12
public class MyClass
{
  [Obsolete("This method replaced by CalcEx method.", true)]
  static int Calc(int a, int b ) { }

  static int CalcEx (int a, int b ) { }

  public static void Main( )
  {
    int res = Calc(1,2);
  }
}

I used the attribute Obsolete, which marks a method (in this case) that should not be used. The first parameter is the string, which explains why the item is obsolete and what to use instead. In fact, you can write any other text here. The second parameter tells the compiler to treat the use of the item as an error. The default value is false, which means the compiler generates a warning for this.

When we try to compile this program, we will get an error with the message: MyClass.Calc is obsolete: 'This method replaced by CalcEx method.'

Custom attributes

When do you define your custom attributes? query at runtime!  For example, let's create CryAttribute class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CryAttribute : Attribute
{
  private string m_reason;
  public string Reason
  {
    get
    {
      {return m_reason;}
    }
  }

  public CryAttribute(string reason)  
  {
    m_reason = reason;
  }
}

Now, Let's use this attribute:

1
2
3
4
5
6
7
8
9
[Cry("Because babies cry..:)")] // normal babies cry without reason
public class Baby
{
}

[Cry("The baby is hungry")]// The baby cry because he wants to eat
public class HungryBaby : Baby
{
}

It's great...but what can we do with it?? .NET gives us a new point of the view: runtime attributes querying.

How can we query?

1
2
3
4
5
6
7
8
9
public string WhyTheBabyCry(Baby baby)
{
  Type type = baby.GetType();
  object obj = type.GetCustomAttributes()[0];// the first attribute
  if(obj is CryAttribute)
    return ((CryAttribute)obj).Reason;
  else// other attribute
    return "First attribute is not Cry!";
}

Now we can use it:

1
2
3
4
5
6
Baby Baby1 = new Baby();
Baby Baby2 = new HungryBaby();

string reason1,reason2;
reason1 = WhyTheBabyCry(Baby1);// receives "Because babies cry..:)"
reason2 = WhyTheBabyCry(Baby2);// "The baby is hungry"

More about attributes you can find at msdn.

WCF - Part 3: Binding Comparison
Windows Communication Foundation (WCF) has various built-in bindings. System-provided bindings are used to specify the transport protocols, encoding, and security details required for clients and services to communicate with each other.
Although some of these values can be configured differently on certain bindings, the table shows the defaults for each type.
 
This post will briefly describe and summarize the key differences between WCF's built-in bindings.
 
Note: WCF also allows you to define your own custom bindings.
 

Class name

Description

Transport

Message encoding

Security

BasicHttpBinding

A binding that is suitable for communication with WS-Basic Profile conformant Web Services like ASMX-based services. This binding uses HTTP as the transport and Text/XML as the message encoding.

HTTP

 

Text

 

None

WSHttpBinding

A secure and interoperable binding that is suitable for non-duplex service contracts.

HTTP

 

Text

 

Message

WSDualHttpBinding

A secure and interoperable binding that is suitable for duplex service contracts or communication through SOAP intermediaries.

HTTP

 

Text

 

Message

WSFederationHttpBinding

A secure and interoperable binding that supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.

HTTP

 

Text

 

Message

NetTcpBinding

A secure and optimized binding suitable for cross-machine communication between WCF applications

TCP

 

Binary

 

Transport

NetPeerTcpBinding

A binding that enables secure, multi-machine communication.

P2P

 

Binary

 

Transport

NetNamedPipesBinding

A secure, reliable, optimized binding that is suitable for on-machine communication between WCF applications.

Named Pipes

 

Binary

 

Transport

NetMsmqBinding

A queued binding that is suitable for cross-machine communication between WCF applications.

MSMQ

 

Binary

 

Message

MsmqIntegrationBinding

A binding that is suitable for cross-machine communication between a WCF application and existing MSMQ applications.

MSMQ

 

doesn’t use a WCF message encoding – instead it lets you choose a pre-WCF serialization format

Transport

 
Back to WCF TOC.
Enterprise Library 3.1 Released

Enterprise Library 3.1 just Released: It is a maintenance release to fix a few bugs. It also includes an extension point in the Policy Injection Application Block that allows you to replace the injection mechanism.

Changes per Tom Hollander:

Policy Injection Application Block

  • The default Remoting Policy Injector can now be replaced with alternative interception mechanisms via configuration without modifying the application block code
  • Call Handler attributes are now honored correctly when placed on interface methods
  • Fixed an issue that could cause duplicate handlers where matching rules matched both a class and its interface
  • Classes implementing COM interfaces (including those deriving from System.Windows.Forms.Form) can now be intercepted
  • TraceLogEntry class is now serializable, allowing it to be used with the MSMQ Trace Listener

Validation Application Block

  • Fixed an issue that prevented the PropertyComparisonValidator from working with the Windows Forms integration adapter
  • The message template for the PropertyComparisonValidator can now be saved using the configuration tools.

Data Access Application Block

  • Connection strings for OLEDB and ODBC connections can now be edited using custom dialog boxes from the configuration tools

You can download it here.

We are the champions!

Inzaghi inspires Milan to glory!!

Milan win the Champions League final thanks to a 2-1 victory over Liverpool, with both goals coming from Filippo Inzaghi. The first came on 45 minutes and the second came on 82 minutes. Kuyt scored for Liverpool on 88 minutes.

WCF - Part 2: Basic Client/Server app

This post is an example of how to build your first basicly wcf solution.

First step: Contract

Our contract is a simple interface class (ICalculator) containing one function: (Add).In order to declare the interface as a contract, you should add a [ServiceContract] attribute to the class. All methods you want to expose in your service, you should mark as [OperationContract].

1
2
3
4
5
6
[ServiceContract]
public interface ICalculator
{
  [OperationContract]
  int Add(int a,int b);
}

Second step: The server

The server should implement the contract simply by implementing the ICalculator interface as the following code:

1
2
3
4
5
6
7
8
9
public class Calculator : ICalculator
{
  #region ICalculator Members
  public int Add(int a,int b)
  {
    return a + b ;
  }
  #endregion
}

Hosting the server: We'll do this using a C# console application. We need a ServiceHost object to host our service. It implements IDisposable, so we'll use the using statement to create one.

Explanations for the sample below :

  1. Declare a type variable, assign Calculator service contract type to it and pass it into the constructor of our ServiceHost instance.
  2. Open the service.

1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
Type type = typeof(Calculator);
  using (ServiceHost host = new ServiceHost(typeof(type)))
  {
    host.Open();
    Console.WriteLine("The service is available.Press any key to continue...");
    Console.ReadLine();
    host.Close();
  }
}

WCF needs some information from configuration;  The server is configured to run using the ICalculator Contract, but I didn't specify neither the Address or the Binding. The App.Config file contains the Address and Binding as following:

We can generate the App.config using the SvcConfigEditor.exe tool under "\Program Files\Microsoft Visual Studio 8\Common7\IDE\".

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <services>
            <service name="Wcf.Samples.Calculator">
                <endpoint
                  address="net.tcp://localhost:5555/Calculator/"
                  binding="netTcpBinding"                  
                  contract="Wcf.Samples.ICalculator"
                  bindingConfiguration="" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

Third step: The client

After the server is ready, we can build our client;

1
2
3
4
5
6
7
8
9
10
static void Main(string[] args)
{
  using (ChannelFactory<ICalculator> claculatorFactory = new ChannelFactory<ICalculator>("MyClient"))
  {
    ICalculator calcProxy = claculatorFactory.CreateChannel();
    int res = calcProxy.Add(1,2);
    Console.WriteLine(res);
    Console.ReadLine();
  }
}

We can generate the App.config the same way we generated the server with the SvcConfigEditor.exe to get the following file:

<client>
    <endpoint address="net.tcp://localhost:5555/Calculator" binding="netTcpBinding"
        contract="Wcf.Samples.ICalculator"
        name="MyClient" />
</client>

The application is ready to use.

Back to WCF TOC.

WCF - Part 1: Introduction & Service ABC

WCF brings all the formerly distinct and separate Microsoft connectivity technologies together under a single umbrella within the System.ServiceModel namespace. Web services (ASMX), the Web service Extensions (WS*), Microsoft Message Queuing (MSMQ), Enterprise Services, COM+, and .NET Remoting are included in WCF.  With WCF you won't have to choose between implementations in a variety of different namespaces and coding types to create a connected application. Whether your application connects via loosely coupled Web services, or tightly coupled Enterprise Services, the coding model will be consistent and the transition between different communication types will be much smoother—because they will all be using the same programming namespace. WCF follows the "software as a service" model, where all units of functionality are defined as services.

ABC

Before start working with WCF the developer should identify three major points:

  • Address: WCF services must have an address. The address specifies the location of the service which will be exposed (like http://www.maordavid.com) for clients that will use it to communicate with the service.  The address's protocol that WCF can provided: HTTP , TCP ,NamedPipe , Peer2Peer ,MSMQ.
  • Binding: Specifies how a service is accessible. In other words: how the two parties will communicate in terms of transport (HTTP , TCP ,NamedPipe , Peer2Peer ,MSMQ)  ,encoding (text, binary etc.) and protocols (like transactional support or reliable messaging).
  • Contract: Used to specify what your service can do. For example: give you the square when providing 2 numbers.

Endpoints

All communications with the WCF service will happen via the endpoints. The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods. The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. WCF provides Windows Activation Services which can be used to host the WCF service. Otherwise the WCF service can also be hosted in IIS or in any process by using the Service Host class, which is provided by WCF. Services can also be self-hosted.

Back to WCF TOC.

WCF Articles

In order to introduce Windows Communication Foundation (WCF) I'm starting a series of posts here.

Most of the applications now requires to support the SOA architecture, means that the application should provide a service interfaces to be exposed to other applications. These interfaces can be exposed using many technologies: Web Services, COM+ and so on. Each technology is completely defferent from the other, and requires special knowledge of coding.

WCF makes life better. WCF helps developers to expose service interfaces using any technology. WCF has same set of functions and attributes that will be used for all technologies (bindings).

From every post I'll refer to this post and I'll keep a TOC here so you can easily navigate in the blog.

TOC:

  1. Introduction to WCF; Service ABC;
  2. Basic client/Server application.
  3. Binding comparision.
WCAT 6.3 web performance and scalability test tool released!

The latest version of WCAT (Web Capacity Analysis Tool - the web performance test tool that the IIS team and NT Performance team use to conduct internal performance and scalability testing of IIS and ASP.NET) just released .

For more details and download, read: http://mvolo.com/blogs/serverside/archive/2007/05/17/WCAT-6.3-web-performance-and-scalability-test-tool-released.aspx.

My article at Patterns and Practices - VSTS Wiki

The patterns and practices VSTS team has created a project in CodePlex. Recently, they have opened it up to community contribution using a Wiki. I published there an article that discussing the synchronization between TFS and test director.

VSTS for database professionals installation requirements

A lot of users feel confused about the installation requirements of VSTS for DB Professionals (DB Pro).

"Team Suite or other product must be installed before Db Pro" as the ReadMe file says.

The requirements of VSTS for Database Professionals are:

  • Visual Studio Professional Edition/Visual Studio Team Suite. Team Edition for Database Professionals is available as a separate product; however, to evaluate the Team Edition for Database Professionals Trial you must first install the Visual Studio 2005 Team Suite 180-Day Trial.  
  • The Visual Basic or C# language feature must be installed.
  • MSXML must be installed.
  • Visual Studio Professional Edition is included on the DVD for Visual Studio Team Edition for Database Professionals.

The requirement for a Team Suite install is ONLY when you want to install the TRIAL Version of DB Pro.  The RTM Full Version of Data Pro is an add on that can be installed with ANY version of Visual Studio starting with the Professional version.

Save datagrid changes in the database

Once you want edit a recore, add new or deleted a recored in your data grid you may want to save it in the database.

How do we do it?

  1. Create UpdateCommand handler for the data grid
  2. Identify what DataGrid row was updated by getting the ItemIndex property of the row (Item object) passed in the event object. Then use the index value to get the corresponding value out of the grid's DataKeys collection:
    • string key = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
  3. Get the changed values out of the DataGrid row. How?
    • From the item passed in the event object, get the appropriate cell (zero-based) out of the Cells collection from the item passed in the event object. For example, the left-most column in the grid is Cells(0).
    • For each cell, get its Controls collection, which contains all the elements that appear in the cell.
    • Get the first (and only) control out of the collection — for this example, a TextBox control. To get the TextBox, declare a local variable of type TextBox and cast the object in the Controls collection to it.
    • Get the TextBox control's value (its Text property).
  4. Find the corresponding row in the data table. The dataset contains a special FindBy method — that locates a row by its primary key and returns a reference to it.
  5. Update the row by changing values in the row you located in Step 4.
  6. Send changes from the dataset to the database by calling the data adapter's Update method.
  7. Switch the current row in the grid out of editing mode.
  8. Data-bind the DataGrid control.

Code example:

private void myDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string productName, productDescription;

// Gets the value of the key field of the row being updated
string key = myDataGrid.DataKeys[e.Item.ItemIndex].ToString();

// Gets get the value of the controls (textboxes) that the user
// updated.
// Each cell has a collection of controls. In this case, a TextBox control.
// The first column -- Cells(0) -- contains the Update and Cancel buttons.

TextBox tb;

// Gets the value the TextBox control in the third column
tb = (TextBox)(e.Item.Cells[2].Controls[0]);
productName = tb.Text;

// Gets the value the TextBox control in the fourth column
tb = (TextBox)(e.Item.Cells[3].Controls[0]);
productDescription = tb.Text;

// Finds the row in the dataset table that matches the
// one the user updated in the grid. This example uses a
// special Find method defined for the typed dataset, which
// returns a reference to the row.
dsProducts.CategoriesRow r;
r = dsProducts.Categories.FindByProductID(int.Parse(key));

// Updates the dataset table.
r.ProductName = productName;
r.ProductDescription = productDescription;

// Calls a SQL statement to update the database from the dataset
sqlDataAdapter1.Update(dsProducts);

// Takes the DataGrid row out of editing mode
myDataGrid.EditItemIndex = -1;

// Refreshes the grid
myDataGrid.DataBind();
}

For more information about DataSet updates, navigate to: http://msdn2.microsoft.com/en-US/library/y2ad8t9c(VS.71).aspx

Db Dude posts

I wrote 2 new posts about DB Dude (of Team System).

The first is a summary about error & warning messages. You can find it at SRLTeam blog.

The second is enable/disable t-sql scripts that executed before and after test data deployment is order to disable triggers and re-enable them. This post also published at SRLTeam blog.

Silverlight introduction

At Mix07, Microsoft announced Silverlight.

Microsoft Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web.

You can read more here (SilverLight site), its amazing!

Great post about Silverlight UI Controls, by Ashish Shetty, you can find here.

Slides and demos you can download from Nikhil Kothari's Weblog.

Enjoy!

More Posts Next page »

Search

Go

This Blog

News

    RSS

     

    Connect with Me

    Maor's Facebook profile  Follow Maor on Twitter  Maor's profile on Linkedin  Maor in FriendFeed 
           

Syndication