Split Image File With Service in vb.net

By Amit Patel Oct 31, 2012
Split Multiple Image File With Service call every 5 minute using vb.net
Download Files: SplitImagesService.r
This Service Use For Split Image in Separate Page.
This Service Run only monday to friday 9am to 8pm every 5min.

First We Set Variable and Give the path.

SourcePath :
Give the g3n file folder path.
Destinationpath :
This Path Use for a converted file storage Purpose.
SubSoucePath :
This Path Use for a Store over g3n file backup.
ExtraBackupPath :
This Path Use for a store over second g3n file backup.
ErrorPath :
This Path Use for a store over Exception File.

app.config Code

<?xml version="1.0" encoding="utf-8" ?>
<!-- This Service Developed By Amit Patel-->
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
            <add name="DefaultSwitch" value="Information" />
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    <add key="SourcePath" value="D:\SplitImage\" />
    <add key="DestinationPath" value="D:\SplitImage\Temp" />
    <add key="SubSourcePath" value="D:\SplitImage\Completed\" />
    <add key="ErrorPath" value="D:\SplitImage\error\" />
    <add key="ExtraBackupPath" value="D:\SplitImage\ExtraBackup\" />
    <add key="ServiceRun_FromTime" value="09:00:00 AM"/>
    <add key="ServiceRun_ToTime" value="08:00:00 PM"/>
    <add key="ServiceRun_Days" value="mon,tue,wed,thu,fri"/>
    <add key ="ServiceRunInterval" value ="5000"/>
    <add key =""/>

Service1.vb Code

'This Service Developed By Amit Patel
#Region "Namespace"
Imports Log.Log
Imports DAL
Imports System.Text
Imports System.Timers
Imports System.IO
Imports System.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing.Imaging
Imports System.Drawing
#End Region

Public Class Service1
#Region "Variables"
    Dim RetVal
    Dim tmrOrderStatus As Timer = Nothing
    Dim StrMail As StringBuilder
    Dim ServiceRun_Days As String = Nothing
    Dim ServiceRun_FromTime As DateTime = Nothing
    Dim ServiceRun_ToTime As DateTime = Nothing
    Dim ServiceRunInterval As Long
    Dim ImageFiles1 As String = String.Empty
    Dim SourcePaths As String = String.Empty
    Dim DestinationPaths As String = String.Empty
    Dim SubSourcePaths As String = String.Empty
    Dim ErrorPaths As String = String.Empty
    Dim ExtraBackupPath As String = String.Empty
    Dim toAddr, fromAddr, ccAddr As String
    Dim NewName As String
    Dim Counter1, CounterLimit1
    Dim Intvl As Integer
    Dim ErrorNo As String = String.Empty
#End Region

#Region "Service Events"
    Protected Overrides Sub OnStart(ByVal args() As String)
            SourcePaths = System.Configuration.ConfigurationSettings.AppSettings.Get("SourcePath")
            DestinationPaths = System.Configuration.ConfigurationSettings.AppSettings.Get("DestinationPath")
            SubSourcePaths = System.Configuration.ConfigurationSettings.AppSettings.Get("SubSourcePath")
            ErrorPaths = System.Configuration.ConfigurationSettings.AppSettings.Get("ErrorPath")
            ExtraBackupPath = System.Configuration.ConfigurationSettings.AppSettings.Get("ExtraBackupPath")
            Intvl = Integer.Parse(System.Configuration.ConfigurationSettings.AppSettings.Get("ServiceRunInterval"))
            WriteLog("Image Splite Process Started Successfully...")
            If Int64.TryParse(ConfigurationManager.AppSettings.Get("PumpingInterval"), ServiceRunInterval) = False Then
                ServiceRunInterval = Intvl * 60
            End If
            ServiceRun_Days = TryCast(ConfigurationManager.AppSettings.Get("ServiceRun_Days"), String)
            If String.IsNullOrEmpty(ServiceRun_Days) = True Then ServiceRun_Days = "mon,tue,wed,thu,fri"
            ServiceRun_Days = ServiceRun_Days.ToLower
            tmrOrderStatus = New System.Timers.Timer
            If Now.Minute = 0 Then
                tmrOrderStatus.Interval = 0
                tmrOrderStatus.Interval = (60 - Now.Minute) * 85
            End If
            tmrOrderStatus.Enabled = True
            AddHandler tmrOrderStatus.Elapsed, AddressOf tmrOrderStatus_Elapsed
        Catch ex As Exception
            WriteLog(ex.ToString, EventLogEntryType.Error)
        End Try
    End Sub

    Protected Overrides Sub OnStop()
            WriteLog("Service stopped Successfully")
        Catch ex As Exception
            WriteLog(ex.ToString(), EventLogEntryType.Error)
        End Try
    End Sub
