Monday, July 7, 2008

Reporting Tool Analysis and Design using C#.NET

A Simple Reporting Tool Analysis and Design Using C#.NET and FireBird Database. Which will allow user to Design/Create/Print their own report during run time...

What is a Report?

If you ask me, then i'ld say that, report is just a template for displaying data that a query result from a give database passes to it. Every report has data values that act's as a place holder for displaying specific information in specific manner.


Ease of Design:

Every Report should be easy for a user to design, as users are not programmers, they are least concerned about how and where data are stored. they are only interested in getting the data, the way they want. It is very difficult for any developer to design all the report that are required by users. Some of them are left or requirement of specific type of reports are received later. So, if users are provided the ability to design their own reports, then they can design their own reports as per their requirements.



Place holders for Report data:
Panel Control in C# can be considered as one of the best control for holding place holders, let's consider a place holders as Label Control which will be passed data from the Database that they will displayed in the Panel Control.

The main task in this will be displaying data from the database. which ever database we selected the report should be able handle all the database, but with the initial stage we have to select at least one database.

Formating of report is also an important part, it does not matter which data you display in the report but depends on how that data are displayed on the report.
we are not considering a high end report engine for displaying report but with a component which can allow user to create their own reports at runtime.



keep reading more coming soon....

Friday, July 4, 2008

printing Contents of Panel Control using Print Preview Dialog

Make reference to following Libraries
using System.Drawing;
using System.Drawing.Printing ;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;

Declare following Object Variables
PrintDocument printdoc1 = new PrintDocument();
PrintPreviewDialog previewdlg = new PrintPreviewDialog();
Panel pannel = null;

declare event handler for printing in constructor
printdoc1.PrintPage += new PrintPageEventHandler(printdoc1_PrintPage);

Bitmap MemoryImage;
public void GetPrintArea(Panel pnl)
{
MemoryImage = new Bitmap(pnl.Width, pnl.Height);
Rectangle rect = new Rectangle(0,0,pnl.Width ,pnl.Height);
pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, pnl.Width, pnl.Height));
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(MemoryImage, 0, 0);
base.OnPaint(e);
}
void printdoc1_PrintPage(object sender, PrintPageEventArgs e)
{
Rectangle pagearea = e.PageBounds;
e.Graphics.DrawImage(MemoryImage,(pagearea.Width /2 )-(pannel.Width /2) ,pannel.Location.Y);
}

public void Print(Panel pnl)
{
pannel = pnl;
GetPrintArea(pnl);
previewdlg.Document = printdoc1;
previewdlg.ShowDialog();
}

Thursday, July 3, 2008

HTML 2 PDF Using iTextSharp Library

Make reference to the following libraries
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;

Document doc = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter.GetInstance(doc, new System.IO.FileStream("output.pdf", FileMode.Create));
doc.Open();
ArrayList ListaElemenata = new ArrayList();
StreamReader sr = new StreamReader(@quotC:\Document.html", Encoding.UTF8);
try
{
ListaElemenata = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
}
catch{ }
for (int i = 0; i < ListaElemenata.Count; i++)
{
try
{
IElement ielement = (IElement)ListaElemenata[i];
ArrayList chunks = ielement.Chunks;
for (int j = 0; j < chunks.Count; j++)
{
Chunk chunk = (Chunk)chunks[j];
chunk.Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, "Cp1250", 12);
doc.Add(new Phrase(chunk));
}
}
catch{ }
}
doc.Close();
}
catch(Exception excep)
{
MessageBox.Show(excep.Message);
}



you can download itextsharp.dll from http://www.sf.net

Tuesday, July 1, 2008

setting multiple file system watcher using c#

FileSystemWatcher filewatcher = new FileSystemWatcher();
ArrayList WatcherList = new ArrayList();
for (int Count = 0; Count < 5; Count++)
{
try
{
filewatcher.Path = "path to watch for file creation" ;
filewatcher.IncludeSubdirectories = true;
filewatcher.Created += new FileSystemEventHandler(filewatcher_Created);
filewatcher.EnableRaisingEvents = true;
WatcherList.Add(filewatcher);
}
catch { }
}

void filewatcher_Created(object sender, FileSystemEventArgs e)
{}


Above event will be generated when any file is created into the folder or sub folder specified at filewatcher.Path=""

passing message to sockets using C#

Make a reference to

using System.Net;
using System.Net.Sockets;

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
IPAddress broadcast = IPAddress.Parse(ReceiverIpaddress);
byte[] sendbuf = Encoding.ASCII.GetBytes("Message to pass");
IPEndPoint ep = new IPEndPoint(broadcast, "Any Free port Number");
s.SendTo(sendbuf, ep);
}
catch
{}

Firebird Database Access

Every Database comes with one default user, which is created when the database is installed for the first time. As per the Firebird is concerned, It also comes with a default user having Username as sysdba and Password as masterkey which every user using the firebird knows very well. This account has all the privileges on the server and cannot be deleted. Now there comes a security problem, if our database is accessed through internet any user using the default Username and password can log into the database and can easily access the Database.

