Memory and Storage Convertor

Posted by Techie Cocktail | 11:32 AM | | 0 comments »

Came across this handy convertor tool - http://www.csgnetwork.com/memconv.html

ADO.Net Frequently Asked Questions

Posted by Techie Cocktail | 10:56 PM | | 0 comments »

What is the difference between ADO and ADO.Net?
What are the different categories of classes in ADO.Net?
What is the difference between clone() and copy() method of a Dataset?
What is connection pooling?
What is a diffgram?
What is CommandBuilder?
What is the difference between Optimistic and Pessimistic locking?
What are various components of a DataTable?
What are the different RowState transitions in DataRow?
What are the different DataRow versions?
How do determine the current version of a DataRow?
What is a DataReader?
How to iterate through rows in a DataReader?
What are the advanatages/disadvantages of using a DataReader?
How to check if a DataReader is closed or open?
What is a Dataset?
How to Read/Write XML using a Dataset?
What is the use of AcceptChanges() method of Dataset?
What is the use of Update() method of Dataset?
What is a DataAdapter?
How to load the generated DataSet using DataAdapter?
How can we use a Stored Procedure in ADO.Net?
What is Dataview? What is it used for?
How to perform a transaction cycle in ADO.Net?

C# Frequently Asked Questions

Posted by Techie Cocktail | 11:19 PM | | 1 comments »

Below are some of the most commonly asked questios in C#:

Q. What is the difference between a const and readonly in C#?
A. Refer: Const vs Readonly

Q. What is the difference between out and ref keywords?
A. Refer: Difference between out and ref parameters

Q. What is the difference between an Array & ArrayList?
A. Refer: Difference between an Array and ArrayList

Q. Which namespace is the base class for all .Net Class Libraries?
A. System.Object

Q. What is boxing and unboxing?
A. Refer to: Boxing and Unboxing in C#

Q. What is the difference between a thread and a process?
A. Refer: Thread vs Process

Q.What are the different access modifiers in C#?
A. Below are the available access modifiers and their scope details.

a. Public: Access not limited.
b. Protected: Access limited to the containing class or types derived from the containing class.
c. Internal: Access limited to current project.
d. Protected Internal: Access limited to the project or types derived from the containing class.
e. Private: Access limited to the containing type.

Q. Strings are immutable, what does it mean?
A. Strings are immutable, it means if strings are once created, they cannot be changed. Although some string operation methods seem to modify string content, but .Net framework creates a new string with the new value. The original string remains unchanged.

Refer: MSDN for more details.

Q. What are User-defined types? How to create them?

Q. What are Partial Classes?
A. Refer to: Partial Class in .Net

Q. What is the difference between Finalize & Dispose?
A. Refer: Finalize vs Dispose

Q. What is a ternary operator?
A. Refer to: Ternary Operator

Q. What is the difference between CopyTo() and Clone() methods in System.Array?
A. Clone() creates another array with the exact copy as original array. It returns an exact length array. CopyTo() copies the elements from the original array to an another existing array starting at the specified existing array index.

Q. What is a Windows Service? What are the steps to create it?
A. Windows Service is an executable that runs at the background in its own session and performs specific functions.

Refer this link for: Steps to Creating a Windows Service

Q. What are generics?
Q. What is an Event? How to raise it?

Q. What is a delegate?
A. Refer to: Delegates in C#

Q. What is a multicast delegate?
Q. What is Type Forwarding?

Q. What is the difference between a Struct and a Class?
A. Refer: Struct vs Class

Q. What is the difference between method overloading and overriding?
A. Refer: Overloading vs Overriding

Q. What is the difference between an Abstract Class and Interface?
A. Refer: Abstract Class vs Interface

Q. What are sealed classes in c#?
A. Sealed classes are used to restrict inheritance. In C#, the sealed modifier is used to make the class as sealed. No other class can be derived using the sealed class.

A compile-time error occurs if the sealed class is specified as the base class of a class.


// Sealed class
sealed class ClassA
{
//define data members & methods.
}



Read on Sealed Methods in this nice article: Sealed Methods

Q. What are indexers? How they are different from properties?
A. Refer to: Indexers in c#

Q. Can abstract class have non-abstract methods?
A. Yes. The abstract class can contain abstract and non-abstract methods.

Q. What is inheritance?
A. Refer: Inheritance in C#

Q. What is polymorphism?
A. Refer: Polymorphism in C#

Q. What is the difference between typed and instance constructor?
A. Refer: Difference between Typed and Instance Constructor

Q. How to create and send HTML E-Mail Message?
A. The class used to create an E-Mails in .net is MailMessage. It is
contained in System.Web.Mail namespace. Check the below code to create
and send HTML emails using c#.

MailMessage testMail = new MailMessage();
testMail.To = "receiver@test.com";
testMail.From = "sender@test.com";
testMail.Subject = "Hello World!";
testMail.BodyFormat = MailFormat.Text;
testMail.Body = "Check out the attachment!";
testMail.Attachments.Add(new MailAttachment("@c:\attachement.zip"));
SmtpMail.Send(testMail);

Q. What are the types of collections available in .net?
A. Refer: Types of collections in .net

Q. What are Sequential Lists? What are its types?
A. Refer: Sequential Lists in C#

Q. What is Serialization?
Q. How to Serialize and Deserialize an object (using Binary & XML Formatter)?
Q. What are different types of serialization? Which one to choose & when?
Q. What are different types of attributes used in serialization using Binary Formatter?
Q. What are different types of attributes used in serialization using XML Formatter?
Q. What are the different Serialization Events?

Q. What is an Application Domain?
Q. How to load/unload assemblies in an Application Domain?

Q. What is an Event Log? Q. How to Create/Delete an Event Log? Q. How to Read/Write from an Event Log?
A. Refer to: Managing EventLogs in Event Viewer using .Net

Q. What is debugging? What are various debugging techniques that help debugging an issue quickly?
A. Refer: Debugging and its techniques

Q. What is MSMQ? How to create queues? How can applications send and receive messages from queues?
A. Refer: Message Queuing - MSMQ

