Monday, April 30, 2007

* Pre-release version of Longhorn sdk and .NET 3.5 available

Microsoft has made available the pre-release version of both Longhorn sdk and .NET 3.5.

Its available as an ISO image and can be installed on Longhorn, Windows 2003, Vista and XP.

It can be downloaded from following link :

.NET 3.5 beta

Other Posts

* Tool : FxCop - Managed Code Analysis

FxCop is a tool provided by Microsoft for managed code analysis. Its an excellent tool for doing a quality check on your code during and post development.

The documentation provided with FxCop is excellent for beginners so i will not demonstrate how to use the tool. I will list down some of the features of this tool to encourage you to start using this tool if you are not using it till now.

  • Its main objective is to check managed code for programming & design guidelines and report issues if there are any.
  • It is available both with GUI and as a command line tool to get integrated into automated build process. FxCop.exe is with GUi and FxCopCmd.exe is command line tool.
  • It comes by default with lot of best practices rules for programming and design in areas of Naming, performance, security etc.
  • Custom rules can be added and existing rules can be suppressed based on requirement.
  • It can be used to view IL stored in assemblies.
  • It can also be used for finding Managed & Full Binding closure of assemblies.
  • Can be used as an external command in Visual Studio
  • Some of the rules available by default are :
    • Validate Arguments of Public Methods
    • Mark assemblies with assembly version
    • Specify CultureInfo
    • Compound words should be cased correctly
    • Avoid unused parameters
  • With minimum of overhead this tool can bring lot of quality add to your application.

FxCop can be download from FxCop Team Page.

Other Posts

Friday, April 27, 2007

* Writing Plug-in for Windows Live Writer - It can't get easier

Windows Live Writer has almost become the de-facto client blogging tool on Windows to compose and post blogs on various blogging sites. It is more popular among Microsoft community as it is developed using .net technology. Its still in its beta stage but much popular than lots of production ready tools.

Apart from its simple UI, the most powerful feature of Live writer is its extensibility. There are already thousands of plugins available on web to extend your Live Writer Installation. As its developed using .net, the plugins can also be written in .net using CSharp or  VB.NET.

The sdk for Live Writer provide two types of content sources :

  • Simple : for inserting custom HTML into post.
  • Smart : for inserting html content with editing capabilities using sidebar.

The main steps in writing a Live Writer Plugin are :

  • Create a new 'Class Library'  type of project.
  • Include reference to WindowsLive.Writer.Api assembly provided with sdk.
  • Add namespace WindowsLive.Writer.Api to the project main cs file.
  • Create your plugin class inheriting ContentSource class.
  • Override CreateContent method.
  • Build the assembly and copy it to C:\Program Files\Windows Live Writer\Plugins\ folder. That's it .. done :-)
  • Below is the complete code for a plugin which will insert following tags to the post :

Add to : del.icio.us Digg this Technorati

The source code :    

using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

namespace VikasGoyal.WriterPlugin
{
[WriterPlugin("25522063-0a17-47af-ad69-cc284bcb80ef", "Add To Favourites",
PublisherUrl = "http://dotnetwithme.blogspot.com",
Description = "Add to Favourties for various bookmarking sites")]

[InsertableContentSource("Add To Favourties")]


public class AddToFavourites : ContentSource
{
public override DialogResult CreateContent(IWin32Window dialog, ref string content)
{
DialogResult result = DialogResult.OK;
content = "<p><font face=\"Verdana\"><b><font color=\"#FF0000\">Add to :</font></b>" +
"<a href=\"http://del.icio.us/post\">del.icio.us</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
"<a href=\"http://digg.com/submit\">Digg this</a>&nbsp;&nbsp;&nbsp;&nbsp;"+
"<a href=\"http://www.technorati.com/faves\">Technorati</a> </font></p>";
return result;
}
}
}


Some related links :





Other Posts




Wednesday, April 25, 2007

* Tool : CLRProfiler for .NET 2.0 released

CLR team at Microsoft has released the new version of CLRProfiler for .NET 2.0.

It can be downloaded from following location.