The solution for this is to change the password of the master user, so that only limited (trusted) administrators should know this in order to administer the database. Never access the database using master account, create normal users to create and manage the database and use that account to access the database so that, Only that user owns the database. No other users from the user list of the database are allowed to access the database unless any grants are given to those users. The user who creates a database gets all the grants by default because he/she is the owner of the database.

firebird does not have any builtin security feature. So it the programmer, who has to keep this is mind of how to secure their data.

Note : Never access the Database with default Username and password.

Backup/Restore of Firebird Database

i using Firebird super server version 2.0

Backup Code :

FbBackupFile file = new FbBackupFile(@"C:\SAMPLEtestsample.fbk", 2048);
FbBackup backup = new FbBackup();
backup.BackupFiles.Add(file);
string connection = @"C:\SAMPLEDATABASE.FDB"
backup.ConnectionString = @"data source=pc205;initial catalog=" + connection + "User=SYSDBA; password=masterkey"
backup.ServiceOutput += new ServiceOutputEventHandler(backup_ServiceOutput);
backup.Options = FbBackupFlags.IgnoreLimbo;
backup.Execute();



Restore Code :

FbBackupFile restorefile = new FbBackupFile(@"C:\DATABASE.FBK", 2048);
FbRestore fbrestore = new FbRestore();
fbrestore.BackupFiles.Add(restorefile);

string connection = @"C:\DATABASE.FDB"
fbrestore.ConnectionString = @"data source=pc205;initial catalog=" + connection +"User=SYSDBA;password=masterkey"
fbrestore.PageSize = 2048;
fbrestore.Options = FbRestoreFlags.Create | FbRestoreFlags.Replace;
fbrestore.ServiceOutput += new ServiceOutputEventHandler(fbrestore_ServiceOutput);
fbrestore.Execute();

Save File to FireBird Database

string Query = "UPDATE FILEMASTER SET FILECONTENT=@BLOBData WHERE FILECODE=" + FileCode;


Above is my query.

below is the Code for saving Database into database

FbConnection fbconnection = new FbConnection();
try
{
fbconnection.ConnectionString = Connectionstring;
fbconnection.Open();

FbCommand fbcommand = new FbCommand(Query, fbconnection);
fbcommand.Parameters.Add("@Content", FbDbType.Text).Value = FileContent.Trim().Replace("'", "''");
fbcommand.ExecuteNonQuery();
}
catch
{
}
finally
{
fbconnection.Close();
}



i have used update query for this, you can use insert query for saving new entry.

for the table fields to store image data the datatype for this has to set for BLOB.

Storing of BLOB Data depends on the subtype. BLOB data are of unlimited size.
if you want to store plain text in the Field you can user SUBTYPE as 1

and if you want to store files, you can use SUBTYPE as 0.

Read Outlook Contact Details Using C#

First Make reference to Outlook Object Library in your project, which you can do from

Solution Explorer -> Reference : Right Click -> Add Reference -> COM Tab -> Scroll to Microsoft Outlook Object Library x.x (x.x depends on the version of Office installed)


Here is the Code :

using OutLook = Microsoft.Office.Interop.Outlook;

OutLook.Items contactItems = null;
try
{
OutLook.Application outapp = new Microsoft.Office.Interop.Outlook.ApplicationClass();
OutLook.NameSpace outnamespace = outapp.GetNamespace("MAPI");
OutLook.MAPIFolder contactsFolder = outnamespace.GetDefaultFolder (OutLook.OlDefaultFolders.olFolderContacts);
contactItems = contactsFolder.Items;
owner = outnamespace.CurrentUser.AddressEntry.Name;
}
catch
{
MessageBox.Show("Either Outlook is not available or Outlook has reject your request for connection.", "Outlook Search", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

contactItems contains the collection of the Contact which you can iterate though it using Foreach as
foreach (OutLook.ContactItem items in contactItems)
{
//.......
//Some Code
//.......
}

Create XML File from Tree View Control in C#

///
/// Reads a TreeView Control and writes a XML File based on that
///

/// TreeView
/// XML FilePath
public string TreeViewToXML(TreeView Tree,string OutputFilepath)
{
TreeNode firstNode = Tree.TopNode;
strBuilder.Append("<Folder name=\"Root\">");
foreach (TreeNode node in firstNode.Nodes)
{
strBuilder.Append("< Folder name=" + node.Text +">");
getChild(node);
strBuilder.Append("</Folder>");
}
strBuilder.Append("</Folder>");

using (StreamWriter sw = File.CreateText(OutputFilepath))
{
sw.Write(strBuilder.ToString());
}
return OutputFilepath;
}

private void getChild(TreeNode node)
{
foreach (TreeNode nodes in node.Nodes)
{
strBuilder.Append("<Folder name=" + nodes.Text + ">");
getChild(nodes);
strBuilder.Append("</Folder>");
}
}