Q. What are different logical and physical layers in n-tier architectures?
A. Logical Layers:
1. UI - This layer is a presentation layer with which the client interacts.
2. MT - This is a Middle-Tier layer which contains the main code & business functionality.
3. DB - This is a database layer that contains the actual data.

Physical Layers:
1. UI - This could be either a browser (web application), windows client (windows application), dos windows (console based application) or any other interface with which users can interact with.
2. MT - This could be DLLs/Libraries, WebServices, WCF etc.
3. DB - This could be SQL Server, Oracle or some other database.

Linq to XML - Introduction

Posted by Techie Cocktail | 1:24 AM | | 0 comments »

Linq to XML is the modern approach to programming with XML using any .NET Languages. It provides an in-memory XML programming interface that allows querying XML data using SQL-like queries thereby making developers life easy. It also reduces the code size as compared to the old approach.

In the old approach, one had to start with XMLDocument. Using the XMLDocument, create root XMLElement followed by using helper methods to append or create child elements which involved lot of code writing. Also to read/query XMLDocuments, one had to write XPATH queries to get the required data, the validation of which did not happened at compile time.

Using Linq to XML, life has become very easy with the introduction of simple-to-use XML tree creation objects. Also to get data from XDocument, one just have to use simple SQL-like queries having all the required methods to filter & get the required match data. The code size has reduced drastically, more readable and easy to understand.

In .Net 3.5 a new namespace called System.Xml.Linq contains all the classes for creating XML documents in any required format. Some of its members are as listed:

XAttribute – Represents an XML attribute.
XComment – Represents an XML comment.
XDeclaration - Represents an XML declaration.
XDocument - Represents an XML document.
XElement - Represents an XML element.
XName - Represents the name of the XElement or XAttribute
XNamespace - Represents an XML namespace.
XNode - Represents any XML node within an XML document(e.g.element,comment)

Lets see how to create an entire XML Document tree using a single statement.


XDocument doc =
new XDocument(
new XElement("Customer",
new XElement("FirstName", "Atul"),
new XElement("LastName", "Ashpalia")));

doc.save(@"d:\sample.xml");

File output:
<customer>
<FirstName>Atul</FirstName>
<LastName>Ashpalia</LastName>
</customer>

Now lets load this XML document in XDocument object from sample.xml file. Then retrieve the value of the FirstName and print it.
Note: We can also load the XML Document from a stream.

Code:
// Load from file.
XDocument customer = XDocument.Load(@"d:\sample.xml");

// Query the data and print the FirstName
var q = from c in customer
where c.Element("FirstName")
select c;

foreach (string name in q)
Console.WriteLine("First Name = {0}", name);

As seen above, the code to create XML Document and to query it looks much more simplified and easy compared to what the old approach had to offer us. Enjoy coding.

SQL Server Command List

Posted by Techie Cocktail | 10:20 AM | , | 0 comments »

Below are some useful TitBits when working with SQL Server. I would append this list quite often with more tips in future.

Please feel free to send in your tips to be published that would be helpful to others. You can post them on the comments part of this article below.

SQL Commands:

1. How can i get the local SQL Server Name?
SELECT @@SERVERNAME

2. How to get the list of .mdf (data files) & .ldf (log files) files of all databases and their details for an SQL Server?
SELECT * FROM SYS.MASTER_FILES

3. How to get the database id for a given database?
SELECT DB_ID('<Database_Name>')

4. How to check if a particular table exists in a database?
SELECT * FROM <Database_Name>..sysobjects WHERE NAME LIKE '<Table_Name>'

5. How to get only data file details of a particular database?
EXEC ('DBCC SHOWFILESTATS')

Note: Run this command by selecting the database for whose datafile details you want to view.

6. How to get the LogSpace details of all the database in a SQLServer?
EXEC('DBCC SQLPERF (Logspace)')

7. How to rename a database?
sp_renamedb 'oldname' , 'newname'
If the database is being used by someone, sp_renamedb will not work. In that case,
- first get the db to a single user mode using sp_dboptions.
- use sp_renamedb to rename the db.
- use sp_dboptions to change the db to the multi user mode.

8. How do i get information about the remote server?
sp_helpserver [server_name]

9. How can i see the text of a procedure, trigger, view, default, rule, integrity check constraint?
sp_helptext [object_name]

10. How can i get details on any SQL Server object (for eg. table)?
sp_help [table_name/ojbect_name]

11. How do i get the list of processes that currently hold locks?
sp_lock spid1 [,spid2] (you can check for multiple spid's)

where spid1, spid2 - is the SQL Server process ID number of a lock.

12. How can i get a SPID information about all SQL Server users and processes?
sp_who or sp_who2

13. How can i check the machine hard drive space details?
EXEC xp_fixeddrives

14. How can i get list of users in the current database?
EXEC sp_helpuser

15. How can i get the list of logins for each database?
EXEC sp_helplogins

16. How can i get the number of rows affected by the last statement in a stored proc?
SELECT @@ROWCOUNT

17. How do i get the space, index, row counts of a SQL Table?
EXEC sp_spaceused <table>

18. How do i get the list of stored procedures in a database?
SELECT [name] FROM sysobjects WHERE [type] = 'p'

19. How do i get the list of tables in a database?
SELECT [name] FROM sysobjects WHERE [type] = 'u'

20. How can i debug a stored procedure execution in a production environment?
Use SQL Profiler.

Write Log details to a text file C#

Posted by Techie Cocktail | 4:23 PM | | 0 comments »

Lot of times we are unable to detect an issue in the code. Below function can do logging for you in a text file in your application path.

Checkout.


static private void WriteLogsToTextFile(string logStr)
{
try
{
if (ConfigurationSettings.AppSettings["beginLogging"].ToString().Equals("true"))
{
if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
using (StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + logStr);
sw.Close();
}
}
else using (StreamWriter sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + logStr);
sw.Close();
}
}
}
catch (Exception ex)
{
//display error.
}
}

Split Function in SQL Server

