Split Image File With Service in vb.net

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-->
<configuration>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- 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"/> -->
        </sharedListeners>
    </system.diagnostics>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <appSettings>
    <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 =""/>
  </appSettings>
</configuration>


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)
        Try
            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
            Else
                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()
        Try
            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)
        Try

            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()
            Else
                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
        Next
        Return Counter1
    End Function

    Public Function MainFunction()
        Try
            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
                'Next
                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)
                Try
                    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
                Threading.Thread.Sleep(1000)
                Counter = CInt(Counter) + 1
                ImageFiles1 = ""
            Next
            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")
        Else
            Try
                '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 & "\"
                Try
                    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"
                            TarImg.Save(documentPath)
                            gr.Dispose()
                            'img1.Save(documentPath)                  
                        Next
                    End If
                    oimage.Dispose()
                    fImage.Dispose()
                End If
            Catch ex As Exception
                WriteLog(ex.ToString, EventLogEntryType.Error)
            End Try
        End If
    End Function
#End Region

End Class

Ebook Download
View all
Learn
View all