Friday, January 21, 2011

C#.net - Create Window Service in C#.net

A windows service is a program which runs continuously in the background of an Operating System. It was formerly known as NT services. Window service internally uses the Service Control Manager (SCM) of the operating system. A service must be installed in a SCM database before it can be launched. SCM controls the entire lifetime of each installed service.

Let see how to create window service in C#.net.

Step 1
Create a window service project.

On the File menu, click New Project.The New Project dialog box opens.Select Windows Service in the list of Visual C# project templates, and name the project WindowServiceDemo. Click OK.



















Click on image for better view

Step 2
Click the designer to select Service1. Then, in the Properties window, set the Name and ServiceName  property for Service1 to ServiceTest.

















Click on image for better view


























Click on image for better view

Step 3
Add functionality to your service.

Select service1.cs file from solution explorer and right click on View Code.
Whenever you open this file you find there two overridden functions OnStart and OnStop.The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service.

Create a method for write a text content to the file when we start and stop the service.it is look like this


 #region Methods
        /// <summary>
        /// Write a Text File
        /// </summary>
        /// <param name="FilePath">Specify the File Path</param>
        /// <param name="Content">Specify the Content</param>
        private void WriteText(String FilePath, String Content)
        {
            try
            {
                System.IO.FileStream FS = new System.IO.FileStream(FilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

                System.IO.StreamWriter SW = new System.IO.StreamWriter(FS);
                SW.BaseStream.Seek(0, System.IO.SeekOrigin.End);     
                SW.WriteLine(Content);
                SW.Flush();
                SW.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

Now call above method in OnStart and OnStop function.

 protected override void OnStart(string[] args)
        {
            try
            {
                WriteText(@"D:\WindowService.txt", "Service Started on " + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
            }
            catch (Exception)
            { }
        }

        protected override void OnStop()
        {
            try
            {
                WriteText(@"D:\WindowService.txt", "Service Stopped on " + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
            }
            catch (Exception)
            { }
        }

Step 4
Create a Installers for your service.

In Solution Explorer, right-click Service1.cs and select View Designer. Click the background of the designer and right click on and then click Add Installer.




















Click on image for better view

By default, a component class that contains two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.

















Click on image for better view

In Design view for ProjectInstaller, select serviceInstaller1 and right click on Property.
Set the StartType property to Automatic.




Click on image for better view

In Design view for ProjectInstaller, select ServiceProcessInstaller1 and right click on Property. Set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.


















Click on image for better view


Build the project by pressing CTRL+SHIFT+B.

Step 5
Install and Run the Service.

You need to call installutil.exe to register this service from command line.Open Visual Studio Command Prompt.
Note:If you using window vista or window 7 then run visual studio command prompt in Administrator Mode.


Go to start > All Programs > Microsoft Visual Studio 2008 or 2010 > Visual Studio Tools >Visual Studio Command Prompt (2010) and right click on Run as Administrator.

Install the WindowService
installutil E:\WindowServiceDemo\WindowServiceDemo\bin\Debug\WindowServiceDemo.exe
















Click on image for better view


Unistall the WindowService
installutil /u E:\WindowServiceDemo\WindowServiceDemo\bin\Debug\WindowServiceDemo.exe

















Click on image for better view


Step 6
Start and Stop the Service.

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.



Click on image for better view

Under the Service and application,Click on Services  you will see the service ServiceTest.Start and Stop menu item starts and stops the service.

















Click on image for better view

Step 7
After start the service then go to your directory and see if text file is there with contents or not.


Download
Download Source Code

Thursday, January 20, 2011

MS-SQL - Get the First and Last date of the Previous Month

In this article i will show you how to get first and last date of the previous month from the given date.

Step 1
First we create a user defined function GetFirstDate function,it is look like this

CREATE FUNCTION dbo.GetFirstDate(@OriginalDate datetime)
RETURNS varchar(50)
AS
    BEGIN
            
            DECLARE @FirstDate datetime
            
            SET @FirstDate=DATEADD(MONTH,-1,DATEADD(DAY,-DATEPART(Day,@OriginalDate)+1, @OriginalDate))
            
            RETURN Convert(varchar(50),@FirstDate,101)
    END

In this function we get first date of the previous month from given actual date value.

Step 2
Create a user defined function GetLastDate function,it is look like this


CREATE FUNCTION dbo.GetLastDate(@OriginalDate datetime) 
RETURNS varchar(50)
AS
    BEGIN
        DECLARE @LastDate datetime
        
        SET @LastDate=DATEADD(DAY,-DATEPART(DAY,@OriginalDate), @OriginalDate)
        
        RETURN Convert(varchar(50),@LastDate,101)
    END

In this function we get last date of the previous month from given actual date value.

Step 3
Call above user defined functions,it is look like this
--Date value must specify on this format ---  MM/DD/YYYY
    SELECT dbo.GetFirstDate('01/18/2010') as 'FirstDate of the Previous Month',
               dbo.GetLastDate('01/18/2010') as 'LastDate of the Previous Month'


Output





Download
Download SQL Script

LINQ - Insert,Update,Delete data in XML by using Linq to XML

In this article i will show you how to insert,update and delete data in xml by using LINQ to XML.

Step 1
Create a Console application and give the solution name as LinqToXML_IUD.

Step 2
In console application base directory(debug folder) insert XML file and give the file name as Customers.xml.

Step 3
The XML in the following example defines an XML document with a root node called Customers. This root node contains one or more nodes called Customer that include elements called ID,FirstName,LastName and Location.


<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer>
    <ID>1</ID>
    <FirstName>kishor</FirstName>
    <LastName>Naik</LastName>
    <Location>Mumbai</Location>
  </Customer>
</Customers>

Step 4
Create a Customer class in the solution,it is an entity class,it is look like this

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

namespace LinqToXML_IUD
{
    public class Customer
    {
        #region Property

        public int ID
        {
            get;
            set;
        }

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public String Location
        {
            get;
            set;
        }

        #endregion
    }
}

Step 5
Create a CustomerDAL static class in a solution for insert,update and delete data to XML document,it is look like this


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

namespace LinqToXML_IUD
{
    public static class CustomerDAL
    {
        #region Methods

        /// <summary>
        /// Insert Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Insert(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                // Load Xml Document
                System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                // Add the elements
                System.Xml.Linq.XElement XNew = new System.Xml.Linq.XElement("Customer",
                                                                new System.Xml.Linq.XElement("ID", CustomerObj.ID),
                                                                new System.Xml.Linq.XElement("FirstName", CustomerObj.FirstName),
                                                                new System.Xml.Linq.XElement("LastName", CustomerObj.LastName),
                                                                new System.Xml.Linq.XElement("Location", CustomerObj.Location)  
                                                                );

                XDoc.Add(XNew); 

                // Save the Xml File
                XDoc.Save(XmlFile);

                Flag = true; 
 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        /// <summary>
        /// Update Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Update(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                // Load Xml Document
                System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                // Obtain single customer data from XML file by passing CustomerID
                IEnumerable<System.Xml.Linq.XElement> Query = from Q in XDoc.Elements("Customer")
                                                              where Q.Element("ID").Value == Convert.ToString(CustomerObj.ID)
                                                              select Q; 
                                                      
                // Check the count is grether thae equal 1
                if (Query.Count() >= 1)
                {
                    // Replace the element
                    foreach (System.Xml.Linq.XElement X in Query)
                    {
                        X.SetElementValue("FirstName", CustomerObj.FirstName);
                        X.SetElementValue("LastName", CustomerObj.LastName);
                        X.SetElementValue("Location", CustomerObj.Location); 
   
                    }

                    // Save the Xml File
                    XDoc.Save(XmlFile);
                    Flag = true;  
                }

                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        /// <summary>
        /// Delete Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Delete(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                 String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                 // Load Xml Document
                 System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                 // Obtain single customer data from XML file by passing CustomerID
                 IEnumerable<System.Xml.Linq.XElement> Query = (from Q in XDoc.Elements("Customer")
                                                  where Q.Element("ID").Value == Convert.ToString(CustomerObj.ID)
                                                  select Q);

                 // Check the count is grether thae equal 1
                 if (Query.Count() >= 1)
                 {
                     // Remove the element
                     foreach (System.Xml.Linq.XElement X in Query)
                     {
                         X.Remove(); 
                     }

                     // Save the Xml File
                     XDoc.Save(XmlFile);
                     Flag = true; 
                 }

                 
                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        #endregion
    }
}

Step 6
Call a methods in Main function,it is look like this

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

namespace LinqToXML_IUD
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                #region Insert Section
                // Create a Object of Customer class
                Customer CustomerInsertObj = new Customer();

                // Add data in object
                CustomerInsertObj.ID = 6;
                CustomerInsertObj.FirstName = "Kakashi";
                CustomerInsertObj.LastName = "Hatake";
                CustomerInsertObj.Location = "Osaka";

                // Call Insert function
                if (CustomerDAL.Insert(CustomerInsertObj))
                {
                    System.Console.WriteLine("Insert Sucessfully");
                }


                #endregion


                //#region Update Section
                //// Create a Object of Customer class
                //Customer CustomerUpdateObj = new Customer();

                ////Add data in object
                //CustomerUpdateObj.ID = 6;
                //CustomerUpdateObj.FirstName = "Naruto";
                //CustomerUpdateObj.LastName = "OzoMaki";
                //CustomerUpdateObj.Location = "Osaka";

                //// Call Update function
                //if(CustomerDAL.Update(CustomerUpdateObj))
                //{
                //    System.Console.WriteLine("Update Sucessfully");   
                //}

                //#endregion


                //#region Delete Section
                //// Create a Object of Customer class
                //Customer CustomerDeleteObj = new Customer();

                ////Add data in object
                //CustomerDeleteObj.ID = 6;

                //// Call Delete function
                //if (CustomerDAL.Delete(CustomerDeleteObj))
                //{
                //    System.Console.WriteLine("Delete Sucessfully");   
                //}
                //#endregion

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

Run the project.

Download
Download Source Code

Tuesday, January 11, 2011

C#.net - Extract image from PDF file.

In this article i will show you how to extract image from PDF file.

Step 1
First you need to download "ITextSharp.dll" from the following link.
http://sourceforge.net/projects/itextsharp/

Step 2
Create a Console application and give the solution name as ConExtractImagefromPDF.

Step 3
Add two assembly reference to the project from solution explorer.

1.ITextSharp.dll




2.System.Drawing.dll






Step 4
Write a static method for extracting image from pdf file,it is look like this






/// <summary>
        ///  Extract Image from PDF file and Store in Image Object
        /// </summary>
        /// <param name="PDFSourcePath">Specify PDF Source Path</param>
        /// <returns>List</returns>
        private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
        {
            List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

            iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj = null;

            try
            {
                RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

                for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                             try
                                {

                                    iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                             new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);
                                    
                                    System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
                                   

                                    ImgList.Add(ImgPDF);

                                }
                                catch (Exception)
                                {
                                    
                                }
                        }
                    }
                }
                PDFReaderObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return ImgList;
        }


Step 5
Write a static method for store extracting image file in folder,it is look like this

 /// <summary>
        ///  Write Image File
        /// </summary>
        private static void WriteImageFile()
        {
            try
            {
                System.Console.WriteLine("Wait for extracting image from PDF file....");

                // Get a List of Image
                List<System.Drawing.Image> ListImage = ExtractImages(@"C:\Users\Kishor\Desktop\TuterPDF\ASP.net\ASP.NET 3.5 Unleashed.pdf");

                for (int i = 0; i < ListImage.Count; i++)
                {
                    try
                    {
                        // Write Image File
                        ListImage[i].Save(AppDomain.CurrentDomain.BaseDirectory + "ImageStore\\Image" + i + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        System.Console.WriteLine("Image" + i + ".jpeg write sucessfully"); 
                    }
                    catch (Exception)
                    { }
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

Step 6
Call above function in main method,it is look like this

static void Main(string[] args)
        {
            try
            {
                WriteImageFile(); // write image file
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);  
            }
        }

Full Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConExtractImagefromPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                WriteImageFile(); // write image file
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);  
            }
        }

        #region Methods

        /// <summary>
        ///  Extract Image from PDF file and Store in Image Object
        /// </summary>
        /// <param name="PDFSourcePath">Specify PDF Source Path</param>
        /// <returns>List</returns>
        private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
        {
            List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

            iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj = null;

            try
            {
                RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

                for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            try
                                {

                                    iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                             new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);
                                    
                                    System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
                                   

                                    ImgList.Add(ImgPDF);

                                }
                                catch (Exception)
                                {
                                    
                                }
                        }
                    }
                }
                PDFReaderObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return ImgList;
        }


        /// <summary>
        ///  Write Image File
        /// </summary>
        private static void WriteImageFile()
        {
            try
            {
                System.Console.WriteLine("Wait for extracting image from PDF file....");

                // Get a List of Image
                List<System.Drawing.Image> ListImage = ExtractImages(@"C:\Users\Kishor\Desktop\TuterPDF\ASP.net\ASP.NET 3.5 Unleashed.pdf");

                for (int i = 0; i < ListImage.Count; i++)
                {
                    try
                    {
                        // Write Image File
                        ListImage[i].Save(AppDomain.CurrentDomain.BaseDirectory + "ImageStore\\Image" + i + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        System.Console.WriteLine("Image" + i + ".jpeg write sucessfully"); 
                    }
                    catch (Exception)
                    { }
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}


Download
Download Source Code