Posted by Techie Cocktail | 1:43 PM | | 0 comments »

Did you ever want to split a comma/space/<any character> delimited long string?
In .Net we have the in-built split function available to perform this task.

Check this below function in SQL Server:


CREATE FUNCTION dbo.splitString(
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ' ' -- delimiter that separates items. Space in this case.
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN

SELECT @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))), @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END

IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO

-- This is how you would test
select * from splitString('This is a split function', ' ')

-- Output
This
is
a
split
function


References: http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci932171,00.html

Another concise coding feature in C# 3.0. Let’s see it using user-defined class and other using one of the .Net Collections. This feature demonstrates a new way to initialize a class or a collection.



a. Initializing a User defined class

Lets pick up the employee class example as defined in my whitepaper Auto-Implemented properties in C# 3.0. As we have the class ready lets initialize the object of employee class.



Traditional Approach



employee emp = new employee();

emp.Name = "John";

emp.Designation = "Senior";

emp.GetSalary();

double Sal = emp.Salary;





New Approach



employee emp = new employee { Name = "John", Designation = "Senior" };

emp.GetSalary();



As in the new approach, line 1, you can initialize the employee members (properties) at the time of instantiation. You don’t need to write extra lines of code as done in the traditional approach.



b. Initializing a List Collection



List employees = new List();

employees.Add(new employee{ Name="John", Designation="Junior"});



OR we can even concise it as this:



List employees = new List

{

new employee{ Name="John", Designation="Junior"}

};



So guys say bye to long codes, the future is going to be easier with these concise coding features.

Auto-Implemented Properties in C# 3.0

Posted by Techie Cocktail | 2:02 PM | | 0 comments »

Auto-Implemented Properties is one of the new features in C# 3.0. Let’s see what are they, how to implement them and how it makes our lives easy.

To create simple read-write, read-only properties in a class, you write many lines of code. The properties are public in nature and their underlying data are stored in private variables.

For example, check the below sample class having a few properties.


public class employee
{
private string _name;
private string _designation;
private double _salary;

public string name
{
get
{
return _name;
}
set
{
value = _name;
}
}

public string designation
{
get
{
return _designation;
}
set
{
value = _designation;
}
}

public double salary
{
get
{
return _salary;
}
}

public void GetSalary()
{
switch (designation)
{
case "Junior":
{
_salary = 2000;
}
break;
case "Senior":
{
_salary = 4000;
}
break;
case "Manager":
{
_salary = 10000;
}
break;
}
}
}


As you see in order to create a simple property we had to write extra lines of code. And if the class has 6-10 properties you would spend time writing those extra lines of code for each property.

This issue has been simplified by VS Team in C# 3.0 by introducing 'prop' (for 'read-write' property) and 'propg' (for 'read-only' property). In your code view, in your class, simply type 'prop' and hit tab twice to get your property created. Your property looks like this.


public string Name { get; set; } //read-write property
public double Salary { get; private set; } //read-only property


Just this one line of code. You do not have to create any private variable to store its underlying data. .Net takes care of it.


public class employee
{
public string Name { get; set; }
public string Designation { get; set; }
public double Salary { get; private set; }

public void GetSalary()
{
switch (Designation)
{
case "Junior":
{
Salary = 2000;
}
break;
case "Senior":
{
Salary = 4000;
}
break;
case "Manager":
{
Salary = 10000;
}
break;
}
}
}


The code size has reduced with the use of Auto-Implemented Properties. This has nothing to do with performance as the compiler would generate the same code as the previous traditional implementation. The benefits of using them are the approach towards encapsulation, save time to write the extra lines of code.

But,
if you wanted to implement some event notification or any code inside the property than just declaring a simple property, you would have to go back to the old implementation approach.

References:
a. Inside Microsoft
b. MSDN

Creating Windows Service - C#

Posted by Techie Cocktail | 1:36 PM | | 4 comments »

Creating a windows service is not a big deal. But as most people don’t often create windows service they tend to do some silly mistakes when they have to create one. Hence I thought of writing up a sample code demonstrating its basics.

Steps:
a. Create a new Windows Service Project. Go to File -> New -> Project and select 'Windows Service' Project template from Windows tab as shown in the figure.



b. The wizard creates for you Service1.cs by default.



c. Let’s see the default code view created by VS.



d. Now let’s add some functionality to this service. Most of the services have timers implemented in them so as to perform a particular task at regular intervals in the background. Lets add a timer and set to fire a method or an action at regular interval as set.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;

