Imports System.Collections.ObjectModel
Imports System.IO
Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.DataLayer.DatabaseModels
Imports EgtUILib
Imports EgtWPFLib5

Public Class ProjManagerVM
   Inherits VMBase

#Region "FIELDS & PROPERTIES"

   ' Nome file NGE con i pezzi selezionati per effettuare UpdateBTL
   Friend Const UPDATEBTL_NGE As String = "UpdateBTL.nge"

   Private m_ProjManager_IsEnabled As Boolean = True
   Public ReadOnly Property ProjManager_IsEnabled As Boolean
      Get
         Return m_ProjManager_IsEnabled
      End Get
   End Property

   Private m_CurrProj As ProjFileVM
   Friend Property CurrProj As ProjFileVM
      Get
         Return m_CurrProj
      End Get
      Set(value As ProjFileVM)
         m_CurrProj = value
      End Set
   End Property

   Private m_TempCurrProj As ProjFileVM
   Friend Property TempCurrProj As ProjFileVM
      Get
         Return m_TempCurrProj
      End Get
      Set(value As ProjFileVM)
         m_TempCurrProj = value
      End Set
   End Property

   Private m_IsEnabled As Boolean
   Public Property IsEnabled As Boolean
      Get
         Return m_IsEnabled
      End Get
      Set(value As Boolean)
         If value <> m_IsEnabled Then
            m_IsEnabled = value
            NotifyPropertyChanged("IsEnabled")
         End If
      End Set
   End Property

   ' indice ultimo progetto
   Private m_nLastProjId As Integer
   Friend ReadOnly Property nLastProjId As Integer
      Get
         Return m_nLastProjId
      End Get
   End Property

   Public ReadOnly Property nProjType As BWType
      Get
         Return If(Not IsNothing(CurrProj), CurrProj.nType, BWType.NULL)
      End Get
   End Property

   ' indice progetto in caricamento
   Private m_nLoadingProjId As Integer = 0
   Public ReadOnly Property nLoadingProjId As Integer
      Get
         Return m_nLoadingProjId
      End Get
   End Property

   Friend m_MruFiles As New MruList
   Public ReadOnly Property MruFileNames As ObservableCollection(Of String)
      Get
         Dim IdAndBTLFileNames As New ObservableCollection(Of String)
         For Each FileName In m_MruFiles.FileNames.ToList()
            Dim PjId As Integer = 0
            Dim sPjId As String = Path.GetFileNameWithoutExtension(DirectCast(FileName, String).Replace("__", "_"))
            Integer.TryParse(sPjId, PjId)
            Dim PjFileM = DbControllers.m_ProjController.FindByProjIdConv(PjId)
            If IsNothing(PjFileM) Then
               m_MruFiles.Remove(FileName)
            Else
               IdAndBTLFileNames.Add(sPjId & " | " & PjFileM.sBTLFileName)
            End If
         Next
         Return IdAndBTLFileNames
      End Get
   End Property

   Private m_UpdateBTL_Visibility As Visibility = Visibility.Collapsed
   Public Property UpdateBTL_Visibility As Visibility
      Get
         Return m_UpdateBTL_Visibility
      End Get
      Set(value As Visibility)
         m_UpdateBTL_Visibility = value
      End Set
   End Property

   ' Definizione comandi
   Private m_cmdNew As ICommand
   Private m_cmdOpen As ICommand
   Private m_cmdOpenMruFile As ICommand
   Private m_cmdSave As ICommand
   Private m_cmdSaveAs As ICommand
   Private m_cmdExport As ICommand
   Private m_cmdDxfOut As ICommand
   Private m_cmdImportBTL As ICommand
   Private m_cmdUpdateBTL As ICommand
   Private m_cmdImportProject As ICommand
   Private m_cmdExportProject As ICommand
   Private m_cmdGoToProd As ICommand
   Private m_cmdSendFeedback As ICommand

#Region "ToolTip"

   'Proprietà ToolTip
   Public ReadOnly Property NewToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 1)
      End Get
   End Property
   Public ReadOnly Property OpenToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 2)
      End Get
   End Property
   Public ReadOnly Property SaveToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 3)
      End Get
   End Property
   Public ReadOnly Property SaveAsToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 4)
      End Get
   End Property
   Public ReadOnly Property InsertToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 5)
      End Get
   End Property
   Public ReadOnly Property ImportBTL_ToolTip As String
      Get
         Return EgtMsg(61840)
      End Get
   End Property
   Public ReadOnly Property UpdateBTL_ToolTip As String
      Get
         Return EgtMsg(61834)
      End Get
   End Property
   Public ReadOnly Property ExportProject_ToolTip As String
      Get
         Return EgtMsg(61838)
      End Get
   End Property
   Public ReadOnly Property ImportProject_ToolTip As String
      Get
         Return EgtMsg(61839)
      End Get
   End Property
   Public ReadOnly Property GoToProd_ToolTip As String
      Get
         Return EgtMsg(61835)
      End Get
   End Property

#End Region ' ToolTip

#End Region    ' Fields & Properties

#Region "CONSTRUCTOR"

   Sub New()
      ' Creo riferimento a questa classe in Map
      Map.SetRefProjManagerVM(Me)
      ' Leggo ultimo indice di progetto
      m_nLastProjId = GetMainPrivateProfileInt(S_GENERAL, K_PROJSINDEX, 1)
      ' Impostazioni MruLists
      m_MruFiles.Init(S_MRUPROJFILES, 8)
      ' leggo attivazione update btl
      If GetMainPrivateProfileInt(S_GENERAL, K_UPDATEBTL, 0) > 0 Then
         UpdateBTL_Visibility = Visibility.Visible
      End If
   End Sub

#End Region    ' CONSTRUCTOR

#Region "METHODS"

   Private Sub NewProdFromProj()
      ' inizializzo nuovo progetto
      Dim nProdId As Integer = 0
      Dim sProdDir As String = ""
      Map.refProdManagerVM.InitNewProject(m_CurrProj.nProjId, nProdId, sProdDir)
      ' setto il PType del Prod
      DbControllers.m_ProdController.UpdatePType(nProdId, CurrProj.nType)
      ' setto la Macchina associata al Prod
      DbControllers.m_ProdController.UpdateMachine(nProdId, CurrProj.sMachine)
      ' copio file progetto
      Dim sProjPath As String = String.Empty
      Dim bOk = False
      Dim sProdPath As String = sProdDir & "\" & nProdId.ToString("0000") & ".nge"
      If EgtGetCurrFilePath(sProjPath) AndAlso Not String.IsNullOrEmpty(sProjPath) Then
         Try
            File.Copy(sProjPath, sProdPath)
            'Map.refSceneHostVM.MainController.OpenProject(sProdPath)
            bOk = True
         Catch ex As Exception
            EgtOutLog("Impossibile copiare il file")
            bOk = False
         End Try
      End If
      If bOk Then
         ' aggiorno path proj
         Map.refProjManagerVM.UpdateCurrProj()
         ' imposto currprod
         Map.refProdManagerVM.SetCurrProd(nProdId)
         ' imposto TempCurrProd
         Map.refProdManagerVM.TempCurrProd = Map.refProdManagerVM.CurrProd
         ' setto flag nuovo progetto in prod
         Map.refProdManagerVM.CurrProd.bIsNew = True
      Else
         ' elimino da DB
         DbControllers.m_ProdController.DeleteProd(nProdId, True)
      End If
   End Sub

   Private Function InitNewProject(ByRef nProjId As Integer, ByRef sProjectDir As String, nType As BWType, Machine As Machine) As Boolean
      ' se non ho ricevuto numero progetto da sovrascrivere
      If nProjId = 0 Then
         ' richiedo indice nuovo progetto
         nProjId = DbControllers.m_ProjController.GetNextIndex(Map.refMainWindowVM.MainWindowM.GetKeyNumber())
      End If
      ' salvo data creazione progetto
      DbControllers.m_ProjController.Update(New ProjModel() With {.ProjId = nProjId,
                                                                  .DtCreated = DateTime.Now(),
                                                                  .PType = nType,
                                                                  .Machine = If(Not IsNothing(Machine), Machine.Name, Nothing)})
      If nProjId <= 0 Then Return False
      sProjectDir = refMainWindowVM.MainWindowM.sProjsDir & "\" & nProjId.ToString("0000")
      ' creo cartella nuovo progetto
      If Not Directory.Exists(sProjectDir) Then
         Directory.CreateDirectory(sProjectDir)
      Else
         Dim di As System.IO.DirectoryInfo = New DirectoryInfo(sProjectDir)
         For Each file As FileInfo In di.EnumerateFiles()
            file.Delete()
         Next
         For Each dir As DirectoryInfo In di.EnumerateDirectories()
            dir.Delete(True)
         Next
      End If
      Return True
   End Function

   Private Function UpdateProjData(nProjId As Integer, nProdId As Integer, dtExportDate As DateTime,
                                   sListName As String)
      Return DbControllers.m_ProjController.Update(New ProjModel() With {.ProjId = nProjId,
                                                                  .DtExported = dtExportDate,
                                                                  .ListName = sListName})
   End Function

   'Private Function UpdateBTLFileName(nProjId As Integer, BTLFileName As String)
   '    Return DbControllers.m_ProjController.Update(New ProjModel() With {.ProjId = nProjId,
   '                                                              .BTLFileName = BTLFileName})
   'End Function

   ''' <summary>
   ''' Aggiornamento descrizione del PROJ con nuova colonna
   ''' </summary>
   ''' <param name="nProjId"></param>
   ''' <param name="Description"></param>
   ''' <returns></returns>
   Private Function UpdateDescription(nProjId As Integer, Description As String)
      Return DbControllers.m_ProjController.UpdateDescription(nProjId, Description)
   End Function

   Public Function SetCurrProj(nProjId As Integer) As Boolean
      Dim Currproj As ProjFileM = DbControllers.m_ProjController.FindByProjIdConv(nProjId)
      If IsNothing(Currproj) Then Return False
      m_CurrProj = New ProjFileVM(Currproj)
      Return True
   End Function

   Public Function UpdateCurrProj() As Boolean
      Return SetCurrProj(CurrProj.nProjId)
   End Function

   Public Sub ResetCurrProj()
      CurrProj = Nothing
   End Sub

   Friend Sub SetProjManagerIsEnabled(bIsEnabled As Boolean)
      m_ProjManager_IsEnabled = bIsEnabled
      NotifyPropertyChanged(NameOf(ProjManager_IsEnabled))
   End Sub

   Private Sub ReloadBTLStructure()
      Map.refProjectVM.BTLStructureVM = New BTLStructureVM(BTLStructureM.CreateBTLStructure(Map.refProjManagerVM.CurrProj.nProjId))
      ' verifico se volume pezzi calcolato
      Dim bIsCalculated As Boolean = False
      For Each BTLPart In Map.refProjectVM.BTLStructureVM.BTLPartVMList
         If BTLPart.BTLPartM.dVolume > 0 Then Continue For
         bIsCalculated = True
         BTLPart.CalcBTLPartVolume()
      Next
      If bIsCalculated Then
         Dim CurrProject As String = ""
         EgtGetCurrFilePath(CurrProject)
         EgtSaveFile(CurrProject, NGE.CMPTEXT)
      End If
   End Sub

#End Region    ' METHODS

#Region "COMMANDS"