CLRProfiler is mainly used to study the memory usage behavior of managed applications.

Some of the graphs available as an output are :

  • Allocation Graph
  • Assembly Graph
  • Function Graph
  • Class Graph
  • Call Graph

Its an excellent tool for detecting memory leaks in managed code.

Other Posts

Tuesday, April 24, 2007

* Visual Studio Tip : How to change the default assembly information

New project creation in Visual Studio takes place based on Project Templates provided by Visual Studio or custom templates created.

When we create a new console application using the default project template provided by Visual Studio, the assembly.info is generated by default with some data like Company & Copyright information which is populated using information provided at time of installation.

If you want to change this default generated data, here is the trick.

The default project templates are stored in equivalent of following folder in Visual Studio 2005 installation area :

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates.

Suppose if you want to change the default values for C# console application, change the assembly.info file located in following folders:

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\ConsoleApplication.zip

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplatesCache\CSharp\Windows\1033\ConsoleApplication.zip

Other Posts

Monday, April 23, 2007

* Tool : MSIL Disassembler (Ildasm.exe)

Ildasm is one of the most frequently used tool by .NET community. It comes as part of the .net sdk since the very beginning.

The main purpose of this tool is to convert the portable executable (PE) file into readable and compilable MSIL code.

For beginners let me just explain few things :

  • MSIL : Microsoft Intermediate Language. When you compile your .net source code it gets converted to MSIL which is a platform independent language. The resultant exe or dll which you get contains the MSIL which gets compiled to native code at runtime.
  • PE File : The exe or dll file which you get after compilation of .net source code or MSIL code is called portable executable file which contains MSIL plus metadata about types and external dependencies which make PE an independent,self-describing entity and can be executed by runtime.

Ildasm supports both console and rich UI interface. The rich UI interface is the one most commonly used and is very useful for seeing following contents of an assembly :

  • Types in that assembly with full qualified names.
  • Methods and signatures available in various types.
  • Access modifiers of various types.
  • Version of that assembly.
  • Detecting if its strong named
  • External assemblies to which it references to including their version number.

In console mode Ildasm supports various other advanced options. The output in the console mode can be saved to a file in rtf , text or html format.

The other advanced options supported are :

  • /linenum : includes references to original source files
  • /source : show original source lines as comments
  • /html : produces output in html format.

The unrestricted output file containing MSIL generated by Ildasm can be given as input directly to MSIl Assembler Tool (Ilasm.exe) which will generate PE back again from which MSIL was generated.

Ildasm can also be used to check if the exe or dll file is managed or not. For unmanaged files it displays a message that no valid common language header found.

Add to : del.icio.us    Digg this    Technorati

Other Posts

Friday, April 20, 2007

* Tutorial : Policy Injection Application Block - Enterprise Library

To get overview of Policy Injection Application Block (PIAB) pls read following post.

In this tutorial i will cover the steps required to use/integrate PIAB into an application. For sample i will be integrating PIAB into a console application.

Let's consider a following sample application :

using System;
using System.Collections.Generic;
using System.Text;

namespace PIAB
{
class Program
{
static void Main(string[] args)
{
TargetClass tc = new TargetClass();
tc.SayHello();
}
}

class TargetClass
{
public void SayHello()
{
Console.WriteLine("Hello from Target Class");
}
}
}


Now suppose in this we want to track the number of method calls on instances of TargetClass instances. The PIAB helps you in doing all this without writing the tracking code in methods. Let us enable the above code for PIAB integration. Our objective is to log the method calls on TargetClass in event logs using Logging Application Block.





  • Add references to following assemblies :



    • Microsoft.Practices.EnterpriseLibrary.Common

    • Microsoft.Practices.EnterpriseLibrary.PolicyInjection

    • Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers

    • Microsoft.Practices.ObjectBuilder


  • Import the following namespaces :



    • Microsoft.Practices.EnterpriseLibrary.PolicyInjection

    • Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers


  • Derive TargetClass from MarshalByRefObject

  • Use the Create method of PIAB to create new instance of TargetClass instead of using new.

  • The modified code will look like following :
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers;

