Friday, November 28, 2008

Firebird Security and Performance

I am using Firebird since last 2 years from 1.5 version. The latest version that i am presently using in Firebird 2.1.0 Super Server. Before this I had never used any open source Database, though there are lots of Databases available like
SQLite
Postgres
MySQL
etc..
Being a file based RDBMS, i have seen very good performance in Firebird.
though we are using firebird in our company there are lots of conflicts in mind of developers in our company, so i decided post a comment on Firebird Security and Performance.
Lets start with performance..
When you install Firebird server with default installation option it will install it as a Super Server, with some default page size. page size plays a very vital role in the performance of Firdbird Database.

coming soon.....

Friday, September 12, 2008

Create Word, Excel using Office Object Library

Add a reference to Microsoft Word Object XX.0 Library and also same for Excel. i have user Object Library 12.0

using MSWord Microsoft.Office.Interop.Word;
using MSExcel = Microsoft.Office.Interop.Excel;

public bool CreateWordDocument(string FilePath)
{
bool bsuccess = false;
try
{
object missing = System.Reflection.Missing.Value;
MSWord.ApplicationClass msword = new MSWord.ApplicationClass();
Document doc = msword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
object Filename = FilePath;
doc.SaveAs(ref Filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
bsuccess = true;
}
catch
{
bsuccess = false;
}
return bsuccess;
}

public bool CreateExcelWorkBook(string FilePath)
{
bool bsuccess = false;
try
{
object missing = System.Reflection.Missing.Value;
MSExcel.ApplicationClass excel = new MSExcel.ApplicationClass();
MSExcel.Workbook book = excel.Workbooks.Add(missing);
object Filename = FilePath;
book.SaveAs(Filename, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excel.Quit();
bsuccess = true;
}
catch
{
bsuccess = false;
}
return bsuccess;
}

Wednesday, August 13, 2008

Dot NET Interview Questions

Q. Which is the Base class for all the classes in .NET?
A. System.Object

Q. What is the differece between .ToString() and Convert.ToString()?
A. .ToString() can not handle null, while Convert.ToString() handles null and does not raise a null value exception.

Q. What is the difference between bool and Boolean?
A. No difference they both refers to the same, and also same is with string/String, int/int32, etc..

Q. Can we set an integer values as null?
A. No.

Q. Can we print the Panel Control?
A. Yes, by passing the panel area to the bitmap object and then send that to the printdocument, through panel.DrawtoBitmap() method.

Q. What happens to the Print when printing data exceeds one page?
A. It is automatically passed to the second page.

Q. Which are the three pillars of any object oriented Programming Language?
A. 1. Encapsulation.
2. Polymorphism.
3. Inheritance.

Q. Do .Net provides multiple inheritance?
A. No.

Q. How can we achieve multiple inheritance in .Net?
A. With the help of interfaces.

Q. An interface must have atleast one abstract Method Yes or No?
A. Yes.

Q. What is a Partial class, how it is usefull?
A. A partial class is a simple class same as other class. but has a facility that, i can be distribute in many .cs files. When they are complied they form a single class. It is usefull when developement is going on in different places all the developers can have their own partial class which can be merged during compilation.

Q.How many web.config files does a single web application can have?
A.Depends on the Applciation behaviour, a single web application have atleast one web config file, but can have more than on web.cinfig files.

Q.What is the differece between a Class and A Module?
A.You can initialize a class but you can not initialize a Module. The scope of the class depends on the available of the class object, but the scope of a module is upto the entire application

Q.What is the difference between Interface and Abstract Class.?

Q.What is a Sealed Class, how it is useful in Object Oriented Concept of C#?

Q.What is Components and Assembly?

Q.What is User Control, how it is useful?

Q.What are Delegates and Events?

Q.Explain the concept of Threading. What is deadlock?

Q.Can we have more than one thread in one Application?

Q.What is the minimum number of Thread/s does any .NET application have?

Q.What is ADO.NET?

Q.How ADO.NET is different from ADO?

Q.Explain the difference between ExecuteNonQuery() and ExecuteScalar() methods of ADO.NET.

Q.What is a DataSet? How it is useful?

Q.What is a Master page ASP.NET?

Q.What is bubbled Event?

Q.What is a ToolTip Class?

Q.How to pass values to the constructor of parent class from the child class when inherited, Give example with Code.

Q.Explain the concept of overloading, how it is useful?

Q.What is Boxing and UnBoxing?

Q.What is DLL Hell?

Q.What is strong type DLL?

Q.What is Exception Handling ? Which is the Main class for any exceptions?

Q.Explain difference between continue, break, return.

Q.Explain Dispose() Method.

Q.Which is more applicable in programming, goto or switch?

Q.Name the class which .NET automatically creates when you create New Project which contains Main() Method.

Q.Which is executed first Form_Load() or Form_Activate()?

Q.Write Code sample for Creating DataTable in Memory with one Primary Key
Column?

Q.How can I programmatically add New Line to TextBox Control, if its MultiLine Property is set to true.

Q.What is Indexing?

Q.What is the difference between const and static?

Q.Enums are static to its class? Yes/No

Q.What is the difference between Array and ArrayList?

Q.Verify the below Code, What will be the output?

Int32 InntegerData=50;
object obj = new object();
obj= (object)IntegerData;
string StringData= Convert.ToString(obj);
MessageBox.Show(StringData);

Q.What will be the output of the below Code
TextBox textbox= new TextBox(“Hello!, Keep Smiling”);
MessageBox.Show(textbox.ToString());

Q.What are resources? Explain the difference between Embedded and Linked resources?

Q.Which Namenpace I will use to get the current MachineName?

Q.what is finalizer? How it is useful?

Some .NET Interview Questions

Q.Which is the Base class for all the classes in .NET?
A.System.Object

<

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>");
}
}