#Region "New"

   ''' <summary>
   ''' Returns a command that do Save.
   ''' </summary>
   Public ReadOnly Property New_Command As ICommand
      Get
         If m_cmdNew Is Nothing Then
            m_cmdNew = New Command(AddressOf NewProject)
         End If
         Return m_cmdNew
      End Get
   End Property

   ''' <summary>
   ''' Execute the Save.  This method is invoked by the SaveCommand.
   ''' </summary>
   Public Sub NewProject()
      ' verifico se progetto modificato, e chiedo se salvare
      If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return
      ' se si ha una sola macchina disponibile (non BOTH) setto il nuovo porgetto a quella macchina e al tipo progetto associato 
      ' altrimenti apro il dialog per scegliere la macchina e il tipo progetto a cui settare il nuovo progetto
      Dim Machine As Machine = Nothing
      Dim nType As BWType = BWType.NULL
      Dim ProjectTypeWndVM As New ProjectTypeWndVM()
      If ProjectTypeWndVM.MachineList.Count = 1 AndAlso DirectCast(ProjectTypeWndVM.SelMachine, MyMachine).nType <> MachineType.BOTH Then
         Machine = ProjectTypeWndVM.SelMachine
         nType = DirectCast(Machine, MyMachine).nType
      Else
         Dim ProjectTypeWnd As New ProjectTypeWndV(Application.Current.MainWindow, ProjectTypeWndVM)
         If ProjectTypeWnd.ShowDialog() Then
            Machine = ProjectTypeWndVM.SelMachine
            nType = ProjectTypeWndVM.nSelType
         Else
            Return
         End If
      End If
      ' creo nuovo progetto
      If Map.refSceneHostVM.MainController.NewProject() Then
         ' inizializzo nuovo progetto
         Dim nProjId As Integer = 0
         Dim sProjDir As String = ""
         InitNewProject(nProjId, sProjDir, nType, Machine)
         SetCurrProj(nProjId)
         ' carico lista macchine e macchina del progetto per il pulsante Reset Macchina del CALCPanel
         Map.refCALCPanelVM.LoadMachineList()
         Dim sProjFileName As String = sProjDir & "\" & nProjId.ToString("0000") & ".nge"
         ' imposto ProjId di caricamento
         m_nLoadingProjId = nProjId
         ' creo gruppo BTLinfo
         Dim nBTLInfoLayer As Integer = EgtCreateGroup(GDB_ID.ROOT)
         EgtSetName(nBTLInfoLayer, BTLINFO)
         EgtSetLevel(nBTLInfoLayer, GDB_LV.SYSTEM)
         Map.refProjectVM.BTLStructureVM.BTLStructureM.UpdateBTLInfoLayer()
         ' scrivo info proj e tipo su layer BtlInfo
         EgtSetInfo(nBTLInfoLayer, BTL_PRT_PROJ, nProjId)
         EgtSetInfo(nBTLInfoLayer, BTL_GEN_PROJTYPE, nType)
         ' salvo il progetto
         If EgtSaveFile(sProjFileName, NGE.CMPTEXT) Then
            SectionXMaterial.SetType(nType)
            Core.ViewPanelVM.UpdateBWType(nType)
            Map.refPartManagerVM.LockVisibilityUpdate()
            ' imposto flag secondo tipo di progetto (travi o pareti)
            Dim sBTLFlag As String = If(nType = Core.ConstBeam.BWType.BEAM, K_BTLFLAG, K_WALLBTLFLAG)
            Dim nFlag As Integer = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)
            EgtBeamSetFlag(nFlag)
            DbControllers.m_ProjController.UpdateInfo(nProjId, "Hand made", "Hand made", "", Date.MinValue, nType, Map.refMachinePanelVM.SelectedMachine.Name)
            SetCurrProj(nProjId)
         End If
         Map.refProjectVM.SetOptimizePanel_Visibility(Map.refProjectVM.BTLStructureVM.nPROJTYPE = BWType.WALL AndAlso Map.refMainWindowVM.MainWindowM.GetKeyOption(KEY_OPT.NESTING_AUTO))
      Else
         MessageBox.Show(EgtMsg(61876))
      End If
      Map.refMainWindowVM.UpdateTitle()
      NotifyPropertyChanged(NameOf(MruFileNames))
   End Sub

#End Region ' New

#Region "OpenCommand"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property OpenCommand As ICommand
      Get
         If m_cmdOpen Is Nothing Then
            m_cmdOpen = New Command(AddressOf Open)
         End If
         Return m_cmdOpen
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Friend Sub Open()
      ' verifico se progetto modificato, e chiedo se salvare
      If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return
      OpenProject(Nothing)
   End Sub

   Friend Sub OpenProject(ReceivedCurrProj As ProjFileVM)
      Dim bStart As Boolean = IsNothing(m_TempCurrProj)
      m_TempCurrProj = ReceivedCurrProj
      ' se la stringa è vuota
      If IsNothing(TempCurrProj) Then
         If GetMainPrivateProfileInt(S_GENERAL, K_PROJECTMODE, 0) = 1 Then
            Dim OpenProdFileDialogVM As NewOpenProjectFileDialogVM = Nothing
            ' apro dialogo di scelta Prod
            OpenProdFileDialogVM = New NewOpenProjectFileDialogVM
            Dim OpenFile As New NewOpenProjectFileDialogV(Application.Current.MainWindow, OpenProdFileDialogVM)
            Dim DialogResult As Boolean? = OpenFile.EgtShowDialog(ProjectType.PROJ)
            If IsNothing(DialogResult) OrElse Not DialogResult Then Return
            Dim TempProd As ProdItem = OpenProdFileDialogVM.SelProject
            If TempProd.ProjFileList.Count > 1 Then
               ' apro dialogo di scelta Proj
               Dim OpenProjFileDialogVM As OpenProjectFileDialogVM = Nothing
               OpenProjFileDialogVM = New OpenProjectFileDialogVM
               Dim ProjOpenFile As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjFileDialogVM)
               Dim ProjDialogResult As Boolean? = ProjOpenFile.EgtShowDialog(ProjectType.PROJ, OpenProdFileDialogVM.SelProject.ProjFileList)
               If IsNothing(DialogResult) OrElse Not ProjDialogResult Then Return
               TempCurrProj = OpenProjFileDialogVM.SelProject
            ElseIf TempProd.ProjFileList.Count = 1 Then
               TempCurrProj = OpenProdFileDialogVM.SelProject.ProjFileList(0)
            Else Return
            End If
         Else
            Dim OpenProjectFileDialogVM As OpenProjectFileDialogVM = Nothing
            ' apro dialogo di scelta file
            OpenProjectFileDialogVM = New OpenProjectFileDialogVM
            Dim OpenFile As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjectFileDialogVM)
            Dim DialogResult As Boolean? = OpenFile.EgtShowDialog(ProjectType.PROJ)
            If IsNothing(DialogResult) OrElse Not DialogResult Then Return
            TempCurrProj = OpenProjectFileDialogVM.SelProject
         End If
      End If
      LoadingWndHelper.OpenLoadingWnd(ActiveIds.OPENPROJ, 3, EgtMsg(63000), EgtMsg(63001), 50)       ' Project opening    ' Loading project geometries
      ' imposto ProjId di caricamento
      m_nLoadingProjId = TempCurrProj.nProjId
      ' se esiste prod prendo quello, altrimenti proj
      Dim sFilePath As String = ""
      If Not IsNothing(TempCurrProj.nProdId) AndAlso TempCurrProj.nProdId > 0 Then
         sFilePath = TempCurrProj.sProdPath
      Else
         sFilePath = TempCurrProj.sProjPath
      End If
      SectionXMaterial.SetType(TempCurrProj.nType)
      Core.ViewPanelVM.UpdateBWType(TempCurrProj.nType)
      ' imposto flag secondo tipo di progetto (travi o pareti)
      Dim sBTLFlag As String = If(TempCurrProj.nType = Core.ConstBeam.BWType.BEAM, K_BTLFLAG, K_WALLBTLFLAG)
      Dim nFlag As Integer = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)
      EgtBeamSetFlag(nFlag)
      ' se la macchina del progetto in apertura non è tra le macchine disponibili lo segnalo e apro un progetto vuoto
      If IsNothing(Map.refMachinePanelVM.MachineList.FirstOrDefault(Function(x) x.Name = Map.refProjManagerVM.TempCurrProj.sMachine)) Then
         ' rimuovo il file in apertura dalla lista degli MRU
         Dim ProjId As Integer = Map.refProjManagerVM.nLoadingProjId
         Dim PjFileVM As ProjFileVM
         If Not IsNothing(ProjId) AndAlso ProjId <> 0 Then
            PjFileVM = New ProjFileVM(DbControllers.m_ProjController.FindByProjIdConv(ProjId))
            If Not IsNothing(PjFileVM.ProjFileM) AndAlso Not IsNothing(PjFileVM.sProjPath) Then Map.refProjManagerVM.m_MruFiles.Remove(PjFileVM.sProjPath)
         End If
         MessageBox.Show(EgtMsg(61885), EgtMsg(10001), MessageBoxButton.OK, MessageBoxImage.Error)        'Error
         If bStart Then Map.refProjManagerVM.NewProject()
      Else
         If Map.refSceneHostVM.MainController.OpenProject(sFilePath, False) Then
            Map.refProjectVM.SetOptimizePanel_Visibility(Map.refProjectVM.BTLStructureVM.nPROJTYPE = BWType.WALL AndAlso Map.refMainWindowVM.MainWindowM.GetKeyOption(KEY_OPT.NESTING_AUTO))
            Map.refPartManagerVM.LockVisibilityUpdate()
         End If
      End If
      ' aggiorno titolo
      Map.refMainWindowVM.UpdateTitle()
      NotifyPropertyChanged(NameOf(MruFileNames))
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.OPENPROJ)
   End Sub

#End Region ' OpenCommand

#Region "OpenMruFileCommand"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property OpenMruFileCommand As ICommand
      Get
         If m_cmdOpenMruFile Is Nothing Then
            m_cmdOpenMruFile = New Command(AddressOf OpenMruFile)
         End If
         Return m_cmdOpenMruFile
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Public Sub OpenMruFile(ByVal param As Object)
      ' verifico se progetto modificato, e chiedo se salvare
      If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return
      ' ricavo l'Id e il progetto associato per l'apertura di quest'ultimo
      Dim PjId As Integer = 0
      Dim arrStrPjId As String() = DirectCast(param, String).Split("|")
      Integer.TryParse(arrStrPjId(0), PjId)
      Dim PjFileM = DbControllers.m_ProjController.FindByProjIdConv(PjId)
      Dim PjFileVM = New ProjFileVM(PjFileM)
      OpenProject(PjFileVM)
   End Sub

#End Region ' OpenMruFileCommand

#Region "SaveCommand"

   ''' <summary>
   ''' Returns a command that do Save.
   ''' </summary>
   Public ReadOnly Property SaveCommand As ICommand
      Get
         If m_cmdSave Is Nothing Then
            m_cmdSave = New Command(AddressOf SaveCmd)
         End If
         Return m_cmdSave
      End Get
   End Property

   Public Sub SaveCmd()
      Save(True)
   End Sub

   ''' <summary>
   ''' Execute the Save.  This method is invoked by the SaveCommand.
   ''' </summary>
   Public Sub Save(Optional bShowLoading As Boolean = False)
      If IsNothing(CurrProj) Then Return
      Dim bShowBuilding As Boolean = False
      Dim bShowSolid As Boolean = False
      If bShowLoading Then LoadingWndHelper.OpenLoadingWnd(ActiveIds.SAVEPROJ, 1, EgtMsg(63007), "", 100)            ' Project saving
      ' se vista tutti i pezzi
      If Map.refShowBeamPanelVM.bShowAll Then
         ' verifico se assemblato e lo annullo per salvataggio
         bShowBuilding = Map.refShowBeamPanelVM.ShowBuilding_IsChecked
         If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(False, False)
         ' se vista singolo pezzo
      Else
         bShowSolid = Map.refShowBeamPanelVM.ShowSolid_IsChecked
         If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, False, False)
      End If
      ' imposto ProjId di caricamento
      m_nLoadingProjId = CurrProj.nProjId
      Map.refSceneHostVM.SaveProject()
      Map.refMainWindowVM.SetTitle(CurrProj.nProjId.ToString("0000") & " - " & CurrProj.sBTLFileName & " - EgtBEAMWALL")
      ' aggiorno BTLParts su DB
      DbControllers.m_ProjController.UpdateBtlParts(CurrProj.nProjId, Map.refProjectVM.BTLStructureVM.BTLStructureM.BTLPartMList)
      ' se nuovo progetto
      If m_CurrProj.bIsNew Then
         ' resetto stato new
         DbControllers.m_ProjController.ResetNew(CurrProj.nProjId)
         m_CurrProj.bIsNew = False
      End If
      ' se assemblato lo ripristino
      If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
      If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, True, False)
      ' verifico se Reset Macchina modificato e nel caso aggiorno DB e CurrProj
      If Map.refCALCPanelVM.IsMachineModified() Then
         DbControllers.m_ProjController.UpdateMachine(Map.refProjManagerVM.CurrProj.nProjId, Map.refCALCPanelVM.SelectedMachine.Name)
         Map.refProjManagerVM.CurrProj.SetMachine(Map.refCALCPanelVM.SelectedMachine.Name)
         ' se esiste un Prod associato al Proj corrente aggiorno anche questo Prod nel DB 
         If Map.refProjManagerVM.CurrProj.nProdId > 0 Then DbControllers.m_ProdController.UpdateMachine(Map.refProjManagerVM.CurrProj.nProdId,
                                                                                                        Map.refCALCPanelVM.SelectedMachine.Name)
         Map.refCALCPanelVM.ResetMachineModified()
      End If
      ' aggiorno titolo
      Map.refMainWindowVM.UpdateTitle()
      NotifyPropertyChanged(NameOf(MruFileNames))
      If bShowLoading Then LoadingWndHelper.CloseLoadingWnd(ActiveIds.SAVEPROJ)
   End Sub