namespace PIAB
{
class Program
{
static void Main(string[] args)
{
TargetClass tc = PolicyInjection.Create<TargetClass>();
tc.SayHello();
}
}

class TargetClass : MarshalByRefObject
{
public void SayHello()
{
Console.WriteLine("Hello from Target Class");
}
}
}




  • Add the application config file to the application if its not added already.

  • Open the app config file using Enterprise Library Configuration Tool.

  • Add PIAB block to the app config file.

  • In PIAB section add a new policy and say name it 'SamplePolicy'.

  • In the Matching Rules section add a 'Type Matching Rule'. As we are trying to track method calls on a type and hence this rule.

  • Set the value of property Matches to full type name which is 'PIAB.TargetClass'.

  • We are through with the rule setting. Now we need to create handler which should get executed whenever the rule executes to true.

  • Add a new 'Logging Handler' in the Handlers section.

  • Set the various values of parameters in Logging Handler section as following:



    • AfterMessage - Ends

    • BeforeMessage - Starts

    • LogBehaviour - BeforeAndAfter


  • As we are using logging handler, you will have to add Logging application block also to the config file. The default options will log message in event viewer.

  • After setup the PIAB section of app.config file will look like following :
<policyInjection>
<policies>
<add name="SamplePolicy">
<matchingRules>
<add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.TypeMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Type Matching Rule">
<matches>
<add match="PIAB.TargetClass" ignoreCase="true" />
</matches>
</add>
</matchingRules>
<handlers>
<add logBehavior="BeforeAndAfter" beforeMessage="Starts"
afterMessage="Ends" eventId="0" includeParameterValues="true"
includeCallStack="false" includeCallTime="true" priority="-1"
severity="Information" type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.LogCallHandler, Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Logging Handler" />
</handlers>
</add>
</policies>
</policyInjection>




  • Build and execute the application.

  • You will notice two messages in Application event logs, One with 'Starts' message and other with 'Ends' message.

  • If you call the 'SayHello' method again, there will be another two messages.


PIAB is a highly customizable block and any number of Matching rules and handlers can be created.



Other Posts



* Orcas and .NET 3.5 Beta 1 Released

Visual Studio Team has announced the first beta release of next version of Visual Studio code named Orcas and .NET 3.5.

Currently its available only for MSDN subscribers but soon be available for everyone.

You can check more details on following link.

Other Posts

Thursday, April 19, 2007

* Enterprise Library : Policy Injection Application Block - An Overview

Policy Injection Application Block (PIAB) is a newly introduced app block in Enterprise library 3.0.

Enterprise Library assist in Aspect-Oriented software development by providing application blocks which solves common problems across layers of an application.

PIAB helps in aggregating these blocks and apply them to the application execution thread using configurable policies without requiring to call individual blocks from app code.

The main objectives of this block are :

  • Ability to apply policies to type instances at runtime based on configurable policies which can be changed without changing code.
  • Ability to build custom handlers and matching rules for applying policies.

Some of the common scenarios where PIAB can be used are :

  • Logging Method invocations
  • Handling exceptions
  • Validating Parameter Values
  • Caching Method results
  • Measuring Target Method Performance

The main steps in using PIAB are :

  • Identifying the Object which needs to be intercepted and checking if it is interceptable. For Object to be interceptable it must meet one of the following conditions:
    • Class must be derived from MarshalByRefObject
    • Class must implement a known interface.
  • Add the PIAB block to the app config file using the Enterprise Library tool
  • Create a policy which will be applied to the application.
  • Within policy create matching rules. There are some matching rules which come with block like assembly matching rule, Member name matching rule, etc. Custom matching rules can also be developed.
  • Specifying the handlers to be executed in case rules matched. There are some default handlers which come with PIAB like authorization handler, logging handler, etc. Custom handlers can also be developed.
  • Creating or Wrapping the target instances using the methods provided by PIAB to add a handler pipeline.

Apart from specifying in config file, handlers can also be applied using attributes provided by PIAB which makes sure that handlers get executed in all circumstances.

In my next post on this I will cover a tutorial on how to use PIAB.