namespace MyService
{
public partial class MyFirstService : ServiceBase
{
private Timer _timer;

public MyFirstService()
{
InitializeComponent();

//instantiate the timer and set its interval to fire every one hour.
_timer = new Timer();
_timer.Interval = 3600000;

//perform the action immediately on service start.
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
}

void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Write a msg in a text file with the time at which the Elapsed event was raised.
WriteMsgToTextFile(string.Format("Hello: {0}", e.SignalTime.ToString()));
}

protected override void OnStart(string[] args)
{
//start the timer.
_timer.Start();
}

protected override void OnStop()
{
//stop the timer onStop
_timer.Stop();
}

private void WriteMsgToTextFile(string msg)
{
try
{
if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
using (StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
else using (StreamWriter sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
catch (Exception ex)
{
//Write Logs.
}
}
}
}


e. Now after the code is written successfully, it's time to install the service. For this you need to add the service installer to the project.

f. In the properties window as below, you would see an 'Add Installer' link at the bottom. Click on that to add the installer to your project.



g. This adds two objects 'ServiceProcessInstaller' & 'ServiceInstaller' as below.



h. Also you would have 'ProjectInstaller' files added to your Solution Explorer.



i. Installing the service: To install your windows service, go to the projects ‘bin’ directory. You will see the 'MyService' (in this case) application. Use the below command from your command line to install the service.

C:\Program Files\Microsoft Visual Studio 9.0\VC>
installutil E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

This install the service successfully. You can see your service installed by going to Start -> Run -> 'Services.msc', you would see your service.



To uninstall your service, use the '/u' switch as below.
installutil /u E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

Comments:
As seen in the SCM (Service Control Manager), the service appears as 'Manual'. This is because the startup type property of the ServiceInstaller was set to Manual.

Service Process Installer has 'Account' property which has values – 'LocalService', 'NetworkService', 'LocalSystem', 'User'. It indicates the account under which the service will run.

User - allows the service to impersonate a specific user whether or not that user is logged in. The account is mostly useful during development and not when installing the service in production. The problem with this account is that if the user changes their password, the services needs to be reconfigured with the new password to enable it to function.

Local System - system account with high privileges. This account is similar to Administrator account.
It provides full access to the local system's resources.

Local Service – provides a lower privilege level account. The account is ideal that requires limited or no access to the network resources.

Network Service - this account is built into windows. It provides less privilege to the local computer. The account is ideal for services that require substantial access to network resources.

Reference: MSDN

Zip Unzip files Programmatically in C#

Posted by Techie Cocktail | 7:54 AM | | 0 comments »

C# and VB.Net does not have support to perform Zip and UnZip operations. But you can achieve this in .Net using Visual J# in C#. Its very easy. Check below.



Steps:

a. Ensure that you have Visual J# in your Visual Studio version. In VS 2005, Visual J# used to come by default, but it does not comes by default in VS 2008. So you need to install it to your VS 2008.

You can download Visual J# Redistributable Packages from -

this link.



b. After installing V J#, add a reference to 'vjslib.dll' in your project.

c. Refer to these namespaces in your code - java.util, java.util.zip, java.io;



d. Follow this code below. Works perfect.



Source Code:



public static void CreateZipFile(string filename, string[] items)

{

FileOutputStream fout = new FileOutputStream(filename);

ZipOutputStream zout = new ZipOutputStream(fout);

zout.close();

ZipFile zipfile = new ZipFile(filename);

AddEntries(zipfile, items);

}





private static void AddEntries(ZipFile file,string[] newFiles)

{

string fileName = file.getName();

string tempFileName = Path.GetTempFileName();

ZipOutputStream destination = new ZipOutputStream

(new FileOutputStream(tempFileName));

try

{

CopyEntries(file, destination);

if (newFiles != null)

{

foreach (string f in newFiles)

{

ZipEntry z = new ZipEntry(f.Remove

(0,Path.GetPathRoot(f).Length));

z.setMethod(ZipEntry.DEFLATED);

destination.putNextEntry(z);

try

{

FileInputStream s = new FileInputStream(f);

try

{

CopyStream(s, destination);

}

finally

{

s.close();

}

}

finally

{

destination.closeEntry();

}

}

}

}

finally

{

destination.close();

}

file.close();

System.IO.File.Copy(tempFileName, fileName, true);

System.IO.File.Delete(tempFileName);

}





private static void CopyEntries(ZipFile source,

ZipOutputStream destination)

{

List entries = GetZippedItems(source);

foreach (ZipEntry entry in entries)

{

destination.putNextEntry(entry);

InputStream s = source.getInputStream(entry);



CopyStream(s, destination);

destination.closeEntry();

s.close();

}

}





private static void CopyEntries(ZipFile source,

ZipOutputStream destination,string[] entryNames)

{

List entries = GetZippedItems(source);

for(int i=0;i
{

foreach (ZipEntry entry in entries)

{

if (entry.getName() == entryNames[i])

{

destination.putNextEntry(entry);

InputStream s = from.getInputStream(entry);



CopyStream(s, destination);

destination.closeEntry();

s.close();

}

}

}

}





private static void CopyStream(InputStream source,

OutputStream destination)

{

sbyte[] buffer = new sbyte[8000];

int data;

while (true)

{

try

{

data = source.read(buffer, 0, buffer.Length);

if (data > 0)

{

destination.write(buffer, 0, data);

}

else

{

return;

}

}

catch (Exception ex)

{

string msg = ex.Message;

}

}

}





private static List GetZippedItems(ZipFile file)

{

List entries = new List();

Enumeration e = file.entries();

while (true)

{

if (e.hasMoreElements())

{

ZipEntry entry = (ZipEntry)e.nextElement();

entries.Add(entry);

}

else

{

break;

}

}

return entries;

}





public static void ExtractZipFile(string zipfilename,

string destination)

{

ZipFile zipfile = new ZipFile(zipfilename);

List entries = GetZippedItems(zipfile);

foreach (ZipEntry entry in entries)

{

if (!entry.isDirectory())

{

InputStream s = zipfile.getInputStream(entry);

try

{

string fname = System.IO.Path.GetFileName(entry.getName());

string dir=System.IO.Path.GetDirectoryName(entry.getName());

string newpath = destination + @"\" + dir;

System.IO.Directory.CreateDirectory(newpath);

FileOutputStream dest = new FileOutputStream

(System.IO.Path.Combine(newpath, fname));

try

{

CopyStream(s, dest);

}

finally

{

dest.close();

}

}

finally

{

s.close();

}

}

}

}



For more information on this topic check this reference website: DotNetBips



Other method to zip files:



private void Zip(string zipFileName, string[] sourceFile)

{

FileOutputStream filOpStrm = new FileOutputStream(zipFileName);

ZipOutputStream zipOpStrm = new ZipOutputStream(filOpStrm);

FileInputStream filIpStrm = null;

foreach(string strFilName in sourceFile)

{

filIpStrm = new FileInputStream(strFilName);

ZipEntry ze = new ZipEntry(Path.GetFileName(strFilName));

zipOpStrm.putNextEntry(ze);

sbyte[] buffer = new

sbyte[1024];

int len = 0;

while ((len =

filIpStrm.read(buffer)) > = 0)

{

zipOpStrm.write(buffer, 0, len);

}

}

zipOpStrm.closeEntry();

filIpStrm.close();

zipOpStrm.close();

filOpStrm.close();

}

Reference: http://69.10.233.10/KB/cs/unzipC_usingJ_.aspx

Functions to get First Date and Last Date of Previous Month and Year.

private DateTime LastDateOfPreviousMonth()
{
    return DateAndTime.DateAdd("d", -1, DateTime.Now.Month.ToString() + "/01/" + DateTime.Now.Year.ToString());
}

Note:
In C#, you will need to add the namespace as 'using Microsoft.VisualBasic' in the source code unit. Also Add Reference to 'Microsoft.VisualBasic' dll.

private DateTime FirstDateOfPreviousMonth()
{
    int Yr, Mnth;
    DateTime prev = DateTime.Now.AddMonths(-1);
    Yr = prev.Year;
    Mnth = prev.Month;

    return Convert.ToDateTime(Mnth.ToString() + "/01/" + Yr.ToString());
}

Totals row at the end - Logparser

Posted by Techie Cocktail | 6:33 PM | , | 0 comments »

I wanted to display a totals row at the end in a Logparser query. Thought of sharing the magic.

'WITH ROLLUP' keyword does the magic.

Things to note:
'WITH ROLLUP' should be used immediately after GROUP BY clause (not after ORDER BY)

If you try to use 'ORDER BY' clause after 'WITH ROLLUP', the totals column will come in the first line but it depends on what you are sorting.

Also, if you are using Visual Logparser tool to run the query having 'WITH ROLLUP', it doesn't work and gives an error: 'Input string was not in a correct format'
But it works completely fine when run from the command line which is strange.

Example Query:
logparser "select Top 5 Date, grouping(date) as
Gdate, c-ip as IPAddress, SUM(10), count(*) as [Count] from where c-ip like 'xx.xx%' group by Date, ipaddress with rollup" -stats:off

check out the magic.

I was deploying my .aspx page that shows SSRS reports on Microsoft Report Viewer Control. After deploying the website, the report came successfully but the dundas charts weren't showing up.

After struggling for a long time, following steps i had to perform showed up the charts:

a. Copied the following dundas dll's to this location - 'C:\Program Files\Microsoft SQL Server\MSSQL.x\Reporting Services\ReportServer\bin'

- DundasRSChart.dll
- DundasRSChartDesigner.dll
- DundasWebChart.dll

b. Added the following code to the 'rsreportserver.config' file at 'C:\Program Files\Microsoft SQL Server\MSSQL.x\Reporting Services\ReportServer' location (inside the <Extensions> element):

</Service>
<Extensions>
<ReportItems>
<ReportItem Name="DundasChartControl" Type="Dundas.ReportingServices.DundasChart,DundasRSChart" />
</ReportItems>
<Delivery>

c. Added the following code to the 'rssrvpolicy.config' file at 'C:\Program Files\Microsoft SQL Server\MSSQL.x\Reporting Services\ReportServer' location (Make sure the following <IMembershipCondition> tag exists within the element <CodeGroup>):

</CodeGroup>
<CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="DundasChartControl" Description="This code group grants FullTrust to DundasChartControl assemblies."> <IMembershipCondition class="StrongNameMembershipCondition" version="1" PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100d
16006505277d0860ce7d429331480cb3b9711481cd51213259cf3b106e30156f5ef48262e0154e862fa
05374e6c7cef5c4daa95b2272a73e503f0e5077c6b71a24176e67eadbff8e8765742f022e317194571de
05d0ac9a4fca62fd355854ebe5a38969a831030018edad7d7405dd23d0710c9faf95acf16a4a14003bada
5be" />
</CodeGroup>
</CodeGroup>
</CodeGroup>
</PolicyLevel>

Refer to this site for more details: http://support.dundas.com/Default.aspx?article=1107

This made my day. The charts showed up with a surprise.

In my web app, i was displaying the SSRS report using Microsoft Report Viewer Control. On loading the web app to view the report, was getting this error:

"The permissions granted to user 'NT AUTHORITY\NETWORK SERVICE' are insufficient for performing this operation. (rsAccessDenied)"

Found the following solution, thought of sharing:

a. Go to Report Manager under "http://localhost/Reports".
b. Click on Properties tab.
c. Go to Security options.
d. Choose New Role Assignment.
e. Add in the 'Group or user name' -> 'NT AUTHORITY\NETWORK SERVICE'.
f. Assign 'Browser' role to 'NT AUTHORITY\NETWORK SERVICE' user.

This should fix the problem. I was able to see my SSRS reports in my web app.

Breaked my head figuring out the above mentioned issue. It looked silly to me because it was just a normal Win2k3 server. Then why wouldn't it execute the exe's that i copied from another machine.

After browsing through the internet for a while, the below solution worked for me.

SOLUTION:
As i had copied the exe file from another machine, right clicked the exe file, Under General Tab, clicked the "Unblock" button.

seems like a Security Feature in Win2k3 and it says - "The file came from another computer and might be blocked to help protect this computer".

Some people got this problem fixed by:
going to add/remove windows components, then uninstalling the "Internet Explorer Enhanced Security component"

These issues seems to be strange and irritates sometimes, hence thought of sharing. May help someone.

CASE Statement in Logparser Query

Posted by Techie Cocktail | 5:52 PM | , | 1 comments »

Good Logparser examples, specially the CASE Statement that helped me today.

http://technet.microsoft.com/en-us/magazine/cc160953.aspx

There is no direct string function to convert a given case string to a Mixed Case or Title Case (first letter of the word is capitalized)

Below is the code you can achieve this using the CultureInfo in Globalization namespace:

string myString = "test string";

System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;

string mixedCaseString = textInfo.ToTitleCase(myString.ToLower());

The mixedCaseString will be "Test String".

Flex Livedocs

Posted by Techie Cocktail | 4:30 PM | | 0 comments »

Great resource for Flex, fast upcoming language. Check it yourself at http://livedocs.adobe.com/flex/3/html/index.html

Everything about File and Stream IO

Posted by Techie Cocktail | 11:30 PM | | 0 comments »

Good source covering most of the things related to File and Stream IO in MSDN: http://msdn.microsoft.com/en-us/library/k3352a4t.aspx

My web app has a report viewer control. Its layout was fine when viewed in IE7. But in FireFox browser, it shrinked both on width and height. Also in IE6, the report viewer control collapsed on height and the chart and report were not visible.

After breaking my head on figuring out the cause, found a fix:

a. Comment/remove the DOCTYPE line from the .aspx page.
b. On the Report Viewer control, change the AsyncRendering property value to "False". Default is set to "True"

Also, if you are getting a Report Viewer Scroll bar for long data, do the following to remove the Report Viewer scrollbar and use the entire webpage to scroll:

a. Remove the height attribute value if you have set any.
b. Set Width to 100%.

The above fixes made my Report Viewer Control to work on all browsers properly without any layout or scrolling issues and made my life.

References: http://arcanecode.wordpress.com/2007/11/29/sql-server-2005-reporting-services-reportviewer-control-and-ie7/

I ran into this issue and was happy to find this solution. Thought of sharing this fix and also for my future reference purpose.



Error: The attempt to connect to the report server failed. Check your connection information and that the reportserver is a compatible version. The request failed with HTTP status 404: Not Found.



This means that you have configured the /reportserver/ app to not be reachable via
http://localhost/...



Solution:



a) Add the localhost hostheader to the web-site which hosts the /reportserver/ and make sure the app is then reachable via that path.



b) Edit the file -

C:\Program Files\Microsoft SQL Server\MSSQL.1\Reporting Services\ReportManager\RSWebApplication.config



and add the full url to the ReportServer into the ReportServerUrl tag (no ending / nessesary) AND remove the value from ReportServerVirtualDirectory (otherwise you get nasty, unprecise exceptions). THEN you must recycle the app-pool used by the Report-Manager so that config file is being reloaded



<UI>

<ReportServerUrl>http://localhost/reportserver
<ReportServerVirtualDirectory></ReportServerVirtualDirectory>

<ReportBuilderTrustLevel>FullTrust</ReportBuilderTrustLevel>

</UI>



Reference: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=198252&SiteID=1

I had a requirement to automate the generation of PDF files of SSRS reports.

Figured out a way to use 2 webservices exposed by SQL Server Reporting Services 2005:
a. ReportService2005
b. ReportExecution2005

Implementation:
a. Create SSRS reports and deploy it on the report server.
b. In the windows application add reference to the 2 SSRS webservices: ReportService2005, ReportExecution2005
c. Set default report credentials.
d. Set 2 webservies url
e. Load the SSRS report using ReportExecution2005
f. Get SSRS reportparameters using ReportService2005, to get the total parameters in the report and set the appropriate parameters value to render the report using ReportExecution2005. (confused !!!. Check the code below)
g. Set report parameters using
SetExecutionParameters() method of ReportExecution2005.
h. Render the report to get the PDF in byteArray format.
i. Write the pdf byteArray[] to the given pdf file using FileStream Class.



Source Code:

static private void CreatePDFReports()

{
//create proxy to the webservice
ReportService2005.ReportingService2005 rs2005 = new ReportService2005.ReportingService2005();
ReportExecution2005.ReportExecutionService re2005 = new ReportExecution2005.ReportExecutionService();

try
{
//authenticate to the web service using windows credentials
rs2005.Credentials = System.Net.CredentialCache.DefaultCredentials;
re2005.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs2005.Url = ConfigurationSettings.AppSettings["ReportService2005.ReportService2005"];
re2005.Url = ConfigurationSettings.AppSettings["ReportExecution2005.ReportExecution2005"];

//prepare render arguments
string historyID = null;
string deviceinfo = null;
string format = "PDF";
byte[] bytPDF;
string encoding = string.Empty;
string mimeType = string.Empty;
string extension = string.Empty;
ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;

//define variables needed for GetParameters() method
//get the report name
string _reportname = ConfigurationSettings.AppSettings["reportName"];
string _historyID = null;
bool _forRendering = false;
ReportService2005.ParameterValue[] _values = null;
ReportService2005.DataSourceCredentials[] _credentials = null;
ReportService2005.ReportParameter[] _parameters = null;

//load the selected report.
ReportExecution2005.ExecutionInfo ei = re2005.LoadReport(_reportname, historyID);

//Get the no. of parameters in the report.
_parameters = rs2005.GetReportParameters(_reportname, _historyID, _forRendering, _values, _credentials);
int totalParams = _parameters.Length;

ReportExecution2005.ParameterValue[] parameters = null;

//prepare report parameters
parameters = new ReportExecution2005.ParameterValue[totalParams];

foreach (ReportService2005.ReportParameter rp in _parameters)
{
switch (rp.Name)
{
case "param1_name":
{
parameters[_parameters.Length - totalParams] = new scheduleReports.ReportExecution2005.ParameterValue();
parameters[_parameters.Length - totalParams].Name = rp.Name;
parameters[_parameters.Length - totalParams].Value = 1;
}
break;

case "param2_name":
{
parameters[_parameters.Length - totalParams] = new scheduleReports.ReportExecution2005.ParameterValue();
parameters[_parameters.Length - totalParams].Name = rp.Name;
parameters[_parameters.Length - totalParams].Value = 100;
}
break;
}
totalParams--;
}

re2005.SetExecutionParameters(parameters, "en-us");
bytPDF = re2005.Render(format, deviceinfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);

FileStream fs = new FileStream("report.pdf", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bytPDF, 0, bytPDF.Length);

fs.Close();
}

catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}

References

Posted by Techie Cocktail | 1:30 PM | | 0 comments »

ASP.NET:

a. Deciding When to Use the DataGrid, DataList or Repeater: http://msdn.microsoft.com/en-us/library/aa479015.aspx#aspnet-whenusedatawebcontrols_topic5

Source code to get the first day and the last day of the current month for the given year:

First Day:
DateTime firstDayOfSelectedMonth =
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

Last Day:
DateTime lastDayOfSelectedMonth =
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);

