Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Linq
Imports System.Data
Imports System.Collections.Generic
Imports JF.PlmJobManager
Imports JF.PlmJobManager.JobServer
Imports JF.Tools

'' Script For MSC MultiSite Check via TaskSheduler: 
''  Date         Person        ChangeInfo
''  22.02.2018   S.Gueth       created
''  

'' #Doc: Parameter usage:
'' Parameter                           Description   
'' /SiteId=MySiteId                    SiteId where objects should be processed
'' /StatusToSet=RUN1                   Status that should be set
'' /ProcessGroupNumber=20              process group number
'' /PauseOnEnd=true/false              enables / disables  pause on end 		

Namespace JobMgrScript

    Public Class MarkObjectsToMigrate_EATON

        Public Function ScriptMain(ByVal JS_ScriptingInterface As JobServer.ScriptingInterface.Methodes) As JF_Return_cls

            ' Required class for returning script results
            Dim ScriptReturn_r As New JF_Return_cls
            Dim WaitTimeIn_MSec As Integer
            Dim SiteId As String = Nothing
            Dim StatusToSet As String = Nothing
            Dim ProcessGroupNumber As String = Nothing
            Dim PauseOnEnd As Boolean = False
            Dim SchriptParameter As String = JS_ScriptingInterface.ScriptDef.cmdPara

            '-- #Step: open the ScriptRun form  
            Dim ScriptOutput_frm As New JobServer.JobServer_ScriptRun_frm(JS_ScriptingInterface.ScriptDef)
            ScriptOutput_frm.Show()

            '-- for printing Informations to the header textbox 
            ScriptOutput_frm.InfoSysHeader.PrintObject("Script file", JS_ScriptingInterface.ScriptDef.Script_DPNE)
            ScriptOutput_frm.InfoSysHeader.PrintObject("Script description", JF.Tools.JF_ToolsFile.ParsePath_NE(JS_ScriptingInterface.ScriptDef.NameDescription))
            ScriptOutput_frm.InfoSysHeader.PrintObject("EATON", "Mark objects for migration")
            ScriptOutput_frm.InfoSysHeader.PrintObject("using Paramter", SchriptParameter)

            Try
                SiteId = JS_ScriptingInterface.ParameterValueGet("SiteId")
                StatusToSet = JS_ScriptingInterface.ParameterValueGet("StatusToSet")
                ProcessGroupNumber = JS_ScriptingInterface.ParameterValueGet("ProcessGroupNumber")
                PauseOnEnd = If(JS_ScriptingInterface.ParameterValueGet("PauseOnEnd") = "true", True, False)
                ScriptReturn_r.ResetToDefaultValues()
                ScriptOutput_frm.InfoSysHeader.Print("Mark objects for SiteId: " + SiteId)

                ' #Step 1: get list of all items from defined site id
                Dim cmd As System.Data.Common.DbCommand
                cmd = JS_ScriptingInterface.MyApplDataSourceObjGet.CreateCommandNew()
                cmd.CommandType = System.Data.CommandType.Text
                cmd.CommandText = String.Format("SELECT distinct " + vbCrLf +
                                                "    ObjectName as ItemId" + vbCrLf +
                                                "FROM " + vbCrLf +
                                                "    Objects_tbl " + vbCrLf +
                                                "where " + vbCrLf +
                                                "    ObjectClass = 'I' and " + vbCrLf +
                                                "    ObjectFromSiteID = '{0}'", SiteId)
                Dim DataTable_r As System.Data.DataTable = Nothing
                Dim JFReturn_Obj = JS_ScriptingInterface.MyApplDataSourceObjGet.cmdFillDataTable(cmd, DataTable_r)
                ScriptOutput_frm.InfoSysProtocol.PrintInfoLine("Rows: " + DataTable_r.Rows.Count.ToString)
                cmd = Nothing

                Dim index As Integer = 1
                Dim count As Integer = DataTable_r.Rows.Count()
                ' #Step 2: cycle through each item id
                For Each datarow As System.Data.DataRow In DataTable_r.Rows

                    ' get item ID
                    Dim itemId As String = datarow.Item("ItemId").ToString

                    ' create command to get ir from item id
                    Dim commandIR As System.Data.Common.DbCommand
                    commandIR = JS_ScriptingInterface.MyApplDataSourceObjGet.CreateCommandNew()
                    commandIR.CommandType = System.Data.CommandType.StoredProcedure
                    commandIR.CommandText = "Objects_tbl_Item_GetIRS"
                    Dim ItemName_SqlPara As New System.Data.SqlClient.SqlParameter("@ItemId", System.Data.SqlDbType.VarChar, 64) _
                    With {.IsNullable = False, .Direction = ParameterDirection.Input, .Value = itemId}
                    Dim ObjectFromSiteID_SqlPara As New System.Data.SqlClient.SqlParameter("@ObjectFromSiteID", System.Data.SqlDbType.VarChar, 32) _
                    With {.IsNullable = False, .Direction = ParameterDirection.Input, .Value = SiteId}
                    commandIR.Parameters.Add(ItemName_SqlPara)
                    commandIR.Parameters.Add(ObjectFromSiteID_SqlPara)

                    ' get irs from item id
                    Dim ReturnIR_Obj As New JF_Return_cls
                    ReturnIR_Obj.ErrUp = JF.Tools.BooleanTrueFalseToggle(JS_ScriptingInterface.MyApplDataSourceObjGet.cmdFillDataTable(commandIR, ReturnIR_Obj.ReturnDataTable))
                    commandIR = Nothing

                    ' get ir objects from datatable
                    Dim Irs_List As New List(Of Datasets_and_Irs_cls)
                    If ReturnIR_Obj.ResultIsEverythingOk Then
                        '-- #Step: alle gef. DS.DataRows der Datasets_and_Irs_List_r hinzug?gen
                        For Each ReturnDataTable_Row As DataRow In ReturnIR_Obj.ReturnDataTable.Rows
                            Dim Datasets_and_Irs_ObjCur As New Datasets_and_Irs_cls
                            Datasets_and_Irs_ObjCur.DataRow_TransTo_ObjectDef_Value(ReturnDataTable_Row)
                            Irs_List.Add(Datasets_and_Irs_ObjCur)
                        Next
                    End If

                    If Irs_List.Count = 0 Then Continue For

                    ' get item revision that should be migrated
                    Dim irToMigrate = IRToMigrateGet(Irs_List)

                    ' get all datasets of ir with status N
                    ' create command to get ir from item id
                    Dim commandDS As System.Data.Common.DbCommand
                    commandDS = JS_ScriptingInterface.MyApplDataSourceObjGet.CreateCommandNew()
                    commandDS.CommandType = System.Data.CommandType.Text
                    commandDS.CommandText = "SELECT " + vbCrLf +
                                            "   DS.* " + vbCrLf +
                                            "FROM " + vbCrLf +
                                            "   dbo.Objects_tbl IR " + vbCrLf +
                                            "   INNER JOIN dbo.Objects_Ir_Rel_tbl IR_DS_REL ON (IR.Id = IR_DS_REL.IrId) " + vbCrLf +
                                            "   INNER Join dbo.Objects_tbl DS ON (IR_DS_REL.ObjectId = DS.Id) " + vbCrLf +
                                            "WHERE " + vbCrLf +
                                            "   IR.ObjectName = '" + irToMigrate.ObjectName + "' AND " + vbCrLf +
                                            "   IR.ObjectFromSiteID = '" + SiteId + "' AND " + vbCrLf +
                                            "   IR.ObjectClass = 'IR' AND " + vbCrLf +
                                            "   DS.ObjectClass = 'DS' AND " + vbCrLf +
                                            "   DS.ProcStateCol" + ProcessGroupNumber + " = 'N'"

                    Dim ReturnDS_Obj As New JF_Return_cls
                    ReturnDS_Obj.ErrUp = JF.Tools.BooleanTrueFalseToggle(JS_ScriptingInterface.MyApplDataSourceObjGet.cmdFillDataTable(commandDS, ReturnDS_Obj.ReturnDataTable))
                    commandDS = Nothing

                    ' get dataset objects from datatable
                    Dim Datasets_List As New List(Of Datasets_and_Irs_cls)
                    If ReturnDS_Obj.ResultIsEverythingOk Then
                        '-- #Step: alle gef. DS.DataRows der Datasets_List_r hinzug?gen
                        For Each ReturnDataTable_Row As DataRow In ReturnDS_Obj.ReturnDataTable.Rows
                            Dim Datasets_and_Irs_ObjCur As New Datasets_and_Irs_cls
                            Datasets_and_Irs_ObjCur.DataRow_TransTo_ObjectDef_Value(ReturnDataTable_Row)
                            Datasets_List.Add(Datasets_and_Irs_ObjCur)
                        Next
                    End If

                    ' add objects where status should be set to list
                    For Each Dataset As Datasets_and_Irs_cls In Datasets_List

                        Dim DSEdit_new_OBJ = New DSEdit_cls()
                        With DSEdit_new_OBJ
                            .DS.Ir.ObjectFromSiteID = SiteId
                            .DS.Ir.ItemName = Dataset.ObjectCliNameParse_Obj.Item
                            .DS.Ir.Rev = Dataset.ObjectCliNameParse_Obj.Rev
                            .DS.DatasetObjectType = Dataset.ObjectCliNameParse_Obj.ObjectTypeTC
                            .EditValue.ValueNew = StatusToSet

                            '-- Process Status aendern
                            .ColumeNameEditTarget_SetBy_ProcStateColNum = ProcessGroupNumber
                            Dim MyCallReturn As JF_Return_cls = JS_ScriptingInterface.DS_Edit_ProcessState(DSEdit_new_OBJ)
                            If index Mod 10 = 0 Then
                                Call ScriptOutput_frm.InfoSysProtocol.Print("[" + index.ToString() + "/" + count.ToString + "] -> Done:" + MyCallReturn.ResultMsg)
                            End If
                        End With

                    Next

                    index += 1
                Next


            Catch ex As Exception
                ScriptReturn_r.Ex = ex
                ScriptReturn_r.ExMsg = "Exeption in script:" + JS_ScriptingInterface.ScriptDef.NameDescription
                ScriptOutput_frm.InfoSysProtocol.PrintEx(ex, "MultiSiteCheck.ScriptMain")
            End Try

            If PauseOnEnd Then
                ScriptOutput_frm.Pause()
            Else
                WaitTimeIn_MSec = 2500
                ScriptOutput_frm.InfoSysProtocol.Print_and_StatusBarSetCurrActionStatusInfo_Panel3("wait:" + (WaitTimeIn_MSec / 1000).ToString("#.#") + " sec")
                System.Threading.Thread.Sleep(WaitTimeIn_MSec)
            End If


            '-- #Step: closing the ScriptRun form 
            ScriptOutput_frm.Close()
            ScriptOutput_frm.Dispose()

            Return ScriptReturn_r
        End Function

        ''' <summary>
        ''' function to get the item revision, that should be migrated
        ''' </summary>
        ''' <param name="IRsOfItem"></param>
        ''' <remarks> 
        ''' #New: 3.1454;23.02.2018;S.Gueth
        ''' </remarks>
        Public Function IRToMigrateGet(ByRef IRsOfItem As List(Of Datasets_and_Irs_cls)) As Datasets_and_Irs_cls

            Dim IRsOrderByCreateDateDescending As List(Of Datasets_and_Irs_cls) = IRsOfItem.OrderByDescending(Function(ir) ir.ObjectCreateDate).ToList

            For Each ir As Datasets_and_Irs_cls In IRsOrderByCreateDateDescending

                If ir.ObjectReleaseState.Contains("130") Or
                   ir.ObjectReleaseState.Contains("230") Or
                   ir.ObjectReleaseState.Contains("330") Or
                   ir.ObjectReleaseState.Contains("410") Or
                   ir.ObjectReleaseState.Contains("430") Or
                   ir.ObjectReleaseState.Contains("900") Then

                    Return ir

                End If

            Next

            Return IRsOrderByCreateDateDescending.Item(0)

        End Function

    End Class
End Namespace






