#End Region ' SaveCommand

#Region "ImportBTL"

   ''' <summary>
   ''' Returns a command that do Export.
   ''' </summary>
   Public ReadOnly Property ImportBTL_Command As ICommand
      Get
         If m_cmdImportBTL Is Nothing Then
            m_cmdImportBTL = New Command(AddressOf ImportBTL)
         End If
         Return m_cmdImportBTL
      End Get
   End Property

   ''' <summary>
   ''' Execute the ImportBTL.  This method is invoked by the ImportBTLCommand.
   ''' </summary>
   Public Sub ImportBTL(Optional sFile As String = "", Optional bWithDlg As Boolean = True)
      If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return
      Dim sDir As String = String.Empty
      GetMainPrivateProfileString(S_GENERAL, K_LASTIMPDIR, "", sDir)
      If bWithDlg Then
         ' apro finestra scelta file
         Dim BTLDlg As New Microsoft.Win32.OpenFileDialog() With {
               .DefaultExt = ".btl",
               .Filter = "BTL (*.btl)|*.btl" &
                         "|BTLX (*.btlx)|*.btlx",
               .InitialDirectory = If(Directory.Exists(sDir), sDir, ""),
               .CheckFileExists = True,
               .ValidateNames = True}
         If BTLDlg.ShowDialog() Then
            sFile = BTLDlg.FileName
         Else
            Return
         End If
      End If
      Dim nProjId As Integer = 0
      Dim sProjDir As String = ""
      ' verifico se non e' tra i BTL gia' importati
      Dim sBTLFileName As String = Path.GetFileNameWithoutExtension(sFile)
      Dim nAlreadyImported As Integer = DbControllers.m_ProjController.AlreadyImported(sBTLFileName)
      If nAlreadyImported > 0 Then
         ' recupero progetto con lo stesso nome
         Dim ToDeleteProj As ProjFileM = DbControllers.m_ProjController.FindByProjIdConv(nAlreadyImported)
         ' se esiste gia' un'ottimizzazione
         If ToDeleteProj.nProdId > 0 Then
            Select Case MessageBox.Show(EgtMsg(61942), "Information", MessageBoxButton.YesNo, MessageBoxImage.Information)       ' BTL file already imported and optimized. Do you want to import it again?
               Case MessageBoxResult.Yes
                  ' lo importo, quindi non devo fare nulla
               Case MessageBoxResult.No
                  Return
            End Select
         Else
            ' se non ha ottimizazione, chiedo se sovrascriverlo
            Select Case MessageBox.Show(EgtMsg(61943), "Information", MessageBoxButton.YesNoCancel, MessageBoxImage.Information)      ' BTL file already imported. Do you want to overwrite it?
               Case MessageBoxResult.Yes
                  ' cancello BTLParts su DB
                  DbControllers.m_ProjController.UpdateBtlParts(nAlreadyImported, New List(Of BTLPartM))
                  ' cancello nome BTL
                  DbControllers.m_ProjController.UpdateInfo(nAlreadyImported, DateTime.Now.ToString(), DateTime.Now.ToString(), "", DateTime.MinValue, BWType.NULL, "")
                  nProjId = nAlreadyImported
                  sProjDir = refMainWindowVM.MainWindowM.sProjsDir & "\" & nProjId.ToString("0000")
               Case MessageBoxResult.No
                  ' lo importo, quindi non devo fare nulla
               Case MessageBoxResult.Cancel
                  Return
            End Select
         End If
      End If
      ' se si ha una sola macchina disponibile (non BOTH) setto il progetto importato a quella macchina e al tipo progetto associato 
      ' altrimenti apro il dialog per scegliere la macchina e il tipo progetto a cui settare il progetto importato
      Dim Machine As Machine = Nothing
      Dim nType As BWType = BWType.NULL
      Dim ProjectTypeWndVM As New ProjectTypeWndVM()
      If ProjectTypeWndVM.MachineList.Count = 1 AndAlso DirectCast(ProjectTypeWndVM.SelMachine, MyMachine).nType <> MachineType.BOTH Then
         Machine = ProjectTypeWndVM.SelMachine
         nType = DirectCast(Machine, MyMachine).nType
      Else
         Dim ProjectTypeWnd As New ProjectTypeWndV(Application.Current.MainWindow, ProjectTypeWndVM)
         If ProjectTypeWnd.ShowDialog() Then
            Machine = ProjectTypeWndVM.SelMachine
            nType = ProjectTypeWndVM.nSelType
         Else
            Return
         End If
      End If
      LoadingWndHelper.OpenLoadingWnd(ActiveIds.IMPORTBTL, 3, EgtMsg(63008), EgtMsg(63009), 50)           ' BTL file importing     ' Reading BTL file
      ' inizializzo nuovo progetto
      InitNewProject(nProjId, sProjDir, nType, Machine)
      SetCurrProj(nProjId)
      ' imposto il tipo di parametri Q da utilizzare
      BTLIniFile.m_nBTLBWType = nType
      ' carico lista macchine e macchina del progetto per il pulsante Reset Macchina del CALCPanel
      Map.refCALCPanelVM.LoadMachineList()
      ' imposto ProjId di caricamento
      m_nLoadingProjId = nProjId
      ' copio file BTL
      Dim sBtlCopyPath As String = sProjDir & "\" & Path.GetFileName(sFile)
      Dim bOk = False
      Try
         File.Copy(sFile, sBtlCopyPath, True)
         bOk = True
      Catch ex As Exception
         EgtOutLog("Impossibile copiare il file")
         bOk = False
      End Try
      ' disattivo temporaneamente bottone assemblato per non prendere il riferimento sbagliato durante importazione
      Dim bAssembly As Boolean = Map.refShowBeamPanelVM.ShowBuilding_IsChecked
      Map.refShowBeamPanelVM.ShowBuilding_IsChecked = False
      ' importo file
      If bOk Then
         bOk = Map.refSceneHostVM.MainController.ImportProject(sBtlCopyPath, False)
      End If
      Dim sProjFileName As String = sProjDir & "\" & nProjId.ToString("0000") & ".nge"
      Dim bFirstPart As Boolean = EgtGetFirstPart() <> GDB_ID.NULL
      If bOk OrElse bFirstPart Then
         ' salvo path di importazione
         WriteMainPrivateProfileString(S_GENERAL, K_LASTIMPDIR, Path.GetDirectoryName(sFile))
         ' salvo il progetto
         bOk = EgtSaveFile(sProjFileName, NGE.CMPTEXT)
         SectionXMaterial.SetType(nType)
         Core.ViewPanelVM.UpdateBWType(nType)
         ' imposto flag secondo tipo di progetto (travi o pareti)
         Dim sBTLFlag As String = If(nType = Core.ConstBeam.BWType.BEAM, K_BTLFLAG, K_WALLBTLFLAG)
         Dim nFlag As Integer = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)
         EgtBeamSetFlag(nFlag)
      Else
         EgtOutLog("Errore nell'importazione BTL")
      End If
      If bOk Then
         ' aggiorno Db
         Dim ExportDate As DateTime
         DateTime.TryParse(Map.refProjectVM.BTLStructureVM.BTLStructureM.m_sEXPDATE & " " &
                           Map.refProjectVM.BTLStructureVM.BTLStructureM.m_sEXPTIME, ExportDate)
         DbControllers.m_ProjController.UpdateInfo(nProjId, sBTLFileName, sBTLFileName, Map.refProjectVM.BTLStructureVM.sLISTNAME, ExportDate, nType, Map.refMachinePanelVM.SelectedMachine.Name)
         SetCurrProj(nProjId)
         ' se progetto pareti e vista ruotata
         If nType = BWType.WALL AndAlso (CurrentMachine.ViewDir = VT.ISO_NW OrElse CurrentMachine.ViewDir = VT.ISO_NE) Then
            ' ruoto le pareti di 180 per raddrizzarle rispetto alla vista
            For Each Wall In Map.refProjectVM.BTLStructureVM.BTLPartVMList
               Wall.Rotation(True, Map.refProjectVM.BTLStructureVM.nPROJTYPE, True, 180, False)
            Next
         End If
         ' calcolo volumi pezzi
         For Each Part In Map.refProjectVM.BTLStructureVM.BTLPartVMList
            Part.CalcBTLPartVolume()
         Next
         Map.refProjectVM.SetOptimizePanel_Visibility(Map.refProjectVM.BTLStructureVM.nPROJTYPE = BWType.WALL AndAlso Map.refMainWindowVM.MainWindowM.GetKeyOption(KEY_OPT.NESTING_AUTO))
         Map.refPartManagerVM.LockVisibilityUpdate()
         LoadingWndHelper.UpdateLoadingWnd(ActiveIds.IMPORTBTL, 3, EgtMsg(63006), 70, 100)         ' Loading graphics
         Map.refShowBeamPanelVM.ShowBuilding_IsChecked = bAssembly
         ' mostro tutti i pezzi
         Map.refShowBeamPanelVM.ShowAll(True)
      Else
         Map.refShowBeamPanelVM.ShowBuilding_IsChecked = bAssembly
         ' elimino da Db
         ' CheckMe impostata come cancellazione FISICA dal DB...
         DbControllers.m_ProjController.DeleteProj(nProjId, False)
      End If
      ' carico filtri di ricerca
      Map.refProjectVM.BTLStructureVM.LoadFilters()
      ' gestisco log di importazione
      ManageImportLog(nProjId, sProjDir)
      ' aggiorno titolo
      Map.refMainWindowVM.UpdateTitle()
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTBTL)
   End Sub

   Private Sub ManageImportLog(nProjId As Integer, sProjDir As String)
      Dim LogFile As New List(Of String)
      Using FileStream As FileStream = New FileStream(Map.refMainWindowVM.MainWindowM.sLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
         Dim StreamReader As New StreamReader(FileStream)
         Dim Line As String = StreamReader.ReadLine()
         While Not StreamReader.EndOfStream
            Line = StreamReader.ReadLine()
            LogFile.Add(Line)
         End While
         StreamReader.Close()
      End Using
      If LogFile.Count > 0 Then
         ' recupero ultima occorrenza di import
         Dim sLastImport As String = LogFile.LastOrDefault(Function(x) x.Contains("ImportBtl"))
         ' verifico linee successive
         Dim nLastImportIndex As Integer = -1
         If Not String.IsNullOrWhiteSpace(sLastImport) Then
            nLastImportIndex = LogFile.IndexOf(sLastImport)
         End If
         Dim sImportMessage As String = sLastImport & Environment.NewLine
         Dim sImportLog As New List(Of String)({sLastImport})
         If nLastImportIndex > 0 Then
            Dim bGlobalError As Boolean = False
            ' ciclo sulle righe successive 
            For Index = nLastImportIndex + 1 To LogFile.Count - 1
               Dim sLogLine As String = LogFile(Index).Trim()
               ' verifico se fanno parte dell'import
               Dim bStartWithError As Boolean = sLogLine.StartsWith("Error")
               Dim bStartWithInfo As Boolean = sLogLine.StartsWith("Info")
               If Not bStartWithError And Not bStartWithInfo Then Exit For
               If bStartWithError Then
                  If Not bGlobalError Then bGlobalError = True
                  sImportMessage &= sLogLine & Environment.NewLine
               End If
               sImportLog.Add(sLogLine)
            Next
            ' salvo file ImportLog nel progetto
            Try
               File.WriteAllLines(sProjDir & "\" & nProjId.ToString("0000") & "-ImportLog.txt", sImportLog)
            Catch ex As Exception
               '
            End Try
            ' se almeno un errore, mostro log
            If bGlobalError Then
               MessageBox.Show(Application.Current.MainWindow, sImportMessage, EgtMsg(10001), MessageBoxButton.OK, MessageBoxImage.Error)   ' Error
            End If
         End If
      End If
   End Sub

#End Region ' ImportBTL

#Region "UpdateBTL"

   ''' <summary>
   ''' Returns a command that do UpdateBTL.
   ''' </summary>
   Public ReadOnly Property UpdateBTL_Command As ICommand
      Get
         If m_cmdUpdateBTL Is Nothing Then
            m_cmdUpdateBTL = New Command(AddressOf UpdateBTL)
         End If
         Return m_cmdUpdateBTL
      End Get
   End Property

   ''' <summary>
   ''' Execute the UpdateBTL.  This method is invoked by the UpdateBTLCommand.
   ''' </summary>
   Public Sub UpdateBTL(Optional sFile As String = "", Optional bWithDlg As Boolean = True)
      If IsNothing(CurrProj) Then Return
      ' verifico se progetto modificato, e chiedo se salvare
      If CurrProj.bIsNew Or EgtGetModified() OrElse Map.refCALCPanelVM.IsMachineModified() Then
         Select Case MessageBox.Show(EgtMsg(61877), "", MessageBoxButton.YesNoCancel, MessageBoxImage.Question)
            Case MessageBoxResult.Yes
               Save()
            Case MessageBoxResult.Cancel
               Return
            Case Else   ' No
               MessageBox.Show(EgtMsg(61892), "", MessageBoxButton.OK, MessageBoxImage.Exclamation)
               Return
         End Select
      End If

      ' se vista tutti i pezzi
      Dim bShowBuilding As Boolean = False
      Dim bShowSolid As Boolean = False
      Dim nSelPartId As Integer = GDB_ID.NULL
      If Map.refShowBeamPanelVM.bShowAll Then
         ' verifico se assemblato e lo annullo per salvataggio
         bShowBuilding = Map.refShowBeamPanelVM.ShowBuilding_IsChecked
         If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(False, False)
         ' se vista singolo pezzo
      Else
         bShowSolid = Map.refShowBeamPanelVM.ShowSolid_IsChecked
         If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, False, False)
         ' se pezzo selezionato lo segno e metto vista tutti
         nSelPartId = Map.refProjectVM.BTLStructureVM.SelBTLPart.nPartId
         Map.refProjectVM.BTLStructureVM.ShowAll(False)
      End If

      Dim sDir As String = String.Empty
      GetMainPrivateProfileString(S_GENERAL, K_LASTUPDATEDIR, "", sDir)
      If bWithDlg Then
         ' apro finestra scelta file
         Dim BTLDlg As New Microsoft.Win32.OpenFileDialog() With {
               .DefaultExt = ".btl",
               .Filter = "BTL (*.btl)|*.btl" &
                         "|BTLX (*.btlx)|*.btlx",
               .InitialDirectory = If(Directory.Exists(sDir), sDir, ""),
               .CheckFileExists = True,
               .ValidateNames = True}
         If BTLDlg.ShowDialog() Then
            sFile = BTLDlg.FileName
         Else
            ' se assemblato lo ripristino
            If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
            If nSelPartId <> GDB_ID.NULL Then
               Dim SelPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPartId = nSelPartId)
               If Not IsNothing(SelPart) Then
                  SelPart.IsSelected = True
                  If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, True, False)
               End If
            End If
            EgtZoom(ZM.ALL)
            Return
         End If
      End If
      ' salvo lista pezzi del progetto originale
      Dim OrigPartlist As ObservableCollection(Of BTLPartVM) = Map.refProjectVM.BTLStructureVM.BTLPartVMList
      ' creo un nuovo contesto su cui aprire il file BTL
      Dim nCurrCtx As Integer = EgtGetCurrentContext()
      Dim nTempCtx As Integer = EgtInitContext()

      ' setto il flag per inizializzazione gestore travi e pareti per importare progetto
      Dim nFlag As Integer
      Dim sBTLFlag As String
      If Map.refProjManagerVM.nProjType = Core.ConstBeam.BWType.BEAM Then
         sBTLFlag = K_BTLFLAG
      Else
         sBTLFlag = K_WALLBTLFLAG
      End If
      nFlag = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)

      ' inizializzo gestore travi e pareti
      EgtInitBeamMgr(nFlag)

      Dim bOk As Boolean = nTempCtx <> 0
      If bOk Then
         ' importo il file BTL
         bOk = bOk AndAlso Map.refSceneHostVM.MainController.ImportProject(sFile, False)
         ' carico la lista dei Part importati e rimuovo i parametri generali del BTL
         Dim AsseBaseId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
         Dim BtlInfoId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, BTLINFO)
         Dim PartToUpdateList As New List(Of BTLPartToUpdate)

         ' cerco tra i layer BTLInfo
         While BtlInfoId <> GDB_ID.NULL
            ' verifico se il layer appartiene al ProjId
            Dim nBTLInfoLayerProjId As Integer
            EgtGetInfo(BtlInfoId, BTL_PRT_PROJ, nBTLInfoLayerProjId)
            ' carico la lista con i PDN dei pezzi del BTL importato
            Dim nPDN As Integer = 0
            Dim sNAM As String = String.Empty
            Dim nUID As Integer = 0
            Dim nPartId As Integer = EgtGetFirstPart()
            While nPartId <> GDB_ID.NULL
               Dim UIDList As New List(Of Integer)
               Dim nIndUID As Integer = 1
               ' se devo filtrare un progetto
               If nBTLInfoLayerProjId > 0 Then
                  ' verifico se il pezzo appartiene al ProjId
                  Dim nPartProjId As Integer
                  EgtGetInfo(nPartId, BTL_PRT_PROJ, nPartProjId)
                  If nPartProjId = nBTLInfoLayerProjId Then
                     EgtGetInfo(nPartId, BTL_PRT_PDN, nPDN)
                     EgtGetInfo(nPartId, BTL_PRT_NAM, sNAM)
                     While EgtGetInfo(nPartId, BTL_PRT_UID & nIndUID, nUID)
                        UIDList.Add(nUID)
                        nIndUID += 1
                     End While
                     PartToUpdateList.Add(New BTLPartToUpdate(nPartId, nPDN, sNAM, UIDList, OrigPartlist.Any(Function(x) x.nPDN = nPDN)))
                  End If
               Else
                  ' altrimenti carico tutti
                  EgtGetInfo(nPartId, BTL_PRT_PDN, nPDN)
                  EgtGetInfo(nPartId, BTL_PRT_NAM, sNAM)
                  While EgtGetInfo(nPartId, BTL_PRT_UID & nUID, nUID)
                     UIDList.Add(nUID)
                     nIndUID += 1
                  End While
                  PartToUpdateList.Add(New BTLPartToUpdate(nPartId, nPDN, sNAM, UIDList, OrigPartlist.Any(Function(x) x.nPDN = nPDN)))
               End If
               nPartId = EgtGetNextPart(nPartId)
            End While
            EgtErase(BtlInfoId)
            BtlInfoId = EgtGetNextName(BtlInfoId, BTLINFO)
         End While

         ' costruisco un dizionario con gli id dei sottonodi di AsseBase del BTL importato e il valore dell'Info N degli stessi
         Dim AsseBaseSubNodeDict As New Dictionary(Of Integer, Integer)
         Dim nAsseBaseSubNodeId As Integer = EgtGetFirstInGroup(AsseBaseId)
         Dim sAsseBaseUID As String = String.Empty
         Dim nAsseBaseUID As Integer = 0
         While nAsseBaseSubNodeId <> GDB_ID.NULL
            If EgtGetInfo(nAsseBaseSubNodeId, BTL_ASSEBASE_N, sAsseBaseUID) Then
               sAsseBaseUID = sAsseBaseUID.Remove(0, 4)
               Integer.TryParse(sAsseBaseUID, nAsseBaseUID)
               AsseBaseSubNodeDict.Add(nAsseBaseSubNodeId, sAsseBaseUID)
            End If
            nAsseBaseSubNodeId = EgtGetNext(nAsseBaseSubNodeId)
         End While

         ' salvo il file BTL da cui abbiamo rimosso BtlInfo come file NGE
         EgtSaveFile(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & UPDATEBTL_NGE, NGE.CMPTEXT)

         Dim bAppend As Boolean = False
         ' se UserLevel > 5 e fra i Part importati ce ne sta almeno 1 con PDN uguale ai Part già presenti
         ' apro la finestra per chiedere se si vuole aggiornare o accodare 
         If Map.refMainWindowVM.MainWindowM.nUserLevel > 5 Then
            For Each PartToUpdate In PartToUpdateList
               Dim bExitFor As Boolean = False
               For Each BTLPart In Map.refProjectVM.BTLStructureVM.BTLStructureM.BTLPartMList
                  If PartToUpdate.nPDN = BTLPart.nPDN Then
                     Dim UpdateOrAppendWndVM As New UpdateOrAppendWndVM()
                     Dim UpdateOrAppendWnd As New UpdateOrAppendWndV(Application.Current.MainWindow, UpdateOrAppendWndVM)
                     If Not UpdateOrAppendWnd.ShowDialog() Then
                        ' torno sul contesto corrente
                        EgtSetCurrentContext(nCurrCtx)
                        EgtDeleteContext(nTempCtx)
                        ' rileggo la struttura BTL
                        ReloadBTLStructure()
                        ' se assemblato lo ripristino
                        If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
                        If nSelPartId <> GDB_ID.NULL Then
                           Dim SelPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPartId = nSelPartId)
                           If Not IsNothing(SelPart) Then
                              SelPart.IsSelected = True
                              If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, True, False)
                           End If
                        End If
                        EgtZoom(ZM.ALL)
                        Return
                     End If
                     ' salvo lo stato del bottone per accodare
                     bAppend = UpdateOrAppendWndVM.AppendIsChecked
                     bExitFor = True
                     Exit For
                  End If
               Next
               If bExitFor Then Exit For
            Next
         End If

         ' se selezionato Append li accodo tutti
         If bAppend Then
            ' torno sul contesto corrente
            EgtSetCurrentContext(nCurrCtx)
            EgtDeleteContext(nTempCtx)

            ' rileggo la struttura BTL del progetto corrente per non avere quella del contesto temporaneo ancora presente
            ReloadBTLStructure()

            ' salvo gli id degli AsseBase presenti nel progetto corrente
            Dim AsseBaseIdList As New List(Of Integer)
            AsseBaseId = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
            While AsseBaseId <> GDB_ID.NULL
               AsseBaseIdList.Add(AsseBaseId)
               AsseBaseId = EgtGetNextName(AsseBaseId, ASSEBASE)
            End While

            ' calcolo BBox globale del progetto iniziale
            Dim b3Parts As New BBox3d
            Dim nProjPartId As Integer = EgtGetFirstPart()
            Dim nLastProjPartId As Integer = 0
            While nProjPartId <> GDB_ID.NULL
               Dim b3Part As New BBox3d
               EgtGetBBoxGlob(nProjPartId, GDB_BB.ONLY_VISIBLE, b3Part)
               b3Parts.Add(b3Part)
               nLastProjPartId = nProjPartId
               nProjPartId = EgtGetNextPart(nProjPartId)
            End While
            ' inserisco il file importato nel progetto corrente
            bOk = bOk AndAlso EgtInsertFile(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & UPDATEBTL_NGE)
            ' deseleziono tutto
            EgtDeselectAll()
            ' ciclo sui pezzi aggiunti
            Dim nAddedPartId As Integer = EgtGetNextPart(nLastProjPartId)
            Dim bFirstLoop As Boolean = True
            Dim LastPartMaxY As Double
            Dim nIncrPDN As Integer = 0
            While nAddedPartId <> GDB_ID.NULL
               ' incremento il PDN del Part aggiunto rispetto al PDN maggiore attualmente presente
               EgtSetInfo(nAddedPartId, BTL_PRT_PDN, Map.refProjectVM.BTLStructureVM.BTLStructureM.NewPDN() + nIncrPDN)
               ' recupero layer del box
               Dim nBoxLayerId As Integer = EgtGetFirstNameInGroup(nAddedPartId, "Box")
               ' recupero box del layer box
               Dim b3Box As New BBox3d
               EgtGetBBoxGlob(nBoxLayerId, GDB_BB.STANDARD, b3Box)
               ' ricaviamo il box globale del part appena aggiunto
               Dim b3Part As New BBox3d
               EgtGetBBoxGlob(nAddedPartId, 1, b3Part)
               ' sposto il pezzo per distanziarlo dall'ultimo di un offset pari a 500
               bOk = bOk AndAlso EgtMove(nAddedPartId, New Vector3d(0, If(bFirstLoop, b3Parts.Max.y, LastPartMaxY - b3Part.Min.y) + 500, 0))
               bFirstLoop = False
               ' ricaviamo il box globale del part appena spostato, salviamo la sua Y massima e lo aggiungiamo al box globale di tutti i part
               EgtGetBBoxGlob(nAddedPartId, 1, b3Part)
               LastPartMaxY = b3Part.Max.y
               b3Parts.Add(b3Part)
               nAddedPartId = EgtGetNextPart(nAddedPartId)
               nIncrPDN += 1
            End While
            ' aggiungo i part inseriti alla lista
            Dim nNewPartId As Integer = EgtGetNextPart(nLastProjPartId)
            While nNewPartId <> GDB_ID.NULL
               ' aggiungo dati pezzo
               Dim NewPart As BTLPartM = BTLPartM.CreateBTLPart(nNewPartId)
               ' aggiungo pezzo alla lista
               Map.refProjectVM.BTLStructureVM.BTLStructureM.AddBTLPart(NewPart)
               Dim AddedBTLPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.BTLPartM Is NewPart)
               ' verifico se aggiungere sezione alla lista
               If Not Map.refProjectVM.BTLStructureVM.SectionList.Contains(AddedBTLPart.Section) Then
                  Map.refProjectVM.BTLStructureVM.SectionList.Add(AddedBTLPart.Section)
               End If
               nNewPartId = EgtGetNextPart(nNewPartId)
            End While

            ' elimino gli AsseBase del progetto importato
            AsseBaseId = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
            While AsseBaseId <> GDB_ID.NULL
               Dim CurrAsseBaseId = AsseBaseId
               AsseBaseId = EgtGetNextName(AsseBaseId, ASSEBASE)
               If Not AsseBaseIdList.Contains(CurrAsseBaseId) Then EgtErase(CurrAsseBaseId)
            End While

            WriteMainPrivateProfileString(S_GENERAL, K_LASTUPDATEDIR, Path.GetDirectoryName(sFile))
         Else
            ' altrimenti apro la finestra con l'elenco dei Part da checkare per l'inserimento nel progetto (unica strada se UserLevel <= 5),
            ' che prevederà la sovrascrittura di quelli già presenti e l'aggiunta di quelli nuovi
            Dim UpdateBTLWndVM As New UpdateBTLWndVM(PartToUpdateList)
            Dim UpdateBTLWnd As New UpdateBTLWndV(Application.Current.MainWindow, UpdateBTLWndVM)
            If Not UpdateBTLWnd.ShowDialog() Then
               ' torno sul contesto corrente
               EgtSetCurrentContext(nCurrCtx)
               EgtDeleteContext(nTempCtx)
               ' rileggo la struttura BTL
               ReloadBTLStructure()
               ' se assemblato lo ripristino
               If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
               If nSelPartId <> GDB_ID.NULL Then
                  Dim SelPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPartId = nSelPartId)
                  If Not IsNothing(SelPart) Then
                     SelPart.IsSelected = True
                     If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, True, False)
                  End If
               End If
               EgtZoom(ZM.ALL)
               Return
            End If
            If UpdateBTLWndVM.BTLPartList.Count > 0 Then
               ' sovrascrivo i Part nel progetto aperto con i Part checkati nella lista
               Dim BTLPartToOverwriteWithList As New ObservableCollection(Of BTLPartToUpdate)
               ' Elimino dal TempCtx i Part non checkati
               For Each BTLPartToOverwriteWith In UpdateBTLWndVM.BTLPartList
                  If BTLPartToOverwriteWith.bInsert Then
                     BTLPartToOverwriteWithList.Add(BTLPartToOverwriteWith)
                  Else
                     ' elimino pezzo copia
                     Dim nCurrPartId = EgtGetCurrPart()
                     EgtErase(BTLPartToOverwriteWith.nPartId)
                     nCurrPartId = EgtGetCurrPart()
                  End If
               Next

               ' costruisco un nuovo dizionario dei sottonodi di AsseBase contenente solo quelli corrispondenti agli UID contenuti
               ' nei soli Part checkati del BTL nella finestra UpdateBTLWnd
               Dim NewAsseBaseSubNodeDict As New Dictionary(Of Integer, Integer)
               For Each AsseBaseSubNodeItem In AsseBaseSubNodeDict
                  For Each BTLPartToOverwriteWithItem In BTLPartToOverwriteWithList
                     Dim bExitFor As Boolean = False
                     For Each UIDItem In BTLPartToOverwriteWithItem.UIDList
                        If AsseBaseSubNodeItem.Value = UIDItem Then
                           NewAsseBaseSubNodeDict.Add(AsseBaseSubNodeItem.Key, AsseBaseSubNodeItem.Value)
                           bExitFor = True
                           Exit For
                        End If
                     Next
                     If bExitFor Then Exit For
                  Next
               Next
               ' confronto la lista appena costruita con quella originale ed elimino dal contesto i sottonodi con i valori non più presenti
               For Each AsseBaseSubNodeItem In AsseBaseSubNodeDict
                  If Not NewAsseBaseSubNodeDict.ContainsValue(AsseBaseSubNodeItem.Value) Then
                     EgtErase(AsseBaseSubNodeItem.Key)
                  End If
               Next

               ' salvo il file NGE inserito a cui abbiamo rimosso i Part non checkati e gli AsseBase non più associati
               EgtSaveFile(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & UPDATEBTL_NGE, NGE.CMPTEXT)

               ' torno sul contesto corrente
               EgtDeleteContext(nTempCtx)
               EgtSetCurrentContext(nCurrCtx)

               ' rileggo la struttura BTL del progetto corrente per non avere quella del contesto temporaneo ancora presente
               ReloadBTLStructure()

               ' elimino i pezzi da sovrascrivere nel progetto corrente
               For Each BTLPartToOverwriteWith In UpdateBTLWndVM.BTLPartList
                  If BTLPartToOverwriteWith.bInsert Then
                     Dim BTLPartToUpdate As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPDN = BTLPartToOverwriteWith.nPDN)
                     ' se BTLPartToUpdate è Nothing significa che il pezzo è nuovo e quindi basta accodarlo senza eliminare nulla
                     If Not IsNothing(BTLPartToUpdate) Then
                        Dim nPartToDeleteId As Integer = BTLPartToUpdate.nPartId
                        Dim nCurrPartId = EgtGetCurrPart()
                        EgtErase(nPartToDeleteId)
                        nCurrPartId = EgtGetCurrPart()
                        ' verifico se rimuovere sezione dalla lista
                        If Not Map.refProjectVM.BTLStructureVM.BTLPartVMList.Any(Function(x) x IsNot BTLPartToUpdate AndAlso x.Section = BTLPartToUpdate.Section) Then
                           Map.refProjectVM.BTLStructureVM.SectionList.Remove(BTLPartToUpdate.Section)
                        End If
                        ' rimuovo dalla lista pezzi
                        Dim Index As Integer = Map.refProjectVM.BTLStructureVM.BTLPartVMList.IndexOf(BTLPartToUpdate)
                        Map.refProjectVM.BTLStructureVM.SetSelBTLPart(Nothing)
                        Map.refProjectVM.BTLStructureVM.BTLPartVMList.RemoveAt(Index)
                     End If
                  End If
               Next

               ' salvo gli id degli AsseBase presenti nel progetto corrente
               Dim AsseBaseIdList As New List(Of Integer)
               AsseBaseId = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
               While AsseBaseId <> GDB_ID.NULL
                  AsseBaseIdList.Add(AsseBaseId)
                  ' elimino i sottonodi di AsseBase da sovrascrivere
                  AsseBaseId = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
                  nAsseBaseSubNodeId = EgtGetFirstInGroup(AsseBaseId)
                  While nAsseBaseSubNodeId <> GDB_ID.NULL
                     If NewAsseBaseSubNodeDict.ContainsKey(nAsseBaseSubNodeId) Then
                        ' se sottonodo da cancellare salvo il suo id e ricavo il seguente prima di cancellarlo
                        Dim nCurrAsseBaseSubNodeId = nAsseBaseSubNodeId
                        nAsseBaseSubNodeId = EgtGetNext(nCurrAsseBaseSubNodeId)
                        bOk = EgtErase(nCurrAsseBaseSubNodeId)
                     Else
                        ' altrimenti ricavo il seguente e basta
                        nAsseBaseSubNodeId = EgtGetNext(nAsseBaseSubNodeId)
                     End If
                  End While
                  AsseBaseId = EgtGetNextName(AsseBaseId, ASSEBASE)
               End While

               ' calcolo BBox globale del progetto corrente
               Dim b3Parts As New BBox3d
               Dim nProjPartId As Integer = EgtGetFirstPart()
               Dim nLastProjPartId As Integer = GDB_ID.NULL
               While nProjPartId <> GDB_ID.NULL
                  Dim b3Part As New BBox3d
                  If EgtGetBBoxGlob(nProjPartId, GDB_BB.ONLY_VISIBLE, b3Part) Then
                     b3Parts.Add(b3Part)
                  End If
                  nLastProjPartId = nProjPartId
                  nProjPartId = EgtGetNextPart(nProjPartId)
               End While
               ' se sovrascrivo tutti e bbox esce nullo
               If b3Parts.IsEmpty Then
                  b3Parts = New BBox3d(Point3d.ORIG)
               End If

               ' inserisco il file NGE (ricavato dal BTL importato) nel progetto corrente
               bOk = bOk AndAlso EgtInsertFile(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & UPDATEBTL_NGE)

               ' ciclo su tutti gli AsseBase del progetto corrente
               Dim nAsseBaseId = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
               While nAsseBaseId <> GDB_ID.NULL
                  Dim nAsseBaseProjId As Integer
                  Dim nAsseBaseToEraseId As Integer = 0
                  EgtGetInfo(nAsseBaseId, BTL_PRT_PROJ, nAsseBaseProjId)
                  ' se AsseBase di questo step del ciclo è nuovo e suo ProjId uguale a quello del progetto corrente
                  If Not AsseBaseIdList.Contains(nAsseBaseId) AndAlso nAsseBaseProjId = Map.refProjManagerVM.CurrProj.nProjId Then
                     ' riloco i sottonodi del nuovo AsseBase nell'AsseBase del progetto aperto col medesimo ProjId
                     Dim AsseBaseSubNodeId As Integer = EgtGetFirstInGroup(nAsseBaseId)
                     While AsseBaseSubNodeId <> GDB_ID.NULL
                        ' ciclo su tutti gli AsseBase per trovare l'id di quello con ProjId uguale al progetto corrente
                        Dim FindAsseBaseId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
                        While FindAsseBaseId <> GDB_ID.NULL
                           Dim SameAsseBaseProjId As Integer
                           EgtGetInfo(FindAsseBaseId, BTL_PRT_PROJ, SameAsseBaseProjId)
                           ' se l'ho trovato esco dal While (FindAsseBaseId è l'id dell'AsseBase in cui vogliamo rilocare i sottonodi)
                           If SameAsseBaseProjId = Map.refProjManagerVM.CurrProj.nProjId Then Exit While
                           FindAsseBaseId = EgtGetNextName(FindAsseBaseId, ASSEBASE)
                        End While
                        ' salvo id dell'AsseBase corrente per ottenere il seguente prima di rilocarlo
                        Dim CurrAsseBaseSubNodeId = AsseBaseSubNodeId
                        AsseBaseSubNodeId = EgtGetNext(CurrAsseBaseSubNodeId)
                        bOk = bOk AndAlso EgtRelocate(CurrAsseBaseSubNodeId, FindAsseBaseId, GDB_POS.LAST_SON)
                     End While
                     ' salvo id dell'AsseBase per cancellarlo
                     nAsseBaseToEraseId = nAsseBaseId
                  End If
                  ' ricavo id del prossimo AsseBase
                  nAsseBaseId = EgtGetNextName(nAsseBaseId, ASSEBASE)
                  ' se salvato id dell'AsseBase per cancellarlo lo cancello 
                  If nAsseBaseToEraseId <> 0 Then bOk = bOk AndAlso EgtErase(nAsseBaseToEraseId)
               End While

               ' deseleziono tutto
               EgtDeselectAll()
               ' ciclo sui pezzi aggiunti
               Dim nAddedPartId As Integer = If(nLastProjPartId <> GDB_ID.NULL, EgtGetNextPart(nLastProjPartId), EgtGetFirstPart())
               Dim LastPartMaxY As Double
               While nAddedPartId <> GDB_ID.NULL
                  ' recupero layer del box
                  Dim nBoxLayerId As Integer = EgtGetFirstNameInGroup(nAddedPartId, "Box")
                  ' recupero box del layer box
                  Dim b3Box As New BBox3d
                  EgtGetBBoxGlob(nBoxLayerId, GDB_BB.STANDARD, b3Box)
                  ' ricaviamo il box globale del part appena aggiunto e ruotato
                  Dim b3Part As New BBox3d
                  EgtGetBBoxGlob(nAddedPartId, 1, b3Part)
                  ' salviamo la Y massima del box globale di tutti i part
                  LastPartMaxY = b3Parts.Max.y
                  ' sposto il pezzo per distanziarlo dall'ultimo di un offset pari a 500
                  bOk = bOk AndAlso EgtMove(nAddedPartId, New Vector3d(0, LastPartMaxY - b3Part.Min.y + 500, 0))
                  ' ricaviamo il box globale del part appena spostato e lo aggiungiamo al box globale di tutti i part
                  EgtGetBBoxGlob(nAddedPartId, 1, b3Part)
                  b3Parts.Add(b3Part)
                  ' aggiungo dati pezzo
                  Dim NewPart As BTLPartM = BTLPartM.CreateBTLPart(nAddedPartId)
                  ' aggiungo pezzo alla lista
                  Map.refProjectVM.BTLStructureVM.BTLStructureM.AddBTLPart(NewPart)
                  Dim AddedBTLPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.BTLPartM Is NewPart)
                  ' se progetto pareti e vista ruotata
                  If nType = BWType.WALL AndAlso (CurrentMachine.ViewDir = VT.ISO_NW OrElse CurrentMachine.ViewDir = VT.ISO_NE) Then
                     ' ruoto le pareti di 180 per raddrizzarle rispetto alla vista
                     AddedBTLPart.Rotation(True, Map.refProjectVM.BTLStructureVM.nPROJTYPE, True, 180, False)
                  End If
                  ' verifico se aggiungere sezione alla lista
                  If Not Map.refProjectVM.BTLStructureVM.SectionList.Contains(AddedBTLPart.Section) Then
                     Map.refProjectVM.BTLStructureVM.SectionList.Add(AddedBTLPart.Section)
                  End If
                  nAddedPartId = EgtGetNextPart(nAddedPartId)
               End While
               WriteMainPrivateProfileString(S_GENERAL, K_LASTUPDATEDIR, Path.GetDirectoryName(sFile))
            End If
         End If
         ' copio il file originale scelto nel dialog per l'Update nella cartella Proj del progetto corrente
         If File.Exists(sFile) Then
            Dim sDestPath As String = Map.refProjManagerVM.CurrProj.sProjDirPath & "\" & Path.GetFileNameWithoutExtension(sFile)
            While File.Exists(sDestPath & ".btl")
               sDestPath = sDestPath & "_1"
            End While
            File.Copy(sFile, sDestPath & ".btl", False)
         End If
      End If
      ' se assemblato lo ripristino
      If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
      If nSelPartId <> GDB_ID.NULL Then
         Dim SelPart As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPartId = nSelPartId)
         If Not IsNothing(SelPart) Then
            SelPart.IsSelected = True
            If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, True, False)
         End If
      End If
      EgtZoom(ZM.ALL)
   End Sub

#End Region ' UpdateBTL

#Region "ExportProject"

   ''' <summary>
   ''' Returns a command that do Export.
   ''' </summary>
   Public ReadOnly Property ExportProject_Command As ICommand
      Get
         If m_cmdExportProject Is Nothing Then
            m_cmdExportProject = New Command(AddressOf ExportProject)
         End If
         Return m_cmdExportProject
      End Get
   End Property

   ''' <summary>
   ''' Execute the Export.  This method is invoked by the ExportCommand.
   ''' </summary>
   Public Function ExportProject(Optional sExportFileName As String = Nothing) As String
      Select Case Map.refMainMenuVM.SelPage
         Case Pages.VIEW
            If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return Nothing
            If IsNothing(CurrProj) Then Return Nothing
         Case Pages.MACHINING
            If ProdFileVM.VerifyProjectModification(Map.refProdManagerVM.CurrProd) = MessageBoxResult.Cancel Then Return Nothing
            If IsNothing(Map.refProdManagerVM.CurrProd) Then Return Nothing
         Case Else
            Return Nothing
      End Select

      ' apro finestra di salvataggio progetto
      Dim ExportDlg As New Microsoft.Win32.SaveFileDialog() With {.DefaultExt = ".ngexp",
                                                               .Filter = "ProjectExport (*.ngexp)|*.ngexp",
                                                               .FileName = CurrProj.nProjId.ToString("0000") & " - " & CurrProj.sBTLFileName & " - ProjectExport"}
      If IsNothing(sExportFileName) Then
         If ExportDlg.ShowDialog() <> True Then Return Nothing
      End If

      LoadingWndHelper.OpenLoadingWnd(ActiveIds.EXPORTPROJECT, 2, EgtMsg(63010), EgtMsg(63016), 30)           ' Project exporting     ' Adding export info
      ' se assemblato me lo segno e lo smonto
      Dim bShowBuilding As Boolean = False
      If Map.refMainMenuVM.SelPage = Pages.VIEW Then
         If Map.refShowBeamPanelVM.bShowAll Then
            ' verifico se assemblato e lo annullo per salvataggio
            bShowBuilding = Map.refShowBeamPanelVM.ShowBuilding_IsChecked
            If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(False, False)
         End If
      End If

      ' per ogni BTLInfo nel progetto riporto il relativo nome del BTL
      Dim nBTLInfoProjId As Integer
      Dim nBTLInfoLayerId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, BTLINFO)
      While nBTLInfoLayerId <> GDB_ID.NULL
         ' recupero il ProjId
         EgtGetInfo(nBTLInfoLayerId, BTL_PRT_PROJ, nBTLInfoProjId)
         If nBTLInfoProjId > 0 Then
            ' recupero il BTL file name di questo proj
            Dim BTLFileNameProj As ProjFileM = DbControllers.m_ProjController.FindByProjIdConv(nBTLInfoProjId)
            If Not IsNothing(BTLFileNameProj) Then
               EgtSetInfo(nBTLInfoLayerId, BTLFILENAME, BTLFileNameProj.sBTLFileName)
            End If
         End If
         nBTLInfoLayerId = EgtGetNextName(nBTLInfoLayerId, BTLINFO)
      End While
      ' aggiungo layer per info di export
      Dim nImpExpPartId As Integer = EgtCreateGroup(GDB_ID.ROOT)
      EgtSetName(nImpExpPartId, EXP_PART)
      ' ci scrivo nome macchina e tipo progetto
      EgtSetInfo(nImpExpPartId, EXP_MACHINE, CurrProj.sMachine)
      EgtSetInfo(nImpExpPartId, BTL_GEN_PROJTYPE, CurrProj.nType)
      '' se c'e' un prod collegato
      'If Map.refProjManagerVM.CurrProj.nProdId > 0 Then
      '   ' scrivo quali sono i proj e prod in questo file
      '   Dim Prod As ProdFileM = DbControllers.m_ProdController.FindCoreByProdId(Map.refProjManagerVM.CurrProj.nProdId)
      '   EgtSetInfo(Map.refProjectVM.BTLStructureVM.BTLStructureM.nBTLInfoId, EXP_PROD, Map.refProjManagerVM.CurrProj.nProdId)
      '   For ProjIndex = 0 To Prod.nProjIdList.Count - 1
      '      EgtSetInfo(Map.refProjectVM.BTLStructureVM.BTLStructureM.nBTLInfoId, EXP_PROJ & ProjIndex + 1, Prod.nProjIdList(ProjIndex))
      '   Next
      'Else
      '   EgtSetInfo(Map.refProjectVM.BTLStructureVM.BTLStructureM.nBTLInfoId, EXP_PROJ & 1, Map.refProjManagerVM.CurrProj.nProjId)
      'End If
      LoadingWndHelper.UpdateLoadingWnd(ActiveIds.EXPORTPROJECT, 2, EgtMsg(63017), 30, 100)        ' Exporting...
      ' salvo info inserite
      Map.refSceneHostVM.SaveProject()
      ' creo file zip
      Dim sZipToCreate As String = If(IsNothing(sExportFileName), ExportDlg.FileName, Map.refMainWindowVM.MainWindowM.sTempDir & "\" & sExportFileName & ".ngexp")
      If File.Exists(sZipToCreate) Then
         File.Delete(sZipToCreate)
      End If
      Try
         Using zip As New Ionic.Zip.ZipFile(sZipToCreate, Console.Out)
            ' impacchetto tutta la cartella del progetto
            Dim sProjectDirPath As String = If(CurrProj.nProdId > 0, CurrProj.sProdDirPath, CurrProj.sProjDirPath)
            For Each sFile As String In Directory.GetFiles(sProjectDirPath)
               zip.AddItem(sFile, "")
            Next
            ' salvo lo zip
            zip.Save()
         End Using
      Catch ex1 As Exception
         EgtOutLog("Exception in zip: " & ex1.ToString())
         MessageBox.Show("Error in export file creation!")
      End Try
      ' elimino layer di esportazione
      EgtErase(nImpExpPartId)
      ' salvo eliminazione info inserite
      Map.refSceneHostVM.SaveProject()
      If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(True, False)
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.EXPORTPROJECT)
      Return sZipToCreate
   End Function