I had to spend sometime around this issue. After adding a new tab to add Ajax Control toolkit controls to my VS 2008 (.Net Framework 3.5) toolbox, i was unable to see the Ajax controls. When i did 'Show All', it showed me my tab but the controls were grayed out. This was something strange to me as i never had such a problem for this when i had worked with framework 2.0.

After breaking my head on this for a while, i finally figured out the issue.

Solution:
Change the project property -> Build -> Target Framework -> change from .NET Framework 2.0 to 3.5.

Suppose you export your SSRS report to PDF extension format (or any other available formats) and your one page report gets broken down into two pages in PDF file, this can be taken care of by updating its 'Device Information Settings'.
The 'Device information settings' section also allows you to override the export extension names by overriding them.
There are other configurable settings as well which can be updated as needed.

Below is how you would do it:
Go to 'rsreportserver.config' at 'C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer' location and update the settings as follows:

<Render>
...
...

<Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport,Microsoft.ReportingServices.ImageRendering">
<OverrideNames>
<Name Language="en-us">PDF (Updated)</Name>
</OverrideNames>

<Configuration>
<DeviceInfo>
<MarginBottom>0in</MarginBottom>
<MarginLeft>0.25in</MarginLeft>
<MarginRight>0in</MarginRight>
<MarginTop>0in</MarginTop>
<PageHeight>10in</PageHeight>
<PageWidth>11in</PageWidth>
</DeviceInfo>
</Configuration>