Monday, June 30, 2008

Zip/UnZip using C# with help of iCSharpCode.Sharpziplib.dll

Code for Ziping Directories
///
/// Zip the complete directory with its complete subfolders
///

/// Complete path of the directory to zip
/// complete file path for the zipped file
public void ZipDirectory(string DirToZip, string OutputPath)
{
string[] filenames = Directory.GetFiles(DirToZip);
this.crc = new Crc32();
if(File.Exists(OutputPath))
File.Delete(OutputPath);
ZipOutputStream outStream = new ZipOutputStream(File.Create(OutputPath));
outStream.SetLevel(7); // 0 - store only to 9 - means best compression
zipdir(DirToZip);
outStream.Finish();
outStream.Close();
}

///
/// zip the direcotry and store the content to the zipdirecotry's zip file
///

/// Directory to zip
private void zipdir(string DirToZip)
{
string[] files = Directory.GetFiles(DirToZip);
foreach(string file in files)
zipfile(file);
string [] subdirs = Directory.GetDirectories(DirToZip);
foreach(string subdirectory in subdirs)
zipdir(subdirectory);
}


Code for UnZip Directories and its sub Directories

private void Unzip(string input ,string output)
{
ZipInputStream zipstream = new ZipInputStream(File.OpenRead(input));
ZipEntry theEntry;
while ((theEntry = zipstream.GetNextEntry()) != null)
{
string directoryName = output;
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName != "")
Directory.CreateDirectory(directoryName);
if (fileName != String.Empty)
{
if (theEntry.Name.IndexOf(".ini") < fullpath =" directoryName" fullpath =" fullPath.Replace(" fulldirpath =" Path.GetDirectoryName(fullPath);" streamwriter =" File.Create(fullPath);" size =" 2048;" data =" new" size =" zipstream.Read(data,"> 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
zipstream.Close();
}

Download :
iCSharpCode.sharpZipLib.dll

Get list of Network Machines Using C#.NET

Before using this code make a reference to following Namespace

using System.DirectoryServices;

#region Get all the machines in the Network
public ArrayList getNetworkMachines()
{
ArrayList MachineList = new ArrayList();
//Getting the List of Mahcines in Network
DirectoryEntry parentEntry = new DirectoryEntry();
try
{

parentEntry.Path = "WinNT:";
foreach (DirectoryEntry childentry in parentEntry.Children)
{
switch (childentry.SchemaClassName)
{
case "Domain":
DirectoryEntry SubParentEntry = new DirectoryEntry();
SubParentEntry.Path = "WinNT://" + childentry.Name;
foreach (DirectoryEntry subChildEntry in SubParentEntry.Children)
{
switch (subChildEntry.SchemaClassName)
{
case "Computer":
MachineList.Add(subChildEntry.Name);
break;
}
}
break;
}
}
}
catch
{
throw;
}
finally
{
parentEntry = null;
}
//
return MachineList;
}
#endregion

A Simple Concept to Database Synchronization

Synchronization Techniques
Synchronization process depends on the functionality required by the disconnected clients, when they are not connected to the Central Database.
There must be strict business rules on both Client Side and Server Side for deletion and updation of records.
Triggers can play a vital role in tracking changes made to either side of the database.
Triggers should maintain a log files on the table basic which should contain in formation about (Type of operation Performed, Table Name, Row Unique Value, Column name, timestamp of operation). These must be maintained at both server and client side.
In the process of Merge replication, Automatic generated primary keys can not serve our purpose, so there needs some unique value that exist at both (Client, Server) which can be used for conflict detection.
All the Tables in the database must follow the cascade rules for updation and deletion.


Business Rules for Database Synchronization
Define the time when synchronization process should occur for total disconnected clients, they must synchronize themselves at least twice a day, so that both Client and Server have latest data.
Client applications are not allowed to delete any records.
If any situation arises that clients are required to delete any record, then at that time they should only be allowed to mark those records as deleted, the actual process of deletion must occur at Server Side.
There must be only one Administrator, who is allowed to delete any record.
Any deletion operations are allowed after server synchronization itself with all the available clients.

Structure of Log Files that will be maintained by Triggers


<?xml version="1.0" encoding="UTF-8"? >

<transactions>

< table name ="””" rowuniquevalue="””" operationperformed="””"
columnname="””" 'oldvalue="””" newvalue="””" timestampofoperation="””" priority="”0”/" >

< /transactions >


Explanation:
Name:
Name of the table in which update was made.
RowUniqueValue: it is Unique Row ID which will uniquely identify the Row it can be Primary key, if it is an auto generated primary key then it will not work.
OperationPerformed: Operation Performed on the table (Insert, Update, Delete);
ColumnName: Name of the Column that was affected by the operation.
OldValue: Old value of the Column before the change was applied; it will be blank for New Record.
NewValue: New value for column after update operation, it will be blank for new and delete operation.
TimestampofOperation: timestamp when the operation was performed, it client and server are in same time zone.
Priority: Set the priority of the operation performed, this is usually for the clients that are allowed to deleted and update the records. This can help when two or more clients make updates on same value.

The above structure of XML file will be easy to maintain and can easily be loaded into a Dataset and can easily be queried.

One important point that needs to clear in mind at creation of transaction Log Files, is the use of Timestamp of operation. It is possible that the client and server could be in different time zones. At that time synchronization can create problems in order to maintain the order of transactions. We can not consider that client and server would be same time zones. If it is case, than no problem it will work fine.

One solution could be to synchronize with the internet time, but this is not a permanent solution. For this to happen, the machine is required to be connected to internet.

Let us consider that the Client and Server are both in different time zones. Then we have to maintain the synchronization process in a specific order on each table that is altered. In this situation we can simply ignore the timestamp data for synchronization.

If Addition, Deletion and Update process has been performed on a table. Then we can maintain an order for changes i.e.
First add all the records to the Client and Server Table.
Then perform the delete operation and reflect to both (Client and Server Database)
And at last perform the Update operation.

Why update operation at last? Because, if some record has been updated by any client and administrator decided to delete that record, then deletion of record after an update operation will be wastage of time.

Using the Above XML File we can generate an SQL Script File (For Insert, Update and Delete operation in database) which will be executed on the database to effect the changes.

I.e. Client Script File will be executed on the Server and vice versa.
In such a situation, server will check how many clients wants to synchronize itself with the server database, and will maintain a queue for all the clients and will accept all the changes from each client one by one and will generate new transaction Log File that will executed on each client.

Conflict detection Technique
Conflict arises when more than one client or client and server both have made updates on same column value. In such a situation there must be some provision to define which update to accept. One way could be a setting the priority of the update that has been made to the record. When any update has been made to the table, both server and clients will set the priority for the update. Now, if server and clients set the same priority for the update, then in that condition, updates from the server will be accepted.

In most of the situation in a client and server based architecture usually server are not an active participant in updating the records, they are in most case act as an central storage medium and very less often act as working medium. It is the client with whom conflicts arises, as they do more client centric work and are usually interacting with the end user. When two or more clients raise a conflict situation, it’s a server task to resolve a conflict and result in a consistent database. For the clients who continuously update the database and require synchronization for such clients it should be provided that they can not process any records in the database. A process records should be maintained for each transactions. When the clients try to synchronize themselves then at that time their request will be sent to the server and server will decide which process to continue and how. This situation depends on the type of application and requirement.

Conflict is a situation when:
One client updates one record and other client deletes that record.
More than one client updates same column value.
One client updates one column value, which other client wants to use in updating other column.

Solutions:
Delete is an operation, which should be given more priority than the update. As I have stated early that, clients are not allowed to delete any record, they can only mark them as deleted, it is the server who will decided whether to delete a record or not.
If more than one client updated the same column value, then it should follow the priority rule, if both the clients have set the same priority value, then server must follow First-Come-First-Serve policy for updating.
The third one needs more attention.
No clients should be allowed to alter master data, on which other values depend.
Even if clients wants to make update, they will maintain a process log for their transaction, that will be passed to sever, when they will synchronize them self.
Usually, Total disconnected clients are not allowed to do any transaction, even if transactions are allowed, they should only be allowed to Add Record.
Totally disconnected clients do not come under the Client Server Architecture. They are just independent applications that want’s their data to be stored at a single place, so that the server has the latest data from all the independent applications. And later all the independent application can copy that data to make them updated.


More to come...