SSMS Tools Pack is a must have add-in for SQL Server Management Studio. It comes packed with a great set of features which as the author says on his site “…were missing from Management Studio”. Here is run down of three features I use most.
Text Format
If SSMS Tools Pack had only one feature and it was text formatting I’d still have praise for the tool. In the past I have used tricks such as switching to query designer view or an online SQL formatting service to format my SQL. With SSMS Tools Pack this can easily be done by pressing Ctrl+K and Ctrl+G. This feature is also configurable and you can enable/ disable keywords.
Generate Insert Statements
Insert Statements can be easily generated for data in your tables. This comes in handy when you want to script your data and maybe run it on another database. Generating Insert Statements is easily done by right clicking on the table –> SSMS Tools –> Generate Insert Statements.
SQL Query Execution History
While working with databases I can at times write a lot of queries. I usually end up commenting many in Query editor just to keep them around. With SQL Query Execution History I don’t bother. I always get a nice history of all queries I have executed in the order of execution.
Other than its features, the thing I like most about SSMS Tools Pack is that it is a light weight add-in which does not mess up your environment. So if you spend a lot or any time writing SQL then SSMS Tools Pack is worth a look.
If you have been having issues with Outlook 2007 related to performance, erratic behaviour and just annoyance in general then this hotfix maybe what you need. Released in February 2007 the patch fixes many issues which can make working with Outlook 2007 a punishment. I installed it today morning and it’s been working fine and dandy for me.
Working on a project where we wrote WCF Services a need was identified to capture the raw xml passed in to the service operation and also capture the reply xml sent back by the service. WCF does not provide such facility out of the box but it can be easily implemented using behaviours. In this article we will look at how to capture raw xml messages when a call is made to a service.
As an example we will create a simple service which implements one operation called SayHello. Our service contract will look like this.
[ServiceContract] public interface IHelloService { [OperationContract] string SayHello(string name); }
In the operation “SayHello” we will return a string. Here is the implementation of IHelloService contract.
public class HelloService : IHelloService { #region IHelloService Members public string SayHello(string name) { return string.Concat("Hello ", name); } #endregion }
We will host our Service In a Windows Forms application so that we can easily view xml we capture. Just to get a feel for it, our host application will look like this. Clicking the button will start the service and as calls are made we will see request and response content in the tabs.
Capturing XML
To capture XML we need to implement two interfaces IDispatchMessageInspector and IServiceBehavior. The way our solution works is that we will add our implementation of IDispatchMessageInspector to MessageInspectors collection on endpoints used by our ServiceHost.
We will first implement IDispatchMessaageInspector in a class called Inspector.
public class Inspector : IDispatchMessageInspector { /// <summary> /// Stores contents of Request message /// passed to the service. /// </summary> /// <value>The request XML.</value> public string Request { get; set; } /// <summary> /// Stores contents of Response messge /// which is sent back to the client. /// </summary> /// <value>The response XmL.</value> public string Response { get; set; } #region IDispatchMessageInspector Members /// <summary> /// Called after an inbound message has been received but /// before the message is dispatched to the intended operation. /// </summary> /// <param name="request">The request message.</param> /// <param name="channel">The incoming channel.</param> /// <param name="instanceContext">The current service instance.</param> /// <returns> /// The object used to correlate state. /// </returns> public object AfterReceiveRequest(
ref System.ServiceModel.Channels.Message request,
System.ServiceModel.IClientChannel channel,
System.ServiceModel.InstanceContext instanceContext) { Request = request.ToString(); return null; } /// <summary> /// Called after the operation has returned but before the reply message is sent. /// </summary> /// <param name="reply">The reply message.
/// This value is null if the operation is one way.</param>
/// <param name="correlationState">The correlation object returned from the /// AfterReceiveRequest method.</param> public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply,
object correlationState) { Response = reply.ToString(); } #endregion }
Next we need to create a custom behaviour by implementing IServiceBehavior. The only method we are interested in this interface is the ApplyDispatchBehavior method. Here is our implementation of IServiceBehavior.
public class CustomBehavior : IServiceBehavior { #region IServiceBehavior Members /// <summary> /// Provides the ability to pass custom data to binding elements /// to support the contract implementation. /// </summary> /// <param name="serviceDescription">The service description of the service.</param> /// <param name="serviceHostBase">The host of the service.</param> /// <param name="endpoints">The service endpoints.</param> /// <param name="bindingParameters">Custom objects to which binding elements have access. /// </param> public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { return; } /// <summary> /// Provides the ability to change run-time property values or /// insert custom extension objects such as error handlers, /// message or parameter interceptors, /// security extensions, and other custom extension objects. /// </summary> /// <param name="serviceDescription">The service description.</param> /// <param name="serviceHostBase">The host that is currently being built.</param> public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) { dispatcher.Endpoints .ToList() .ForEach(x => x.DispatchRuntime.MessageInspectors.Add(new Inspector())); } } /// <summary> /// Provides the ability to inspect the service host and /// the service description to confirm that the service /// can run successfully. /// </summary> /// <param name="serviceDescription">The service description.</param> /// <param name="serviceHostBase">The service host that is currently being constructed. /// </param> public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { return; } #endregion }
As said earlier, we will host our service in a Windows Forms application and we would like to display messages in the UI. For this we need access to messages outside the Inspector class we created above. This can be done by raising events when messages are captured. To do just that we will extend our Inspector class with two events and raise them from AfterReceiveRequest and BeforeSendReply methods.
/// <summary> /// Triggered from AfterReceiveRequest method. /// </summary> public event EventHandler<InspectorEventArgs> RaiseRequestReceived; /// <summary> /// Triggered from BeforeSendReply method. /// </summary> public event EventHandler<InspectorEventArgs> RaiseSendingReply; protected void OnRaiseRequestReceived(string message) { EventHandler<InspectorEventArgs> handler = RaiseRequestReceived; if (handler != null) { handler(this, new InspectorEventArgs(message)); } } protected void OnRaiseSendingReply(string message) { EventHandler<InspectorEventArgs> handler = RaiseSendingReply; if (handler != null) { handler(this, new InspectorEventArgs(message)); } }
And we will also modify AfterReceiveRequest and BeforeSendReply to raise these events.
/// <summary> /// Called after an inbound message has been received but /// before the message is dispatched to the intended operation. /// /// This method will also raise RaiseRequestReceived event. /// </summary> /// <param name="request">The request message.</param> /// <param name="channel">The incoming channel.</param> /// <param name="instanceContext">The current service instance.</param> /// <returns> /// The object used to correlate state. /// </returns> public object AfterReceiveRequest( ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext) { Request = request.ToString(); OnRaiseRequestReceived(Request); return null; } /// <summary> /// Called after the operation has returned but before the reply message is sent. /// /// This method will also raise RaiseSendReply event. /// </summary> /// <param name="reply">The reply message. /// This value is null if the operation is one way.</param> /// <param name="correlationState">The correlation object returned from the /// AfterReceiveRequest method.</param> public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { Response = reply.ToString(); OnRaiseSendingReply(Response); }
InspectorEventArgs is a simple class used to store and pass information with our events.
public class InspectorEventArgs : EventArgs { public InspectorEventArgs(string message) { this.Message = message; } public string Message { get; set; } }
Hosting The Service And Using Inspector
Now we are at the point where we can use our behaviour to capture request and response messages. First of all we need to put in some code to host our service. This code will go in the click event handler for our button. There are two main things do here. First we add our custom behaviour to the Behaviors collection of our host and second we hook up the events that are raised by our Inspector class.
private void buttonStartService_Click(object sender, EventArgs e) { // Add our Custom Behaviour to the list of behaviours host.Description.Behaviors.Add(behavior); // start the service host.Open(); // add event handlers foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers) { foreach (var endPoint in dispatcher.Endpoints) { // get a list of MessageInspectors that are of type Inspector var query = (from ex in endPoint.DispatchRuntime.MessageInspectors where ex.GetType() == typeof(Inspector) select ex).Cast<Inspector>(); // hook up the events foreach (var item in query) { item.RaiseRequestReceived += new EventHandler<InspectorEventArgs>(Form1_RaiseRequestReceived); item.RaiseSendingReply += new EventHandler<InspectorEventArgs>(Form1_RaiseSendingReply); } } } }
Now when HelloService is called we will see request and response xml in our Windows Forms application which is also a host for HelloService. We will use WebBrowser controls to display XML. Displaying XML in the WebBrowser control is not just setting a property. There is little but not too much work involved. I picked up a nice technique from this link.
/// <summary> /// Writes xml to browser. /// WebBrowser control does render xml properly and to get around /// I am using this handy tip from this link. /// http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=51473 /// </summary> /// <param name="browser">The browser.</param> /// <param name="message">The message.</param> private void WriteToBrowser(WebBrowser browser, string message) { XslCompiledTransform xTrans = new XslCompiledTransform(); xTrans.Load("default.xslt"); StringReader sr = new StringReader(message); XmlReader xReader = XmlReader.Create(sr); System.IO.MemoryStream ms = new MemoryStream(); xTrans.Transform(xReader, null, ms); ms.Position = 0; browser.DocumentStream = ms; }
Creating The Client
Client for HelloService is a simple Windows Forms application with a text box, button and a label. You can download the code at the end of this article and see it for yourself.
The Output
Here are screenshots of both client and host showing request and response XML.
I hope you found this article interesting. If yes, then how about subscribing to the feed :)
To get width and height of an image we can use System.Drawing.Image class. This code snippet shows how to retrieve width and height of an image.
string filePath = @"c:\deepak\MeeGo.jpg";
Image img = Image.FromFile(filePath);
Console.WriteLine(string.Format("Height: {0}",img.Size.Height));
Console.WriteLine(string.Format("Width: {0}",img.Size.Width));
Windows Registry Size can be retrieved using WMI objects. This code snippet shows you how to get current size and maximum size for Windows registry.
ManagementObjectSearcher mgmtObjects =
new ManagementObjectSearcher("Select * from Win32_Registry"); foreach (var item in mgmtObjects.Get()) { Console.WriteLine(string.Format("Current Size: {0}MB", item["CurrentSize"])); Console.WriteLine(string.Format("Maximum Size: {0}MB", item["MaximumSize"])); }
The output.
![]()
Conficker worm which strikes on April 1st is already being labelled as one of the most dangerous cyber attacks ever. The way this worm works is that it sets up what are known as botnets on computers around the world. The worm goes active on April 1st when it can be used by its creators to potentially damage computers, networks and do all kind of bad guys stuff. The worm exploits MS088-067 Windows Server vulnerability.
It goes without saying that you should protect your computers. There are many removal tools available which can be used to remove Conficker from your computer. This is a list of different options you have to remove this worm.
- McAftee AVERT Stinger Conficker
- Stand-Alone System Sweeper tool (available as part of Microsoft Desktop Optimization Pack).
- Enigma Software Conficker Removal Tool.
- Removal tool by F-Secure.
- Windows Malicious Software Removal Tool by Microsoft.
As a good practice you should always keep your system patched. This can be done by configuring automatic updates on your windows computer. Keep it safe, keep it updated :)