#End Region

#Region "Internal Functions"
    Private Sub tmrOrderStatus_Elapsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)

            If tmrOrderStatus.Interval <> Intvl * 60 Then tmrOrderStatus.Interval = Intvl * 60
            If ServiceRun_Days.Contains(Now.ToString("ddd").ToLower) = False Then Exit Sub
            If DateTime.TryParse(ConfigurationManager.AppSettings.Get("ServiceRun_FromTime"), ServiceRun_FromTime) = False Then
                ServiceRun_FromTime = New DateTime(Now.Year, Now.Month, Now.Day, 16, 0, 0)
            End If
            If DateTime.TryParse(ConfigurationManager.AppSettings.Get("ServiceRun_ToTime"), ServiceRun_ToTime) = False Then
                ServiceRun_ToTime = New DateTime(Now.Year, Now.Month, Now.Day, 20, 0, 0)
            End If
            If DateTime.Compare(Now, ServiceRun_FromTime) < 0 OrElse DateTime.Compare(Now, ServiceRun_ToTime) > 0 Then Exit Sub

            WriteLog("Call SplitImage")
            Counter1 = CheckFolder()
            If Counter1 > 1 Then
                Call MainFunction()
                WriteLog("No Record Found")
            End If
        Catch ex As Exception
            WriteLog(ex.ToString, EventLogEntryType.Error)
        End Try
    End Sub
    Public Function CheckFolder() As Integer
        Dim FSO, SourceFolder, ImageFiles, SourcePath ', DestinationPath

        FSO = CreateObject("Scripting.FileSystemObject")
        SourcePath = SourcePaths
        'DestinationPath = DestinationPaths
        SourceFolder = FSO.GetFolder(SourcePath)
        'get all the Files into the variable OrderFiles
        ImageFiles = SourceFolder.Files

        'Set the counter limit to the number of files that we want to transfer at one go.
        CounterLimit1 = 5
        Counter1 = 1
        For Each Orderfile In ImageFiles
            Counter1 = CInt(Counter1) + 1
        Return Counter1
    End Function

    Public Function MainFunction()
            Dim chk As Integer
            ErrorNo = ""
            ImageFiles1 = ""
            Dim FSO, SourceFolder, ImageFiles, SourcePath, DestinationPath, FolderName, SubSourceFolder, SubSourcePath, SubImageFiles, SubCompleteDestinationPath, ExtBackupPath
            Dim Counter, CounterLimit
            FSO = CreateObject("Scripting.FileSystemObject")
            SourcePath = SourcePaths
            DestinationPath = DestinationPaths
            SubSourcePath = SubSourcePaths
            SubSourceFolder = FSO.GetFolder(SubSourcePath)
            SubImageFiles = SubSourceFolder.Files
            'set the folder in that we have to search the G3N files
            SourceFolder = FSO.GetFolder(SourcePath)
            'get all the Files into the variable ImageFiles
            ImageFiles = SourceFolder.Files
            'File not Exist then File Creation

            If Not FSO.FolderExists(DestinationPath) Then
                FolderName = FSO.CreateFolder(DestinationPath)
            End If
            'Set the counter limit to the number of files that we want to transfer at one go.
            CounterLimit = 50
            Counter = 1
            'Loop for transfer G3N files one by one
            For Each Orderfile In ImageFiles
                If Counter > CounterLimit Then
                    Exit For
                End If
                chk = 0
                ErrorNo = ""
                ImageFiles1 = Orderfile.Name
                ErrorNo = Orderfile.Name
                'Check Same Name File And Store In Error path
                'For Each ImgFile In SubImageFiles
                '    If ImgFile.Name = Orderfile.Name Then
                '        FSO.MoveFile(SourcePath & "\" & Orderfile.Name, ErrorPaths)
                '        chk = 1
                '        Exit For
                '    End If
                SubCompleteDestinationPath = SubSourcePath & Now.ToString("dd-MMM-yyyy")
                If IO.Directory.Exists(SubCompleteDestinationPath) = False Then IO.Directory.CreateDirectory(SubCompleteDestinationPath)
                ExtBackupPath = ExtraBackupPath & Now.ToString("dd-MMM-yyyy")
                If IO.Directory.Exists(ExtBackupPath) = False Then IO.Directory.CreateDirectory(ExtBackupPath)
                    If chk = 0 Then
                        FSO.CopyFile(SourcePath & "\" & Orderfile.Name, ExtBackupPath & "\")
                        FSO.MoveFile(SourcePath & "\" & Orderfile.Name, SubCompleteDestinationPath & "\")
                        SplitImage(SubCompleteDestinationPath & "\" & ImageFiles1, DestinationPath & "\")
                    End If
                Catch ex As Exception
                    Dim FSO1
                    FSO1 = CreateObject("Scripting.FileSystemObject")
                    FSO1.MoveFile(SourcePath & "\" & Orderfile.Name, ErrorPaths)
                    WriteLog(ErrorNo + " : " + ex.ToString, EventLogEntryType.Error)
                End Try
                Counter = CInt(Counter) + 1
                ImageFiles1 = ""
            If Counter > 1 Then
                WriteLog(Counter - 1 & " : G3N File Completed")
            End If
        Catch ex As Exception           
            WriteLog(ErrorNo + " : " + ex.ToString, EventLogEntryType.Error)
        End Try
    End Function

    Public Function SplitImage(ByVal SourcePath As String, ByVal DestPath As String)
        Dim FileDateDestinationPath = DestPath & Now.ToString("dd-MMM-yyyy")
        If IO.Directory.Exists(FileDateDestinationPath) = False Then IO.Directory.CreateDirectory(FileDateDestinationPath)
        If SourcePath = "" And DestPath = "" Then
            WriteLog("No Data Found")
                'this code for get file/image name
                Dim Dir = SourcePath
                Dim path() As String = Dir.Split("\")
                Dim chunk As Integer = path.Length
                Dim ImageName As String = path(chunk - 1)
                ImageName = ImageName.Replace(".G3N", "")

                Dim pagecount, ImagePageCount As Integer
                Dim oimage As System.Drawing.Image = Nothing
                Dim fImage As Bitmap = Nothing
                Dim pageLoad As Boolean = False
                Dim docPath As String = FileDateDestinationPath & "\"
                    fImage = New Bitmap(SourcePath, False)
                    oimage = fImage
                    pagecount = oimage.GetFrameCount(FrameDimension.Page)
                    pageLoad = True
                Catch ex As Exception
                    Dim FSO
                    FSO = CreateObject("Scripting.FileSystemObject")
                    FSO.MoveFile(SourcePath, ErrorPaths)
                    pageLoad = False
                    WriteLog(ImageName + ".G3N " + ex.ToString, EventLogEntryType.Error)
                End Try
                If pageLoad = True Then
                    If pagecount <> 0 Then                       
                        For ImagePageCount = 0 To pagecount - 1
                            Dim strScanKey As String = System.Guid.NewGuid.ToString
                            oimage.SelectActiveFrame(FrameDimension.Page, ImagePageCount)
                            Dim img1 As Drawing.Bitmap = CType(oimage.Clone, Drawing.Bitmap)
                            Dim OrgImg As New Bitmap(img1)
                            Dim TarImg As New Bitmap(OrgImg.Width, OrgImg.Height)
                            Dim gr As Graphics = Graphics.FromImage(TarImg)
                            gr.DrawImage(OrgImg, 0, 0)
                            Dim documentPath As String = docPath & ImageName & "_" & ImagePageCount + 1 & ".jpg"
                    End If
                End If
            Catch ex As Exception
                WriteLog(ex.ToString, EventLogEntryType.Error)
            End Try
        End If
    End Function
#End Region

End Class


Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs