ramlicious Blogs by Tina & Prabhu

November 23, 2011

Creating Custom Code Snippets in Visual Studio

Filed under: .NET,C#,Programming,Visual Studio,XML — Prabhuram @ 7:12 pm

Definitely Visual Studio Code Snippets save a lot of development time. It makes magic by replacing a small code snippet with a code block. Say for example, by simply typing ctor and pressing tab generates a default constructor code for you. In this article I will show how easy it is to add a custom code snippet. Before creating one, we will study an existing code snippet that you already have. You can view the list of code snippets by opening Visual Studio and opening Code Snippet Manager… in the Tools menu. You can see the code snippet called ctor listed under Visual C#. Simply copy the location of the .snippet file from the window and open the XML snippet file in Notepad.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>ctor</Title>
			<Shortcut>ctor</Shortcut>
			<Description>Code snippet for constructor</Description>
			<Author>Microsoft Corporation</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal Editable="false">
					<ID>classname</ID>
					<ToolTip>Class name</ToolTip>
					<Function>ClassName()</Function>
					<Default>ClassNamePlaceholder</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $classname$ ()
	{
		$end$
	}]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

The three parts that the learner should be interested in are:

  • Header, that informs about the shortcut key and the author
  • Literal Declarations, list of literals that are part of the snippet. You can think of the literals that appear when you use the prop (property) code snippet that requests for changes to the property name or simply as seen in this example it executes a Function to get the value.
  • Code, which is the information about the language and the code that the snippet will be expanded to (also note the SnippetType in Header)
Now you can create endless number of snippets with your imagination. I have created one for the sake of the reader. This code snippet creates a typed DataTable that is created from scratch. So this DataTable can be created by the developer without the use of Schema. All that the developer has to do is to add changes to the TODO part of the code.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

    <Header>
      <Title>Typed DataTable</Title>
      <Shortcut>tdt</Shortcut>
      <Description>Code snippet for generating Typed DataTable</Description>
      <Author>Prabhuram Venkatesan</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>ObjectName</ID>
          <ToolTip>Prefix to the Class Name</ToolTip>
          <Default>Class</Default>
        </Literal>
        <Literal>
          <ID>DBColumn1</ID>
          <ToolTip>Column Name in the Database/T-SQL Query</ToolTip>
          <Default>db_column_1</Default>
        </Literal>
        <Literal>
          <ID>RowColumn1</ID>
          <ToolTip>DataRow property name for db_column_1</ToolTip>
          <Default>RowColumn1</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
using System.Data;

//Auto-generated code for Typed DataTable
public class $ObjectName$Table : DataTable
{
  public $ObjectName$Table()
    :base()
  {
    //TODO: Add all the remaining DB columns names
    Columns.Add(new DataColumn("$DBColumn1$", typeof(string)));
  }
  protected override Type GetRowType()
  {
    return typeof($ObjectName$Row);
  }

  protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
  {
    return new $ObjectName$Row(builder);
  }
  public $ObjectName$Row this[int idx]
  {
    get { return ($ObjectName$Row)Rows[idx]; }
  }

  public void Add($ObjectName$Row row)
  {
    Rows.Add(row);
  }
  public new $ObjectName$Row NewRow()
  {
    $ObjectName$Row row = ($ObjectName$Row)NewRow();
    return row;
  }
}
public class $ObjectName$Row : DataRow
{
  internal $ObjectName$Row(DataRowBuilder builder)
    : base(builder)
  {
    //TODO: Assign default values to all the properties
    $RowColumn1$=String.Empty;
  }

  //TODO: Add all the columns you want as part of a Row
  //      Map the DB column name to a property
  public string $RowColumn1${
    get {return (string)base["$DBColumn1$"];}
    set {base["$DBColumn1$"]=value;}
  }
}
        ]]>
      </Code>
    </Snippet>

  </CodeSnippet>
</CodeSnippets>

And now with this, typing tdt and Tab will generate the following code for you.


using System.Data;

//Auto-generated code for Typed DataTable
public class RoleTable : DataTable
{
    public RoleTable()
        : base()
    {
        //TODO: Add all the remaining DB columns names
        Columns.Add(new DataColumn("db_column_1", typeof(string)));
    }
    protected override Type GetRowType()
    {
        return typeof(RoleRow);
    }

    protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
    {
        return new RoleRow(builder);
    }
    public RoleRow this[int idx]
    {
        get { return (RoleRow)Rows[idx]; }
    }

    public void Add(RoleRow row)
    {
        Rows.Add(row);
    }
    public new RoleRow NewRow()
    {
        RoleRow row = (RoleRow)NewRow();
        return row;
    }
}
public class RoleRow : DataRow
{
    internal RoleRow(DataRowBuilder builder)
        : base(builder)
    {
        //TODO: Assign default values to all the properties
        RowColumn1 = String.Empty;
    }

    //TODO: Add all the columns you want as part of a Row
    //      Map the DB column name to a property
    public string RowColumn1
    {
        get { return (string)base["db_column_1"]; }
        set { base["db_column_1"] = value; }
    }
}