#End Region ' ExportProject

#Region "ImportProject"

   ''' <summary>
   ''' Returns a command that do Export.
   ''' </summary>
   Public ReadOnly Property ImportProject_Command As ICommand
      Get
         If m_cmdImportProject Is Nothing Then
            m_cmdImportProject = New Command(AddressOf ImportProject)
         End If
         Return m_cmdImportProject
      End Get
   End Property

   ''' <summary>
   ''' Execute the Export.  This method is invoked by the ExportCommand.
   ''' </summary>
   Public Sub ImportProject()
      Dim CurrProd As ProjectFileVM = Map.refProdManagerVM.CurrProd
      ' lista di tutti gli errori riscontrati
      Dim ErrorList As New List(Of String)
      If Not ProjFileVM.VerifyProjectModification(CurrProj, ProjectType.PROJ) Then Return
      Dim sDir As String = String.Empty
      GetMainPrivateProfileString(S_GENERAL, K_LASTNGEXPDIR, "", sDir)
      ' apro finestra scelta file
      Dim ImportDlg As New Microsoft.Win32.OpenFileDialog() With {.DefaultExt = ".ngexp",
                                                                  .Filter = "ProjectExport (*.ngexp)|*.ngexp",
                                                                  .InitialDirectory = If(Directory.Exists(sDir), sDir, ""),
                                                                  .CheckFileExists = True,
                                                                  .ValidateNames = True}
      If ImportDlg.ShowDialog() <> True Then Return
      ' creo cartella temporanea di estrazione in Temp
      Dim sProjectimportDir As String = Map.refMainWindowVM.MainWindowM.sTempDir & "\ProjectImport"
      If Directory.Exists(sProjectimportDir) Then
         Directory.Delete(sProjectimportDir, True)
      End If
      Directory.CreateDirectory(sProjectimportDir)
      Try
         Using zip As New Ionic.Zip.ZipFile(ImportDlg.FileName, Console.Out)
            ' estraggo file da zip
            zip.ExtractAll(sProjectimportDir)
         End Using
      Catch ex1 As Exception
         EgtOutLog("Exception in zip: " & ex1.ToString())
         MessageBox.Show("Impossibile importare file", "Errore")
         Return
      End Try
      LoadingWndHelper.OpenLoadingWnd(ActiveIds.IMPORTPROJECT, 2, EgtMsg(63018), EgtMsg(63019), 30)        ' Project importing     ' Loading project
      ' carico progetto
      Dim sProjFromPath() As String = Directory.GetFiles(sProjectimportDir, "*.nge")
      Dim bOk = EgtOpenFile(sProjFromPath(0))
      If Not bOk Then
         LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTPROJECT)
         MessageBox.Show("Impossibile aprire il file", "Errore")
         Return
      End If
      ' recupero e verifico se ho a disposizione la macchina con cui e' stato creato il progetto
      Dim nImpExpPartId = EgtGetFirstNameInGroup(GDB_ID.ROOT, EXP_PART)
      Dim sMachine As String = ""
      EgtGetInfo(nImpExpPartId, EXP_MACHINE, sMachine)
      ' se la macchina del progetto in apertura non è tra le macchine disponibili lo segnalo e apro un progetto vuoto
      If IsNothing(Map.refMachinePanelVM.MachineList.FirstOrDefault(Function(x) x.Name = sMachine)) Then
         LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTPROJECT)
         MessageBox.Show(EgtMsg(61885), EgtMsg(10001), MessageBoxButton.OK, MessageBoxImage.Error)        'Error
         Return
      End If
      Dim Machine As Machine = Map.refMachinePanelVM.MachineList.FirstOrDefault(Function(x) x.Name = sMachine)
      Dim nType As Integer = BWType.NULL
      EgtGetInfo(nImpExpPartId, BTL_GEN_PROJTYPE, nType)
      If IsNothing(Machine) OrElse nType = BWType.NULL Then
         LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTPROJECT)
         MessageBox.Show(EgtMsg(61885), EgtMsg(10001), MessageBoxButton.OK, MessageBoxImage.Error)        'Error
         Return
      End If
      ' elimino part di esportazione
      EgtErase(nImpExpPartId)
      LoadingWndHelper.UpdateLoadingWnd(ActiveIds.IMPORTPROJECT, 2, EgtMsg(63020), 30, 100)         ' Creating imported project
      ' leggo proj e prod presenti dai layer BTLInfo
      Dim ImportProjIdList As New List(Of Integer)
      Dim NewProjIdList As New List(Of Integer)
      Dim BTLInfoIdList As New List(Of Integer)
      Dim BTLFileNameList As New List(Of String)
      Dim CurrImportProjId As Integer
      Dim nBTLInfoLayerId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, BTLINFO)
      While nBTLInfoLayerId <> GDB_ID.NULL
         ' recupero il ProjId
         EgtGetInfo(nBTLInfoLayerId, BTL_PRT_PROJ, CurrImportProjId)
         If CurrImportProjId > 0 Then
            ImportProjIdList.Add(CurrImportProjId)
            BTLInfoIdList.Add(nBTLInfoLayerId)
            ' recupero nome file BTL Associato
            Dim sBTLFileName As String = ""
            EgtGetInfo(nBTLInfoLayerId, BTLFILENAME, sBTLFileName)
            BTLFileNameList.Add(sBTLFileName)
         End If
         nBTLInfoLayerId = EgtGetNextName(nBTLInfoLayerId, BTLINFO)
      End While
      If Not ImportProjIdList.Count > 0 Then
         MessageBox.Show("Nessun progetto trovato all'interno del file importato", "Errore")
      End If
      ' carico i proj
      For nProjIndex = 0 To ImportProjIdList.Count - 1
         Dim nImportProjId As Integer = ImportProjIdList(nProjIndex)
         ' inizializzo nuovo proj
         Dim nNewProjId As Integer = 0
         Dim sNewProjDir As String = ""
         InitNewProject(nNewProjId, sNewProjDir, nType, Machine)
         NewProjIdList.Add(nNewProjId)
         ' imposto ProjId di caricamento
         m_nLoadingProjId = nImportProjId
         ' costruisco BTLStructure del proj
         Map.refProjectVM.BTLStructureVM = New BTLStructureVM(BTLStructureM.CreateBTLStructure(nImportProjId))
         ' scrivo info proj su tutti i pezzi di questo progetto
         For Each BTLPart In Map.refProjectVM.BTLStructureVM.BTLPartVMList
            EgtSetInfo(BTLPart.nPartId, BTL_PRT_PROJ, nNewProjId)
         Next
         ' cambio indicazione proj in gruppo di assemblaggio
         Dim AsseBaseId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, ASSEBASE)
         While AsseBaseId <> GDB_ID.NULL
            Dim nAsseBaseProj As Integer = 0
            EgtGetInfo(AsseBaseId, BTL_PRT_PROJ, nAsseBaseProj)
            If nAsseBaseProj = nImportProjId Then
               EgtSetInfo(AsseBaseId, BTL_PRT_PROJ, NewProjIdList(nProjIndex))
               Exit While
            End If
            AsseBaseId = EgtGetNextName(AsseBaseId, ASSEBASE)
         End While
         ' riporto nuovo ProjId nel layer BTLInfo
         EgtSetInfo(BTLInfoIdList(nProjIndex), BTL_PRT_PROJ, nNewProjId)
         ' resetto tutti gli stati di CALC
         For Each BTLPart In Map.refProjectVM.BTLStructureVM.BTLPartVMList
            BTLPart.ResetCalcTotalPart()
         Next
         ' salvo modifiche fatte al progetto
         bOk = bOk AndAlso Map.refSceneHostVM.MainController.SaveProject()
         If bOk Then
            ' copio file BTL e progetto
            Dim sBTLFromPath As String = sProjectimportDir & "\" & BTLFileNameList(nProjIndex) & ".btl"
            Dim sProjFileName As String = sNewProjDir & "\" & nNewProjId.ToString("0000") & ".nge"
            If sProjFromPath.Count > 0 AndAlso Not String.IsNullOrWhiteSpace(sProjFromPath(0)) Then
               Try
                  If Not String.IsNullOrWhiteSpace(sBTLFromPath) AndAlso File.Exists(sBTLFromPath) Then
                     Dim sBtlToPath As String = sNewProjDir & "\" & Path.GetFileName(sBTLFromPath)
                     File.Copy(sBTLFromPath, sBtlToPath)
                  Else
                     ErrorList.Add(String.Format("File BTL del progetto {0} non trovato", nImportProjId))
                  End If
                  File.Copy(sProjFromPath(0), sProjFileName)
               Catch ex As Exception
                  EgtOutLog("Impossibile copiare il file")
                  LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTPROJECT)
                  MessageBox.Show("Impossibile copiare il file del progetto", "Errore")
                  Return
               End Try
            End If
            ' aggiorno Db
            Dim sBTLFileName As String = BTLFileNameList(nProjIndex)
            Dim ExportDate As DateTime
            DateTime.TryParse(Map.refProjectVM.BTLStructureVM.BTLStructureM.m_sEXPDATE & " " &
                           Map.refProjectVM.BTLStructureVM.BTLStructureM.m_sEXPTIME, ExportDate)
            DbControllers.m_ProjController.UpdateInfo(nNewProjId, sBTLFileName, sBTLFileName, Map.refProjectVM.BTLStructureVM.sLISTNAME, ExportDate, nType, Machine.Name)
         Else
            ' elimino da Db

            ' CheckMe impostata come cancellazione FISICA dal DB...
            DbControllers.m_ProjController.DeleteProj(nNewProjId, False)
         End If
         ' aggiorno BTLParts su DB
         DbControllers.m_ProjController.UpdateBtlParts(nNewProjId, Map.refProjectVM.BTLStructureVM.BTLStructureM.BTLPartMList)
         ' resetto stato new
         DbControllers.m_ProjController.ResetNew(nNewProjId)
         ' resetto lock
         DbControllers.m_ProjController.LockByProjId(nNewProjId, False, Map.refMainWindowVM.MainWindowM.GetKeyNumber())
         DbControllers.m_ProjController.ResetController()
      Next
      ' se tutte le operazioni precedenti sono andate a buon fine
      If bOk Then
         ' sostituisco indicazione nuovi proj nei pezzi
         Dim nDuploLayerId As Integer = EgtGetFirstNameInGroup(GDB_ID.ROOT, "DuploBase")
         Dim nDuploId As Integer = EgtGetFirstInGroup(nDuploLayerId)
         While nDuploId <> GDB_ID.NULL
            ' recupero vecchio proj
            Dim nOldProjId As Integer
            EgtGetInfo(nDuploId, BTL_PRT_PROJ, nOldProjId)
            ' lo cerco nella lista
            Dim nOldProjIndex As Integer = ImportProjIdList.IndexOf(nOldProjId)
            ' lo sostituisco
            EgtSetInfo(nDuploId, BTL_PRT_PROJ, NewProjIdList(nOldProjIndex))
            nDuploId = EgtGetNext(nDuploId)
         End While
         ' resetto CurrProd per evitare di leggere valori produzione dal Db di quel progetto
         Map.refProdManagerVM.CurrProd = Nothing
         ' carico Machgroup che non verrebbero altrimenti importati
         Map.refProjectVM.MachGroupPanelVM = New MyMachGroupPanelVM(MyMachGroupPanelM.CreateMyMachGroupPanel(Map.refMachinePanelVM.MachineList.ToList()))
         If Map.refProjectVM.MachGroupPanelVM.MachGroupVMList.Count > 0 Then
            ' inizializzo nuovo progetto PROD
            Dim nProdId As Integer = 0
            Dim sProdDir As String = ""
            Map.refProdManagerVM.InitNewProject(NewProjIdList(0), nProdId, sProdDir)
            ' setto il PType del Prod
            DbControllers.m_ProdController.UpdatePType(nProdId, nType)
            ' setto la Macchina associata al Prod
            DbControllers.m_ProdController.UpdateMachine(nProdId, sMachine)
            For Each MachGroup As MyMachGroupVM In Map.refProjectVM.MachGroupPanelVM.MachGroupVMList
               ' aggiorno ProdId sui MachGroup
               EgtSetInfo(MachGroup.Id, MGR_RPT_PRODID, nProdId)
               If Map.refMainWindowVM.MainWindowM.nUserLevel < 5 OrElse GetMainPrivateProfileInt(S_MACH, K_EXPORTBWE, 0) <> 1 Then
                  ' resetto tutti gli stati di CALC
                  MachGroup.ResetCalcTotalMachGroup()
               End If
            Next
            If Map.refMainWindowVM.MainWindowM.nUserLevel >= 5 AndAlso GetMainPrivateProfileInt(S_MACH, K_EXPORTBWE, 0) = 1 Then
               ' riporto info di futuro aggiornamento machgroup 
               nBTLInfoLayerId = EgtGetFirstNameInGroup(GDB_ID.ROOT, BTLINFO)
               While nBTLInfoLayerId <> GDB_ID.NULL
                  EgtSetInfo(nBTLInfoLayerId, IMP_VERIFYMACHGROUP, True)
                  nBTLInfoLayerId = EgtGetNextName(nBTLInfoLayerId, BTLINFO)
               End While
            End If
            ' salvo il progetto PROD
            EgtSaveFile(sProjFromPath(0), NGE.CMPTEXT)
            ' copio file progetto
            Dim sProjPath As String = String.Empty
            Dim sProdPath As String = sProdDir & "\" & nProdId.ToString("0000") & ".nge"
            If EgtGetCurrFilePath(sProjPath) AndAlso Not String.IsNullOrEmpty(sProjPath) Then
               Try
                  File.Copy(sProjPath, sProdPath)
                  'Map.refSceneHostVM.MainController.OpenProject(sProdPath)
                  bOk = True
               Catch ex As Exception
                  EgtOutLog("Impossibile copiare il file")
                  bOk = False
               End Try
            End If
            If Map.refMainWindowVM.MainWindowM.nUserLevel >= 5 AndAlso GetMainPrivateProfileInt(S_MACH, K_EXPORTBWE, 0) = 1 Then
               ' copio tutti i bwe
               For Each CurrFile In Directory.GetFiles(sProjectimportDir)
                  If Path.GetExtension(CurrFile) = ".bwe" OrElse Path.GetExtension(CurrFile) = ".html" Then
                     File.Copy(CurrFile, sProdDir & "\" & Path.GetFileName(CurrFile))
                  End If
               Next
            End If
            If bOk Then
               ' aggiungo altri proj a prod
               For Each nProjId In NewProjIdList
                  DbControllers.m_ProdController.AddProj(nProdId, nProjId, Map.refMainWindowVM.MainWindowM.GetKeyNumber())
               Next
            Else
               ' elimino da DB
               DbControllers.m_ProdController.DeleteProd(nProdId, True)
            End If
            Dim MyMachGroupList As New List(Of MyMachGroupM)
            If Not IsNothing(Map.refProjectVM.MachGroupPanelVM) Then
               For Each MachGroup In Map.refProjectVM.MachGroupPanelVM.m_MyMachGroupPanelM.MachGroupMList
                  MyMachGroupList.Add(MachGroup)
               Next
            End If
            ' aggiorno pezzi su Db
            DbControllers.m_ProdController.UpdateMachGroup(nProdId, MyMachGroupList)
            ' resetto lock
            DbControllers.m_ProdController.LockByProdId(nProdId, False, Map.refMainWindowVM.MainWindowM.GetKeyNumber())
         End If
         DbControllers.m_ProdController.ResetController()
      End If
      ' imposto progetto corrente
      If NewProjIdList.Count > 0 Then
         SetCurrProj(NewProjIdList(0))
         OpenProject(CurrProj)
      End If
      ' ripristino eventuale CurrProd precedente
      Map.refProdManagerVM.CurrProd = CurrProd
      WriteMainPrivateProfileString(S_GENERAL, K_LASTNGEXPDIR, Path.GetDirectoryName(ImportDlg.FileName))
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.IMPORTPROJECT)
      ' imposto progetto corrente
      'If NewProjIdList.Count > 0 Then SetCurrProj(NewProjIdList(0))
      ' costruisco BTLStructure del proj
      'Map.refProjectVM.BTLStructureVM = New BTLStructureVM(BTLStructureM.CreateBTLStructure(NewProjIdList(0)))
      ' mostro tutti i pezzi
      'Map.refShowBeamPanelVM.ShowAll()
      'EgtZoom(ZM.ALL, True)
      ' aggiungo il file in apertura alla lista degli MRU
      'If Not IsNothing(CurrProj.ProjFileM) AndAlso Not IsNothing(CurrProj.sProjPath) Then Map.refProjManagerVM.m_MruFiles.Add(CurrProj.sProjPath)
      ' imposto macchina del progetto
      'Map.refMachinePanelVM.SelectedMachine = Machine
      ' aggiorno le colonne in base al tipo progetto
      'Map.refRawPartListVM.UpdateColumns(Map.refProjectVM.BTLStructureVM.BTLStructureM.nPROJTYPE)
      'Map.refPartInRawPartListVM.UpdateColumns(Map.refProjectVM.BTLStructureVM.BTLStructureM.nPROJTYPE)
      'DbControllers.m_ProjController.LockByProjId(Map.refProjManagerVM.CurrProj.nProjId, True)
      ' carico lista macchine e macchina del progetto per il pulsante Reset Macchina del CALCPanel
      'Map.refCALCPanelVM.LoadMachineList()
      'SectionXMaterial.SetType(nType)
      'ManageView.UpdateBWType(nType)
      'Map.refPartManagerVM.LockVisibilityUpdate()
      ' imposto flag secondo tipo di progetto (travi o pareti)
      'Dim sBTLFlag As String = If(nType = Core.ConstBeam.BWType.BEAM, K_BTLFLAG, K_WALLBTLFLAG)
      'Dim nFlag As Integer = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)
      'EgtBeamSetFlag(nFlag)
      'Map.refProjectVM.SetOptimizePanel_Visibility(Map.refProjectVM.BTLStructureVM.nPROJTYPE = BWType.WALL)
      ' aggiorno titolo
      'Map.refMainWindowVM.UpdateTitle()
   End Sub