...
...

</Extension>
</Render>

The above updated settings increases the resolution and accommodates the report in one page in the exported PDF file.
Also, in the 'Export' drop down list, the overridden name "PDF (Updated)" would appear.

For more information on the available 'Device Information Settings' visit: http://msdn.microsoft.com/en-us/library/aa179622(SQL.80).aspx

The below figure shows the default Export Options in SSRS report toolbar. These export options are configurable and can be updated. Say for example you are required to show only PDF and IMAGE export options.


Solution:
This can be achieved by updating the configuration settings of the report server. These configuration settings are stored in the RSReportServer.Config file in 'C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer' folder.

In this file, look for the tag which shows the default rendering extensions as below.

<Render>
<Extension Name="XML" Type="Microsoft.ReportingServices.Rendering.XmlDataRenderer.XmlDataReport,Microsoft.ReportingServices.XmlRendering" />
<Extension Name="NULL" Type="Microsoft.ReportingServices.Rendering.NullRenderer.NullReport,Microsoft.ReportingServices.NullRendering" Visible="false" />

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering" />
<Extension Name="IMAGE" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.ImageReport,Microsoft.ReportingServices.ImageRendering" />
<Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport,Microsoft.ReportingServices.ImageRendering" />
<Extension Name="RGDI" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.RemoteGdiReport,Microsoft.ReportingServices.ImageRendering" Visible="false" LogAllExecutionRequests="false" />