September 14, 2011

OData and JSON

Filed under: JSON,OData,Visual Studio,WCF,XML — Prabhuram @ 1:18 pm

In my last two article which talks about developing WCF data services, you would have noted that when you browsed the .svc page (http://localhost/ODataSampler.Web/MusicAlbum.svc/) from the browser the XML appears something like this:

<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<service xml:base="http://localhost/ODataSampler.Web/MusicAlbum.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">
  <workspace>
    <atom:title>Default</atom:title>
    <collection href="Albums">
      <atom:title>Albums</atom:title>
    </collection>
  </workspace>
</service>

This is the AtomPub format (yes the same format weblogs are distributed). OData supports AtomPub and JSON. In this article we will quickly see how JSON format. In this case, I will use Netflix source. I’ve created a very simple HTML page to demostrate the power of OData.

HTMLPage.htm (976.00 bytes)

Simply click open the link and open the file in a browser, and check out what happens. All that the file contains is a simple call to pull the JSON data from Netflix. And you can also see that HTML only has very simple JQuery calls to pull the data. And when you view the source, it doesn’t have any movie data on the client side, and so everything happens on the fly.

Here is the URI used in the HTML file

http://odata.netflix.com/Catalog/Titles?$filter=ReleaseYear%20eq%202011&$format=json&$callback=?&$orderby=Name

pulls the movie titles released in 2011, and the requested data format is json. So if you just click open the link you can see the actual json data.

June 8, 2011

Formatting XML files with indentation

Filed under: XML — Prabhuram @ 8:30 am

Here is a simple object that can process an unindented xml file to a properly formatted XML file. Simple make an object instance like this:

new XmlFormatter("C:\myXMLfile.xml").Process(); 

Download and use it: XmlFormatter.zip (691.00 bytes)

October 28, 2010

XML to CSV using XSL and VBScript

Filed under: Scripting,Visual Studio,XML — Prabhuram @ 7:35 am

We have seen XML Transformation using XSL: A sample before to transform an XML to a HTML using XSLT. This time we will see how to convert an XML to a CSV file.

The output will be a simple tab separated list with carriage return as the delimiter like this:

Empire Burlesque        Bob Dylan       USA
Roja    AR Rehman       India
Eagles  Eagles  USA

We will use the same catalog.xml which we used in our earlier example. And our XSL is going to generate a text instead of html which can done by this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="text"/>
	<xsl:strip-space elements="*"/>
	<xsl:param name="separator" select="'&#9;'"/>
	<xsl:param name="line-separator" select="'&#13;&#10;'"/>

	<xsl:template match="/">
		<xsl:for-each select="catalog/cd">
			<xsl:value-of select="title"/>
			<xsl:value-of select="$separator"/>
			<xsl:value-of select="artist"/>
			<xsl:value-of select="$separator"/>
			<xsl:value-of select="country"/>
			<xsl:value-of select="$separator"/>
			<xsl:value-of select="$line-separator"/>
		</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>

A simple vbscript will do the trick to transform the xml to a file.

 

The complete code is available here: catalog-csv.zip (1.05 kb)

April 9, 2010

Open XML

Filed under: XML — Prabhuram @ 9:14 am

Open XML is an open ECMA 376 standard and is also approved as the ISO/IEC 29500 standard that defines a set of XML schemas for representing spreadsheets, charts, presentations, and word processing documents. Microsoft Office Word 2007, Excel 2007, and PowerPoint 2007 all use Open XML as the default file format.

The Open XML file formats are useful for developers because they use an open standard and are based on well-known technologies: ZIP and XML.

The Open XML SDK 2.0 for Microsoft Office is built on top of the System.IO.Packaging API and provides strongly typed part classes to manipulate Open XML documents. The SDK also uses the .NET Framework Language-Integrated Query (LINQ) technology to provide strongly typed object access to the XML content inside the parts of Open XML documents.

The Open XML SDK 2.0 simplifies the task of manipulating Open XML packages and the underlying Open XML schema elements within a package. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages, so you can perform complex operations with just a few lines of code.

The tools package contains the Open XML SDK v2.0 Productivity Tool for Office and the documentation for the Open XML SDK v2. The Open XML SDK 2.0 Productivity Tool for Microsoft Office provides a number of features designed to improve your productivity and accelerate your learning while working with the SDK and Open XML files. Features include the ability to generate Open XML SDK 2.0 source code based on document content, compare source and target Open XML documents to reveal differences and to generate source code to create the target from the source, validate documents, and display documentation for the Open XML SDK v2.0, the ECMA376v1 standard, and the Microsoft Office implementation notes.

Download SDK here.

March 16, 2010

Using (Java Script Object Notation) JSON in .NET

Filed under: C#,JSON,Visual Studio,XML — Prabhuram @ 3:39 am

In my earlier blog (Translation Methods by Google and Microsoft), I mentioned that Google will return a JSON string. Today we will see how to deserialize JSON string to a .NET object. I will take the same JSON string which was given as an example in my old blog:

{“responseData”: {“translatedText”:”aquí es una prueba que quería traducir”}, “responseDetails”: null, “responseStatus”: 200}

We will do this by creating a class (in .NET 3.5) called  myJson:


Before writing the class, the project should refer to the following assemblies:


and note the Response object that will have the object representation of the Json string:


Now simply call the Deserialze() function like this:

Find the complete code here: myJson.zip (689.00 bytes)

Key Characteristic Differences between XML and JSON

Filed under: C#,JSON,Visual Studio,XML — Prabhuram @ 2:24 am

 

Characteristic XML JSON
Data types Does not provide any notion of data types. One must rely on XML Schema for adding type information. Provides scalar data types and the ability to express structured data through arrays and objects.
Support for arrays Arrays have to be expressed by conventions, for example through the use of an outer placeholder element that models the arrays contents as inner elements. Typically, the outer element uses the plural form of the name used for inner elements. Native array support.
Support for objects Objects have to be expressed by conventions, often through a mixed use of attributes and elements. Native object support.
Null support Requires use of xsi:nil on elements in an XML instance document plus an import of the corresponding namespace. Natively recognizes the null value.
Comments Native support and usually available through APIs. Not supported.
Namespaces Supports namespaces, which eliminates the risk of name collisions when combining documents. Namespaces also allow existing XML-based standards to be safely extended. No concept of namespaces. Naming collisions are usually avoided by nesting objects or using a prefix in an object member name (the former is preferred in practice).
Formatting decisions Complex. Requires a greater effort to decide how to map application types to XML elements and attributes. Can create heated debates whether an element-centric or attribute-centric approach is better. Simple. Provides a much more direct mapping for application data. The only exception may be the absence of date/time literal.
Size Documents tend to be lengthy in size, especially when an element-centric approach to formatting is used. Syntax is very terse and yields formatted text where most of the space is consumed (rightly so) by the represented data.
Parsing in JavaScript Requires an XML DOM implementation and additional application code to map text back into JavaScript objects. No additional application code required to parse text; can use JavaScript's eval function.
Learning curve Generally tends to require use of several technologies in concert: XPath, XML Schema, XSLT, XML Namespaces, the DOM, and so on. Very simple technology stack that is already familiar to developers with a background in JavaScript or other dynamic programming languages.

JSON is a relatively new data exchange format and does not have the years of adoption or vendor support that XML enjoys today (although JSON is catching up quickly). The following table highlights the current state of affairs in the XML and JSON spaces.

Support Differences between XML and JSON

Support XML JSON
Tools Enjoys a mature set of tools widely available from many industry vendors. Rich tool support—such as editors and formatters—is scarce.
Microsoft .NET Framework Very good and mature support since version 1.0 of the .NET Framework. XML support is available as part of the Base Class Library (BCL). For unmanaged environments, there is MSXML. None so far, except an initial implementation as part of ASP.NET AJAX.
Platform and language Parsers and formatters are widely available on many platforms and languages (commercial and open source implementations). Parsers and formatters are available already on many platforms and in many languages. Consult json.org for a good set of references. Most implementations for now tend to be open source projects.
Integrated language Industry vendors are currently experimenting with support literally within languages. See Microsoft's LINQ project for more information. Is natively supported in JavaScript/ECMAScript only.

Note   Neither table is meant to be a comprehensive list of comparison points. There are further angles on which both data formats can be compared, but we felt that these key points should be sufficient to build an initial impression.

Source: An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET

February 12, 2010

Simple XML transformation for a Dotnet XML documentation file

Filed under: C#,Visual Studio,XML — Prabhuram @ 5:17 pm

Here is a stylesheet that will be useful to view an XML documentation file as a simple HTML page.

All you need to do is add this line: 

<?xml-stylesheet type="text/xsl" href="Documentation.xslt"?>

as the second line in the XML documentation file. If your path to Documentation.xslt is different, then give the full path to the XSLT file. Download this transformation file from here. Also given is a  sample documentation output.

February 5, 2010

Logger tool to write messages to Windows Event Viewer and Text Files

Filed under: C#,Visual Studio,XML — Prabhuram @ 12:46 pm

This time we will see another assembly which can be used in a dotnet application for logging. These objects attached provides interfaces to write application logs either to a windows event viewer or to a text file or to both.

All you need to do is refer the assembly (prabhuram.com.Logging.zip (2.96 kb)) and add configuration settings to the web.config or app.config file (similar to log4net).


and simply call the Logger.Writeline() method from your code.

new Logger().Writeline(ex.Message);

So, if you have the section eventLog in web.config, you will see event message like the one below:

Find the complete source code here: prabhuram.com.Logging.source.zip (3.84 kb)

January 29, 2010

Updated: Writer object for creating Row/Column XML from flat files

Filed under: C#,Visual Studio,XML — Prabhuram @ 10:34 am

I know that my object provided in my last article for XMLRecordWriter was dirty. So I spent some time to clean it and add more clarity. Here is an updated version which supports different column names:

 

You can find the source code here XMLRecordWriter.cs (2.72 kb).All you need to do is call the object like this: Program.cs (1.43 kb).

Older Posts »

Powered by WordPress