In .Net Framework reversing array elements can be done by using Reverse method on Array type. This code snippet shows you how this method can be used to reverse an array.
// Declare an array with 10 elements int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Output elements in original order for (int i = 0; i < numbers.Length; i++) { Console.Write(" {0}", numbers[i]); } Console.WriteLine(); // Reverse the array Array.Reverse(numbers); // Output elements with changed order for (int i = 0; i < numbers.Length; i++) { Console.Write(" {0}", numbers[i]); } Console.ReadKey();
Here is the output.
Array.Reverse method also provides an overload which can be used to reverse elements at a given indexes. For example we want to reverse elements 3, 4 and 5 but leave others intact. This can be achieved using the following code snippet.
// Declare an array with 10 elements int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Output elements in original order for (int i = 0; i < numbers.Length; i++) { Console.Write(" {0}", numbers[i]); } Console.WriteLine(); // Reverse numbers 3 , 4 and 5 Array.Reverse(numbers, 2, 3); // Output elements with changed order for (int i = 0; i < numbers.Length; i++) { Console.Write(" {0}", numbers[i]); } Console.ReadKey();
And the output is.

To convert a Hexadecimal to a number we can use an overload of Convert.ToInt32 method.
Using the overload I can convert for example hex string “BB” to a number.
int number = Convert.ToInt32("BB", 16);
And the number variable gets assigned value of 187.
To get free disk space for all physical drives on a machine we can use xp_fixeddrives extended stored procedure. An interesting this about this procedure is that it is not documented in books online.
EXEC xp_fixeddrives
Here is output on my machine.
![]()
You’ve got to love sys views in SQL Server. While learning about performance tuning on SQL Server 2008 I wanted to get a list of all Indexes on my database and the answer was as simple as it can be. Here i a statement which can be used to get a list of all indexes on a database.
SELECT * FROM sys.indexes
And here is the partial output from AdventureWorks database.