<Extension Name="HTML4.0" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.Html40RenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible="false" LogAllExecutionRequests="false" />

<Extension Name="HTML3.2" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.Html32RenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible="false" />

<Extension Name="MHTML" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.MHtmlRenderingExtension,Microsoft.ReportingServices.HtmlRendering" />
<Extension Name="EXCEL" Type="Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer,Microsoft.ReportingServices.ExcelRendering" /> </Render>

Note some extension tags have "Visible" attribute with the boolean value as "false". This means that the extension tag whose "Visible" attribute is set to false will not be visible in the dropdown list box. The extensions that are visible do not have the "Visible" attribute set because they are defaulted as "true".

As here we want to show only PDF & IMAGE extensions, hence update other extensions by setting their "Visible" attribute’s value to "false" as below:

<Render>
<Extension Name="XML" Type="Microsoft.ReportingServices.Rendering.XmlDataRenderer.XmlDataReport,Microsoft.ReportingServices.XmlRendering" Visible=”false”/>

<Extension Name="NULL" Type="Microsoft.ReportingServices.Rendering.NullRenderer.NullReport,Microsoft.ReportingServices.NullRendering" Visible="false" />

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering" Visible=”false”/>

<Extension Name="IMAGE" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.ImageReport,Microsoft.ReportingServices.ImageRendering" />
<Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport,Microsoft.ReportingServices.ImageRendering"/>
<Extension Name="RGDI" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.RemoteGdiReport,Microsoft.ReportingServices.ImageRendering" Visible="false" LogAllExecutionRequests="false" />

<Extension Name="HTML4.0" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.Html40RenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible="false" LogAllExecutionRequests="false" />

<Extension Name="HTML3.2" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.Html32RenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible="false" />

<Extension Name="MHTML" Type="Microsoft.ReportingServices.Rendering.HtmlRenderer.MHtmlRenderingExtension,Microsoft.ReportingServices.HtmlRendering" Visible=”false”/>

<Extension Name="EXCEL" Type="Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer,Microsoft.ReportingServices.ExcelRendering" Visible=”false”/> </Render>


For more details, you can refer http://msdn.microsoft.com/en-us/library/ms157153.aspx

Demonstration of SSRS reports in ASP.Net

Posted by Techie Cocktail | 4:05 PM | | 0 comments »

The SSRS reports can be integrated in asp.net page using the available 'MicrosoftReportViewer' Control in the toolbox under Reporting tab (Microsoft Visual Studio 2008). This implementation assumes that you have already created SSRS reports and have hosted them on a web server.

This implementation uses - Menu Control, XML Datasource to bind XML Data to the menu control & the Microsoft Report Viewer control. The menu control is bound to the XML data file via the XMLDatasource to create menu items. When the user clicks on the menu item, the underlying data of the menu item is assigned to the ReportViewer’s report path property and the corresponding report is called & displayed in the Report Viewer Control.

Below is the Source code of the above mentioned:

1. Sample XML file - sitemap.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Menu text="Parent Node" url="">
<subMenu text="Child Node" url="/SSRSReports/Report1"/>
</Menu>

2. Attach sitemap.xml to the XMLDatasource using the XMLDatasource’s DataFile Property:

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/sitemap.xml"></asp:XmlDataSource>

3. Attach the XML Datasource to the ASP.Net Menu control by assigining the XMLDataSource ID property value to the asp.net menu control DataSourceID property:

<asp:Menu ID="mnu_Main" runat="server" DataSourceID="XmlDataSource1" />