#End Region ' ImportProject

#Region "GoToProd"

   ''' <summary>
   ''' Returns a command that do GoToProd.
   ''' </summary>
   Public ReadOnly Property GoToProd_Command As ICommand
      Get
         If m_cmdGoToProd Is Nothing Then
            m_cmdGoToProd = New Command(AddressOf GoToProd)
         End If
         Return m_cmdGoToProd
      End Get
   End Property

   ''' <summary>
   ''' Execute the GoToProd.  This method is invoked by the GoToProd_Command.
   ''' </summary>
   Public Sub GoToProd(ByVal param As Object)
      If IsNothing(CurrProj) Then Return
      ' verifico se progetto modificato, e chiedo se salvare
      Dim bSaved As Boolean = True
      If CurrProj.bIsNew Or EgtGetModified() OrElse Map.refCALCPanelVM.IsMachineModified() Then
         Select Case MessageBox.Show(EgtMsg(61877), "", MessageBoxButton.YesNoCancel, MessageBoxImage.Question)
            Case MessageBoxResult.Yes
               Save()
            Case MessageBoxResult.Cancel
               Return
            Case Else   ' No
               If Map.refProjManagerVM.CurrProj.bIsNew Then
                  MessageBox.Show(EgtMsg(61878), "", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                  Return
               End If
               ' resetto stato modificato
               Map.refSceneHostVM.MainController.ResetModified()
               bSaved = False
         End Select
      End If

      LoadingWndHelper.OpenLoadingWnd(ActiveIds.GOTOPROD, 3, EgtMsg(63004), EgtMsg(63011), 10)          ' Optimization opening      ' Loading environment

      Dim nProdId As Integer = Map.refProjManagerVM.CurrProj.nProdId
      If nProdId > 0 Then
         Map.refProdManagerVM.SetCurrProd(nProdId)
         Map.refProdManagerVM.CurrProd.SetReloadProject(Not bSaved)
      Else
         'creo nuova ottimizzazione da progetto corrente
         NewProdFromProj()

         '' chiedo se aggiungere ad ottimizzazione già presente o creare nuova
         'Select Case MessageBox.Show("Aggiungere ad ottimizzazione già esistente?", "", MessageBoxButton.YesNoCancel, MessageBoxImage.Information)
         '   Case MessageBoxResult.No
         '      'creo nuova ottimizzazione da progetto corrente
         '      NewProdFromProj()
         '   Case MessageBoxResult.Yes
         '      ' chiedo in quale ottimizzazione aggiungere il progetto corrente
         '      Dim OpenProjectFileDialogVM As New OpenProjectFileDialogVM
         '      Dim ChooseProdFileDialog As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjectFileDialogVM)
         '      Dim DialogResult As Boolean? = ChooseProdFileDialog.EgtShowDialog(ProjectType.PROD, True)
         '      If IsNothing(DialogResult) OrElse Not DialogResult Then Return
         '      ' se prod selezionato
         '      If Not IsNothing(OpenProjectFileDialogVM.SelProject.nProdId) AndAlso OpenProjectFileDialogVM.SelProject.nProdId > 0 Then
         '         Dim nCurrCtx As Integer = EgtGetCurrentContext()
         '         Dim nTempCtx As Integer = EgtInitContext()
         '         Dim bOk As Boolean = nTempCtx <> 0
         '         If bOk Then
         '            ' inizializzo gestore lavorazioni
         '            bOk = EgtInitMachMgr(Map.refMainWindowVM.MainWindowM.sMachinesRoot, Map.refMainWindowVM.MainWindowM.sToolMakersDir)
         '            ' apro il prod
         '            bOk = bOk AndAlso EgtOpenFile(OpenProjectFileDialogVM.SelProject.sProdPath)
         '            '''' calcolo BBox globale
         '            '''Dim b3Parts As BBox3d
         '            '''Dim nProdPartId As Integer = EgtGetFirstPart()
         '            '''While nProdPartId <> GDB_ID.NULL
         '            '''   Dim b3Part As New BBox3d
         '            '''   EgtGetBBoxGlob(nProdPartId, 1, b3Part)
         '            '''   b3Parts.Add(b3Part)
         '            '''   nProdPartId = EgtGetNextPart(nProdPartId)
         '            '''End While
         '            ' inserisco proj nel prod selezionato
         '            bOk = bOk AndAlso EgtInsertFile(Map.refProjManagerVM.CurrProj.sProjPath)
         '            ' DA METTERE IN MERGE BTL, NON QUI!!!
         '            '''' deseleziono tutto
         '            '''EgtDeselectAll()
         '            '''' ciclo sui pezzi
         '            '''Dim nPartId As Integer = EgtGetFirstPart()
         '            '''While nPartId <> GDB_ID.NULL
         '            '''   ' se arrivano dal nuovo progetto
         '            '''   Dim nCurrProjId As Integer
         '            '''   EgtGetInfo(nPartId, PROJ, nCurrProjId)
         '            '''   If nCurrProjId = Map.refProjManagerVM.CurrProj.nProjId Then
         '            '''      ' sposto i pezzi per non averli sovrapposti
         '            '''      EgtMove(nCurrProjId, New Vector3d(0, b3Parts.DimY() + 500, 0))
         '            '''   End If
         '            '''End While
         '            bOk = bOk AndAlso EgtSaveFile(OpenProjectFileDialogVM.SelProject.sProdPath, NGE.CMPTEXT)
         '            ' torno sul contesto corrente
         '            EgtSetCurrentContext(nCurrCtx)
         '            EgtDeleteContext(nTempCtx)
         '         End If
         '         If bOk Then
         '            ' riporto aggiunta proj a prod su Db
         '            DbControllers.m_ProdController.AddProj(OpenProjectFileDialogVM.SelProject.nProdId, Map.refProjManagerVM.CurrProj.nProjId)
         '            ' imposto currprod
         '            Map.refProdManagerVM.SetCurrProd(OpenProjectFileDialogVM.SelProject.nProdId)
         '         End If
         '      End If
         '   Case MessageBoxResult.Cancel
         '      Return
         'End Select
      End If
      ' Ricavo il tipo di Warehouse settato nell'INI
      Dim nDefault As Integer = 2
      If GetMainPrivateProfileInt(S_WAREHOUSE, EgtBEAMWALL.Core.ConstIni.K_TYPE, nDefault) = WarehouseType.MEDIUM Then
         ' Se di tipo Medium confronto le Sezioni del BTL importato con quelle in Warehouse
         WarehouseWndVM.UpdateSectionXMaterial()
      End If
      ' vado in pagina prod
      Map.refMainMenuVM.SetSelPage(Pages.MACHINING, False)
      ' aggiorno titolo
      Map.refMainWindowVM.UpdateTitle()
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.GOTOPROD)
   End Sub

#End Region ' GoToProd

#End Region    ' Commands

End Class