Other Posts

Wednesday, April 18, 2007

* Is Dw20.exe troubling you ?

Dw20.exe is a Windows Error Reporting tool which detects & collects information whenever any program crashes or stops responding. It then gives users the option of sending the report directly to Microsoft.

Yesterday while profiling an asp.net application, Dw20.exe used to start and use 80% of the CPU. Due to overall high CPU usage, computer stopped responding.

The reason behind this observation is that asp.net worker process was crashing because of some reason and Dw20.exe was detecting it and trying to collect that information, but because the machine was not powerful it was getting saturated. The kind of observation is more common on low end machine.

If you also face this issue, there is a way of disabling error reporting tool temporarily.

Pls do the following steps:

  1. Go to control panel.
  2. Click/Double Click System.
  3. Go to Advanced Tab.
  4. Click Error Reporting.
  5. Now you can select ' Disable Error Reporting' & Press 'OK'.

Other Posts

Tuesday, April 17, 2007

* Performance Analysis/Tuning of ASP.NET Application

These days I am working on analyzing and tuning an asp.net web application.

Its basically a n-tier application based on Front-Controller pattern and very similar to MVC pattern. The communication between web and app tier is using Remoting, where the remote components are hosted on IIS 6.0. Its a session aware application. I am trying various deployment options available and publish the results around next week. I am sure results will guide readers in deciding the deployment scenarios.

Some of the comparison I will be publishing are :

  • Debug & Release Builds
  • InProc & State Server
  • Remoting & No Remoting

Apart from this I will also publish a tutorial about an excellent tool called VSProfiler used for analyzing performance of .NET applications.

Other Posts

Monday, April 16, 2007

* 'TOOLS' Section added

The various tools accompanying the framework are one of the strongest feature of Microsoft.NET technology.

I will be covering most of the tools here with sample usage. So, i have added a new section in right sidebar on tools.

Other Posts

* Announcing 'Microsoft Silverlight'

Dear Community,

Check out the new 'Microsoft Silverlight' website. This is the new brand name for WPF/E framework.

Silverlight is a cross-browser, cross platform plug-in for delivering the next generation of media experiences and rich interactive applications (RIAs) for web.

Other Posts

Friday, April 13, 2007

* Tool : XML Schema Definition Tool (Xsd.exe)

XSD.exe which comes as part of .net framework is mainly used to generate XML schemas or .net classes based on XML schema.

Some of the generations possible with this tool are :

  • XDR -> XSD : generates xml schema based on xml data reduced schema
  • XML -> XSD : generates xml schema based on xml data file
  • XSD -> Dataset : generates code of dataset based class which can be used to read xml data compliant to input xsd using System.Data.DataSet.ReadXml
  • XSD -> Classes : generates code of classes which can be used to read and write xml data using System.Xml.Serialization.XmlSerializer
  • Classes -> XSD : generates xml schema for types in a runtime assembly

 Lets create a sample xml data file and work on it using xsd tool.

Consider the following xml data file EmployeeList.xml:

<EmployeeList>
<Company ID="1">
<Employee>Employee11</Employee>
<Employee>Employee12</Employee>
<Employee>Employee13</Employee>
</Company>
<Company ID="2">
<Employee>Employee21</Employee>
<Employee>Employee22</Employee>
<Employee>Employee23</Employee>
</Company>
<Company ID="3">
<Employee>Employee31</Employee>
<Employee>Employee32</Employee>
<Employee>Employee33</Employee>
<Employee>Employee34</Employee>
</Company>
</EmployeeList>


Execute XSD.exe on the xml data file:



> XSD EmployeeList.xml



The resultant xsd file EmployeeList.xsd will be :

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="EmployeeList" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="EmployeeList" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Company">
<xs:complexType>
<xs:sequence>
<xs:element name="Employee" nillable="true" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent msdata:ColumnName="Employee_Text" msdata:Ordinal="0">
<xs:extension base="xs:string">
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="ID" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>


Now we can generate code of classes using the same tool and xsd generated which can be used to read and write xml data using System.Xml.Serialization.XmlSerializer.



>xsd EmployeeList.xsd /classes



The code generated is :

//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.42.
//


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class EmployeeList {

private EmployeeListCompany[] itemsField;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Company", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public EmployeeListCompany[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmployeeListCompany {

private EmployeeListCompanyEmployee[] employeeField;

private string idField;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Employee", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public EmployeeListCompanyEmployee[] Employee {
get {
return this.employeeField;
}
set {
this.employeeField = value;
}
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ID {
get {
return this.idField;
}
set {
this.idField = value;
}
}
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmployeeListCompanyEmployee {

private string valueField;

/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}


The sample usage of this class can be as below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace XSD_TOOL_SAMPLE
{
class Program
{
static void Main(string[] args)
{
EmployeeList empList;
XmlSerializer xs = new XmlSerializer(typeof(EmployeeList));
FileStream fs = new FileStream(@"D:\Vikas\vikas\tech\code\CSharp\XML\EmployeeList.xml",FileMode.Open);
empList = (EmployeeList)xs.Deserialize(fs);
Console.WriteLine(empList.Items[0].Employee[0].Value);
}
}
}


The output for this will be the value of first Employee element.



Output : Employee11



More detailed documentation on xsd tool can be found on msdn.



Other Posts



* All about .NET

Dear Community ..  check out the following url :

http://www.dotneturls.com/ . It aggregates the most important links related to .NET technology.

My blog's url has been recently added to the ' Featured .NET Blogs' section.

Other Posts

Tuesday, April 10, 2007

* Auto Performance Tuning in ASP.NET 2.0

With ASP.NET 2.0, the process model (processModel) section of machine.config comes with default value of autoconfig="true".

This means that the tuning parameters will be set automatically by ASP.NET engine based on machine configuration.

The parameters considered for auto tuning are :

  • The maxWorkerThreads attribute.

  • The maxIoThreads attribute.

  • The minFreeThreads attribute of the httpRuntime element.

  • The minLocalRequestFreeThreads attribute of the httpRuntime element.

  • The maxConnection attribute of the <connectionManagement> Element (Network Settings) element.

    Their values are determined based on logic mentioned at following link.

    Other Posts

  • How to create Project Item Templates
  • Accelerating development using Visual Studio Templates
  • Visual Studio : How to create temporary projects
  • Reading & Writing XML data
  • Overview of XML support in .NET Framework
  • Creating a context menu item for folders
  • Monday, April 09, 2007

    * Caching Application Block : Usage Notes on Backing Store

    The walkthrough on how to use Caching Application Block can be downloaded from following link.

    Some important points to consider while using Caching Application Block (CAB) of Enterprise Library:

    • By default & always CAB stores data in-memory.
    • It can be configured to store data in some persistent storage also.
    • Out of the box, CAB comes with two persistent backing stores : Isolated Storage & Database Caching Storage.
    • CAB can be extended to support additional backing stores.
    • Isolated storage is suitable for small data.
    • Database caching storage is suitable for large data but read-only data for shared scenarios. 

    Other Posts

    Friday, April 06, 2007

    * Enterprise Library 3.0 : Released

    Microsoft's P&P team has released the final version of Enterprise Library 3.0.

    It can be downloaded from here.

    The main additions to this version are :

    • Validation Application Block
    • Policy Injection Application Block
    • Visual Studio Integrated config editor
    • WCF integration

    Support both .NET 2.0 and 3.0

    Other Posts

    Monday, April 02, 2007

    * Tool : XML Notepad

    XML Notepad is a UI based XML browsing & editing tool built using .NET framework 2.0.

    It is developed by XML tools team at Microsoft.

    The main features of this tool are :

    • Tree View synchronized with Node Text View for quick editing of node names and values.
    • Real time XML schema validation with errors and warning shown.
    • Intellisense based on schema attached.
    • Mapping of Namespace URIs and file names containing schemas.
    • XML difference tool
    • XSLT transformation output.
    • Drag/Drop & Copy/Paste feature for nodes.

    It can be downloaded from following location.

    ~tata & take care~

    Other Posts