I was recently helping Nosh with a LINQ To SQL query where he wanted the resulting T-SQL query to have CASE statements. Having CASE statements in T-SQL queries is a common scenario but how do we it in LINQ To SQL .After some investigation I found the solution which I am presenting here using an example.
I have created a table called CityWeather. This table has two fields: Name and Temperature. Here is the script if you wish to create the table on your machine.
CREATE TABLE [dbo].[CityWeather]( [Name] [nvarchar](100) NOT NULL, [Temperature] [decimal](18, 0) NOT NULL ) ON [PRIMARY]
My objective is to get LINQ To SQL to produce a T-SQL statement similar to this.
SELECT Name, Temperature, CASE Temperature WHEN 30 THEN 'Toasted' WHEN 25 THEN 'I like it' WHEN 10 THEN 'Just perfect' WHEN -15 THEN 'Gonna freeze my' END AS 'Message' FROM CityWeather
Using my trusted LINQPad here is how I wrote my LINQ To SQL query.
from c in CityWeathers
select new
{
c.Name,
c.Temperature,
Messaage = c.Temperature == 30 ? "Toasted" :
c.Temperature == 25 ? "I like it" :
c.Temperature == 10 ? "Just perfect" :
c.Temperature == -15 ? "Gonna freeze my" : ""
}
My LINQ To SQL query produced the following T-SQL Query
SELECT [t0].[Name], [t0].[Temperature], (CASE WHEN [t0].[Temperature] = @p0 THEN CONVERT(NVarChar(15),@p1) WHEN [t0].[Temperature] = @p2 THEN CONVERT(NVarChar(15),@p3) WHEN [t0].[Temperature] = @p4 THEN CONVERT(NVarChar(15),@p5) WHEN [t0].[Temperature] = @p6 THEN @p7 ELSE CONVERT(NVarChar(15),@p8) END) AS [Messaage] FROM [CityWeather] AS [t0] -- @p0: Input Decimal (Size = 0; Prec = 33; Scale = 4) [30] -- @p1: Input NVarChar (Size = 7; Prec = 0; Scale = 0) [Toasted] -- @p2: Input Decimal (Size = 0; Prec = 33; Scale = 4) [25] -- @p3: Input NVarChar (Size = 9; Prec = 0; Scale = 0) [I like it] -- @p4: Input Decimal (Size = 0; Prec = 33; Scale = 4) [10] -- @p5: Input NVarChar (Size = 12; Prec = 0; Scale = 0) [Just perfect] -- @p6: Input Decimal (Size = 0; Prec = 33; Scale = 4) [-15] -- @p7: Input NVarChar (Size = 15; Prec = 0; Scale = 0) [Gonna freeze my] -- @p8: Input NVarChar (Size = 0; Prec = 0; Scale = 0) [] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
And here is the output.

This is where reflection comes in handy. The following code snippet shows you how to get the name of executing assembly.
string assemblyName; assemblyName = System.Reflection.Assembly.GetExecutingAssembly().FullName; Console.WriteLine(assemblyName);
Output for the above code returns the fully qualified name as shown below
To just get the Assembly name we can use this snippet.
string assemblyName; assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; Console.WriteLine(assemblyName);
Here is the output.
![]()
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML

