Thursday, February 19, 2015

WCF Tracing



In service oriented environment, debugging an issue can often become difficult especially if something is failing during the communication between the service and client. .NET provides a System.Diagnostics namespace which allows us to interact with system process, event logs and other counters. WCF tracing is built on top on this namespace.

To use WCF tracing, we can define the trace sources either in configuration file or in code. Here in this blog I will explain how to define it in configuration file. The System.ServiceModel trace source is the most general trace source which records milestones across the WCF communication stack from entering/leaving transport to entering/leaving user code. The System.ServiceModel.MessageLogging source records all messages that flow through the system.

This tracing is not enabled by default. To activate it, we must create a listener and set the trace level to something other than “Off”. If we do not define a listener, tracing is automatically disabled. If we define a listener, but not a trace level, it is automatically set to “Off” and hence no tracing is performed.

We start with defining <system.diagnostics> tag in configuration file.

<configuration>
   <system.diagnostics>

   </system.diagnostics>
</configuration>

WCF has a set of predefined trace sources available for each assembly.

·         System.ServiceModel:
·         System.ServiceModel.MessageLogging
·         System.IdentityModel.
·         System.ServiceModel.Activation.
·         System.IO.Log:
·         System.Runtime.Serialization:
·         CardSpace.

The first step is to define the source for tracing. For example “System.ServiceModel”

<source name="System.ServiceModel">

We need to set a proper tracing level other than “Off” for the above mentioned source to enable the tracing. Following tracing levels are available:

Trace Level
Tracked Events
Off
No traces are emitted.
Critical
Unhandled exceptions including the following are logged:
  • OutOfMemoryException
  • ThreadAbortException (the CLR invokes any ThreadAbortExceptionHandler)
  • StackOverflowException (cannot be caught)
  • ConfigurationErrorsException
  • SEHException
  • Application start errors
  • Failfast events
  • System hangs
  • Poison messages: message traces that cause the application to fail.
Error
All exceptions are logged.
Warning
  • The application is receiving more requests than its throttling settings allow.
  • The receiving queue is near its maximum configured capacity.
  • Timeout has exceeded.
  • Credentials are rejected.
Information
In general, messages helpful for monitoring and diagnosing system status, measuring performance or profiling are generated. You can use such information for capacity planning and performance management:
  • Channels are created.
  • Endpoint listeners are created.
  • Message enters/leaves transport.
  • Security token is retrieved.
  • Configuration setting is read.
Verbose
In general, you can use this level for debugging or application optimization.
  • Understood message header.
ActivityTracing
This level allows administrators and developers to correlate applications in the same application domain:
  • Traces for activity boundaries, such as start/stop.
  • Traces for transfers.
All
All previous events.

The tracing level is determined by the switchValue setting of the source.

<source name="System.ServiceModel" switchValue="Information">

Next step is to configure a listener. To define a listener we need to add the following to config file.

<source name="System.ServiceModel" switchValue="Information">
   <listeners>
      <add name="traceListener"
      type="System.Diagnostics.XmlWriterTraceListener"
      initializeData="D:\log\Traces.svclog" />
   </listeners>
</source>

There are different kinds of listeners available but I have chosen XmlWriterTraceListener for this example. We can add any number of listeners to each source. If the trace listener emits trace to a file, we need to specify the output file location. This is done by setting initializeData to the location and name of the file. The advantage of using XmlWriterTraceListener is that we can open this log file in SvcTraceViewer.exe (Service Trace Viewer Tool) which helps us analyze traces generated by WCF.

So putting all together the file appears like this:

<configuration>
   <system.diagnostics>
      <sources> 
        <source name="System.ServiceModel"
        switchValue="Information">
            <listeners>
               <add name="traceListener"
 type="System.Diagnostics.XmlWriterTraceListener"
 initializeData="D:\log\Traces.svclog" />
            </listeners>
        </source>
      </sources>
   </system.diagnostics>
</configuration>

The .svclog file generated can be directly opened in Service Trace Viewer Tool by double clicking the file. The tool can also be found under

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\ or C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\

Shown below is the screenshot of the tool.


Service Trace Viewer Tool (SvcTraceViewer.exe)


Configuring Shared Listeners

In case of multiple trace sources, we can also configure all traces sources to use the same listener using <sharedListeners>. Please see the below example for usage of <sharedlisteners>

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.IO.Log">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.Runtime.Serialization">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
       </sources>
        <sharedListeners>
            <add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="D:\log\Traces.svclog" />
        </sharedListeners>
    </system.diagnostics>
</configuration>

Enable Message Logging

To activate tracing for System.ServiceModel.MessageLogging we need to set attributes for <messagelogging> element as well. This has be set under <system.serviceModel> tag.


<system.diagnostics>
  <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
                 <add name="messages"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="D:\log\messages.svclog" />
          </listeners>
      </source>
    </sources>
</system.diagnostics>
<system.serviceModel> 
 <diagnostics>
    <messageLogging
         logEntireMessage="true"
         logMalformedMessages="false"
         logMessagesAtServiceLevel="true"
         logMessagesAtTransportLevel="false"
         maxMessagesToLog="3000"
         maxSizeOfMessageToLog="2000"/>
  </diagnostics>