4. Bind the menu items in the menu with the xml file using the DataBindings collection:

<DataBindings>
<asp:MenuItemBinding DataMember="Menu" TextField="text" ValueField="url" />
<asp:MenuItemBinding DataMember="subMenu" TextField="text" ValueField="url" />
</DataBindings>

5. Put this code in the MenuItemClick event:

if (e.Item.Value != null)
{
ReportViewer1.Reset();
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://<ServerName>/ReportServer");
ReportViewer1.ServerReport.ReportPath = e.Item.Value;
ReportViewer1.ShowParameterPrompts = true;
ReportViewer1.ShowBackButton = true;
ReportViewer1.ShowRefreshButton = true;
ReportViewer1.ServerReport.Refresh();
}

This is one of the method to integrate SSRS reports within your asp.net page. You can choose different components in place of the above mentioned.

The XML file used here is a simple one. If one uses complex XML file for the menu, then XPath can be used to retrieve the value from an XMLDocument and bind it to the menu control. The XMLDocument can also be cached using various caching techniques to improve the site performance.

In the above method, clicking on one of the menu items would perform postbacks to the server. This can be avoided with the use of AJAX implementation which would avoid postbacks to the server there by increasing the users experience.

If there are two series to be represented against one parameter in the chart where one series value is always going to be high compared to the other, better representation would be to show the two series on different sides of Y-Axis.

Example:
The below table shows the number of professionals passed/failed in the certification exams on a particular date, where most of the time the Fail ratio is lower than the Pass ratio.

Sr NoDatePassedFailed
12008-07-05 09:00:00.00091
22008-07-06 09:00:00.00082
32008-07-09 09:00:00.000100


Following are the steps on how you would represent both series values on different sides of Y-Axis using DUNDAS Charts:

a. Add both Pass & Fail series as values & group it by date as in the following chart.



b. Double-click on 'Failed' series, for its details. Go to 'Series' Tab.



c. Select the Y-Axis Type value from the drop-down as 'Secondary'.



d. Below is how it would look like.

Log Parser and Reporting

Posted by Techie Cocktail | 1:18 AM | | 0 comments »

Introduction:
Logging information has become integral part of the source code implementation as it helps to identify useful information or troubleshoot an issue. Logs can contain lots of information which may be sometime tedious to interpret, specially, if they contain too much of data. It can sometime become difficult or time-consuming to understand the large number of records in many log files and sometime the data isn't in human-readable format.

Solution:
Log Parser is one of the available free tools provided by Microsoft that can be used to parse the log data efficiently and represent it in one of its available output formats. It uses a SQL-like engine core to process data from logs and generates custom results. It means that it uses SQL language with built-in log parser functions to query the logs and get the desired results.

Some of the log formats it supports are - XML, CSV, Windows Event Logs, IIS Logs, Windows Registry, Active Directory etc. The output can be presented as a chart, datagrid, HTML, XML etc.

The Log Parser tool is available as:
a. Command-line tool:
http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en

b. Easy-to-use Visual Log Parser:
http://www.serialcoder.net/deploy/visual-logparser/publish.htm

Sample scripts:

a. Top 20 IP Address & their count from where your site was looked upon - output results to datagrid.

Logparser –i:IISW3C "select Top 20 Date, c-ip as IPAddress, count(*) as [Count]
from <iislogfile>
group by Count, Date, IPAddressorder by [Count] desc" -o:datagrid

b. Browser Breakup – output results to html using a template:

The output can be presented in the html format by attaching a template fileTemplate:
<LPHEADER>
<HTML>
<HEAD><TITLE>Browser Breakup Report</TITLE></HEAD>
<BODY>
<H1>Browser Breakup Report</H1>
<TABLE BORDER="1">
<TR BGCOLOR="GRAY">
<TH>Browser</TH>
<TH>Hits</TH>
</TR>
</LPHEADER>

<LPBODY>
<TR>
<TD><TT>%Browser%</TT></TD>
<TD><TT>%Hits%</TT></TD>
</TR>
</LPBODY>
</TABLE>
<LPFOOTER>
</BODY>
</HTML>
</LPFOOTER>

Query:

Logparser –i:IISW3C "Select top 50 cs(User-Agent) as Browser, count(*) as Hits
into <report.html>
from <iislogfile>
group by Browser
order by Hits desc"
-stats:OFF -o:TPL -tpl:template.txt

c. Event Viewer Logs – output results to an xml file:

Logparser –i:EVT “SELECT TimeGenerated AS Date, EventTypeName as [Event Type],
EventID, SourceName AS Source,
EventCategoryName AS Category, ComputerName AS Computer, Message
Into <iislogfile>FROM system, Application
where EventType IN (1;2) ORDER BY TimeGenerated DESC”

d. Dumping data to SQL Server directly – output result to SQL Table:

Logparser –i:IISW3C "SELECT sc-status as Status, sc-substatus as Sub-Status, COUNT(*) as [Count]
into SQLTABLE from <iislogfile> GROUP BY sc-status, sc-substatus ORDER BY [Count] DESC”-o:SQL –database:SQLDatabase

e. Status & Sub-Status Code Distribution – output results to Excel:

Logparser –i:IISW3C "SELECT sc-status as Status, sc-substatus as Sub-Status, COUNT(*) as [Count]
into <excel.csv> from <iislogfile> GROUP BY sc-status, sc-substatus ORDER BY [Count] DESC”

Reporting options:
a. Output in the form of html by using a base template.txt attached to it. A chart can also be embedded into the html document by adding the <img> tag within the template.

b. Output data to the SQL Table directly and use SSRS and generate simple, matrix reports and using in-built or Dundas charts.

c. Output the result in the form of XML data. Attach an XSLT file to the xml and transform the output in the form of example.

These are just a few pointers to endless ways to parse and implement reporting. Also, there is a very good help provided in the Help Menu of the visual log parser (VLP). The VLP help shows the complete solid list of functions that can help you to retrieve any possible data you want to. If someone likes the command-line, go for "Logparser –h /?" for help.