</system.serviceModel>
  • logEntireMessage: By default, only the message header is logged but if we set it to true, the entire message including message header as well as body will be logged.
  • logMalformedMessages: This option logs messages that are rejected by WCF stack at any stage known as malformed messages.
  • logMessagesAtServiceLevel: Messages those are about to enter or leave user.
  • logMessagesAtTransportLevel: Messages those are about to encode or decode.
  • maxMessagesToLog: Maximum quota for messages. Default value is 10000.
  • maxSizeOfMessageToLog: Message size in bytes.

More to Read References:

·         Configuring Tracing
·         Configuring Message Logging
·         Service Trace Viewer Tool


Wednesday, September 17, 2014

SQL Server Error "Saving changes is not permitted"

In SQL Server Management Studio, while modifying table design through Design option, users often come across the error "Saving changes is not permitted..." as shown below.

Error Dialog
 
The complete error states that:
Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

This problem occurs when the "Prevent saving changes that require the table re-creation" option is enabled and one or more following changes are made to the table:
  • Changing the Allow Nulls setting for a column
  • Reordering the columns
  • Changing the column data type
  • Adding a new column
When a table is changed such that it alters the metadata structure of table, it requires re-creation of table based on the changes. This may result in loss of metadata and loss of data during re-creation of table. If the "Prevent saving changes that require the table re-creation" option in Designer section of SQL Server Management Studio Options window is enabled, this error message is displayed.
 
To avoid this error, T-SQL statements are to be used to make changes to the  metadata structure of table. For example, to change a column to accept NULL values, we can use:
alter table Table1 alter column Column1 int NULL
 
It is not recommended to disable "Prevent saving changes that require the table re-creation" option to by pass this error.
 
Turning off this option will definitely help in re-creating a table, but it also leads to changes being lost. For instance, we may have enabled the Change Tracking feature to track changes to the table. If we turn of this option, when a table is re-created, the existing change tracking information is deleted. Hence it is not recommended to turn off this option.
 
...Ssk
 


 

Sunday, June 23, 2013

Fun with JQuery - Useful Jquery plugins

jQuery Validation Plugin

Client validation has always been a big task in web development. Well, JQuery makes it simple for us. This jquery plugin makes clientside validation simple and offers many options for customization. It is a good choice when you are making something from scratch and also is easy to integrate into an existing application. The plugin comes with lot of useful set of validation methods including URL and emails validations. It also provide ways to add your own validation methods. All bundled methods comes with default error message in English and transaltions to 37 locales.
You can download this plugin from here.
  

jQuery UI

Ever wondered how to make awesome web UI with little effort. jQueryUI is the answer for that. It is set of user interface interactions, effects, widgets and themes built on top of jQuery library. Whether you are building highly interactive web apps or just adding few controls to your website, this plugin is an excellent choice.
You can download the stable version from here. Also you can customize the download according to the features required at the same link.

jQuery template

DataGrids are one of the most frequently used method to display organized data. jQuery template is the way to do it using jQuery library. jQuery templates contain markup with binding expressions ('Template tags'). Templates are applied to data objects or arrays, and rendered into the HTML DOM. This library was developed by Microsoft to achieve DataGrid like views. Though furhter development has been stopped on this plugin, it is still pretty much useful.
You can download it here

jQuery AJAX Form

AJAX is a well known web development technique used on client side to create aysnchronous web request. Posting the whole form data through AJAX is a difficult thing to manage. To make it easier, jQuery From plugin is the way to go forward. It allows you to easily use AJAX with HTML forms. The main methods ajaxForm and ajaxSubmit allows you to submit your form data via AJAX. Both these methods also support various options which allows you tohave full control over how the form data is submitted.
You can download this plugin from here. Examples to use the plugin are available here

jQuery Wizard

Wizard are known to provide unfamiliar,complex tasks in a easy to do manner to user. Though in windows application there are ways to create easliy, in web application it is a difficult one to attain. jQuery Wizard makes it easier to turn any web form into wizard in few steps. A complete tutorial is available at this link. To download this plugin please click here
 ...Ssk

Tuesday, June 18, 2013

Databind dropdown list (select) in PHP

Being new to PHP, it may occur to you about how to databind controls. I thought of putting it down here about how to do it. To start with we create the connection and query the database.

<?php
$link = mysql_connect("localhost","dbuser","password");

if (!$link) {
        die('Could not connect: ' . mysql_error());
}

mysql_select_db("mydatabase");
$sql = mysql_query("select * from employee");?>

Then add the select statement
<select name="dropdownlist">
<?php
while($row = mysql_fetch_array($sql))
{
?>
<option value=" <?php echo $row['ID']?>">
<?php echo $row['EmpName'] ?></option>
<?php } ?>
</select>

Each row is fetched into $row and the column values can be access by passing the column name like $row['EmpName'] as in above example, the value of option is assigned from ID and the text is added from EmpName.

 ...Ssk