예제 #1
0
 private static bool TryUnlockFile(IEdmFile5 file, out int?edmResultCode)
 {
     try
     {
         file.UnlockFile(0, "");
         edmResultCode = null;
         return(true);
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         edmResultCode = ex.ErrorCode;
         return(false);
     }
 }
예제 #2
0
        /// <summary>
        /// Registration or unregistation files by their paths and registration status.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="isRegistration"></param>
        public void CheckInOutPdm(string pathToFile, bool registration)
        {
            var retryCount = 5;

            try
            {
                IEdmFolder5 oFolder;
                IEdmFile5   edmFile5 = PdmExemplar.GetFileFromPath(pathToFile, out oFolder);
                edmFile5.GetFileCopy(0, 0, oFolder.ID, (int)EdmGetFlag.EdmGet_Simple);
                if (!registration) // Разрегистрировать
                {
                    while (!edmFile5.IsLocked && retryCount > 0)
                    {
                        edmFile5.LockFile(oFolder.ID, 0);
                        retryCount--;
                    }
                }
                if (registration) // Зарегистрировать
                {
                    while (edmFile5.IsLocked && retryCount > 0)
                    {
                        edmFile5.UnlockFile(oFolder.ID, "");
                        retryCount--;
                        Thread.Sleep(50);
                    }
                }
            }

            catch (Exception exception)
            {
                retryCount--;
                Thread.Sleep(200);
                if (retryCount == 0)
                {
                    //
                }
                throw exception;
            }
        }
        /// <summary>
        /// Registration or unregistation files by their paths and registration status.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="isRegistration"></param>
        public void CheckInOutPdm(string pathToFile, bool registration)
        {
            #region not working code
            //foreach (var file in filesList)
            //{
            //    try
            //    {
            //        IEdmFolder5 oFolder;
            //        IEdmFile5 edmFile5 = edmVault5.GetFileFromPath(file.FullName, out oFolder);

            //        var batchGetter = (IEdmBatchGet)(edmVault5 as IEdmVault7).CreateUtility(EdmUtility.EdmUtil_BatchGet);
            //        batchGetter.AddSelectionEx(edmVault5, edmFile5.ID, oFolder.ID, 0);
            //        if ((batchGetter != null))
            //        {
            //            batchGetter.CreateTree(0, (int)EdmGetCmdFlags.Egcf_SkipUnlockedWritable);
            //            batchGetter.GetFiles(0, null);
            //        }

            //        // Разрегистрировать
            //        if (!registration)
            //        {

            //            if (!edmFile5.IsLocked)
            //            {


            //                edmFile5.LockFile(oFolder.ID, 0);
            //                Thread.Sleep(50);
            //            }
            //        }
            //        else if (registration)
            //            if (edmFile5.IsLocked)
            //            {
            //                edmFile5.UnlockFile(oFolder.ID, "");
            //                Thread.Sleep(50);
            //            }
            //    }

            //    catch (Exception exception)
            //    {
            //       //Observer.MessageObserver.Instance.SetMessage(exception.ToString() + "\n" + exception.StackTrace + "\n" + exception.Source);
            //    }
            //}



            //foreach (var eachFile in files)
            //{
            //    try
            //    {
            //        IEdmFolder5 folderPdm;
            //        IEdmFile5 filePdm = edmVault5.GetFileFromPath(eachFile.FullName, out folderPdm);

            //        if (filePdm == null)
            //        {
            //            filePdm.GetFileCopy(0, 0, folderPdm.ID, (int)EdmGetFlag.EdmGet_Simple);
            //        }

            //        // Разрегистрировать
            //        if (registration == false)
            //        {
            //            if (!filePdm.IsLocked)
            //            {
            //                filePdm.LockFile(folderPdm.ID, 0);
            //                Thread.Sleep(50);
            //            }
            //        }
            //        else
            //        {
            //            if (filePdm.IsLocked)
            //            {
            //                filePdm.UnlockFile(folderPdm.ID, "");
            //                Thread.Sleep(50);
            //            }
            //        }
            //    }

            //    catch (Exception exception)
            //    {
            //       //Observer.MessageObserver.Instance.SetMessage(exception.ToString() + "\n" + exception.StackTrace + "\n" + exception.Source);
            //    }
            //}

            #endregion

            var retryCount = 2;
            var success    = false;
            while (!success && retryCount > 0)
            {
                try
                {
                    IEdmFolder5 oFolder;
                    IEdmFile5   edmFile5 = PdmExemplar.GetFileFromPath(pathToFile, out oFolder);
                    edmFile5.GetFileCopy(0, 0, oFolder.ID, (int)EdmGetFlag.EdmGet_Simple);
                    // Разрегистрировать
                    if (registration == false)
                    {
m1:
                        edmFile5.LockFile(oFolder.ID, 0);
                        //Observer.MessageObserver.Instance.SetMessage(edmFile5.Name);
                        Thread.Sleep(50);
                        var j = 0;
                        if (!edmFile5.IsLocked)
                        {
                            j++;
                            if (j > 5)
                            {
                                goto m3;
                            }
                            goto m1;
                        }
                    }
                    // Зарегистрировать
                    if (registration)
                    {
                        try
                        {
m2:
                            edmFile5.UnlockFile(oFolder.ID, "");
                            Thread.Sleep(50);
                            var i = 0;
                            if (edmFile5.IsLocked)
                            {
                                i++;
                                if (i > 5)
                                {
                                    goto m4;
                                }
                                goto m2;
                            }
                        }
                        catch (Exception exception)
                        {
                            MessageObserver.Instance.SetMessage(exception.ToString());
                        }
                    }
m3:
m4:
                    //LoggerInfo(string.Format("В базе PDM - {1}, зарегестрирован документ по пути {0}", file.FullName, vaultName), "", "CheckInOutPdm");
                    success = true;
                }


                catch (Exception exception)
                {
                    //  Логгер.Ошибка($"Message - {exception.ToString()}\nfile.FullName - {file.FullName}\nStackTrace - {exception.StackTrace}", null, "CheckInOutPdm", "SwEpdm");
                    retryCount--;
                    Thread.Sleep(200);
                    if (retryCount == 0)
                    {
                        //
                    }
                    throw exception;
                }
            }
            if (!success)
            {
                //LoggerError($"Во время регистрации документа по пути {file.FullName} возникла ошибка\nБаза - {vaultName}. {exception.ToString()}", "", "CheckInOutPdm");
            }
        }
        public void runTask()//EdmCmdData[] data
        {
            List <string> file2Delete = new List <string>();

            try
            {
                //Keep the Task List status up to date
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_Running);
                inst.SetProgressRange(100, 0, "Starting");

                string tempDir    = Path.GetTempPath() + @"AutoCadTaskConverter\";
                string dataName   = tempDir + @"proccessFile.txt";
                string scriptPath = tempDir + @"proccessScript.scr";
                string lispPath   = tempDir + @"proccessLisp.lsp";
                if (!Directory.Exists(tempDir))
                {
                    Directory.CreateDirectory(tempDir);
                }


                file2Delete.Add(dataName);
                file2Delete.Add(scriptPath);
                file2Delete.Add(lispPath);


                //collect data
                foreach (EdmCmdData item in data)
                {
                    if (item.mlLongData1 == (long)EdmObjectType.EdmObject_File)
                    {
                        var fileParm = new AutoCADParameters();
                        fileParm.FileId   = item.mlObjectID1;
                        fileParm.FolderId = item.mlObjectID2;
                        fileParm.FileName = item.mbsStrData1;

                        ///Custom code to output path
                        var path = Path.GetDirectoryName(fileParm.FileName).Split('\\');
                        try
                        {
                            if (path.Length > 3 && path[2].Equals("30 Projects"))
                            {
                                fileParm.OutputPath    = Path.Combine(path[0] + @"\", path[1], path[2], path[3], "03 PDFs", Path.GetFileNameWithoutExtension(fileParm.FileName) + ".pdf");
                                fileParm.OutputPathDXF = Path.Combine(path[0] + @"\", path[1], path[2], path[3], "04 DXFs", Path.GetFileNameWithoutExtension(fileParm.FileName) + ".dxf");
                            }
                            else
                            {
                                fileParm.OutputPath    = Path.ChangeExtension(fileParm.FileName, ".pdf");
                                fileParm.OutputPathDXF = Path.ChangeExtension(fileParm.FileName, ".dxf");
                            }
                        }
                        catch
                        {
                            fileParm.OutputPath    = Path.ChangeExtension(fileParm.FileName, ".pdf");
                            fileParm.OutputPathDXF = Path.ChangeExtension(fileParm.FileName, ".dxf");
                        }


                        var CADFile = vault.GetFileFromPath(fileParm.FileName, out IEdmFolder5 Cadfld);
                        if (CADFile == null)
                        {
                            break;
                        }

                        string OutputfilePath = tempDir + Path.GetFileNameWithoutExtension(fileParm.FileName) + ".pdf";

                        if (System.IO.File.Exists(OutputfilePath))
                        {
                            File.Delete(OutputfilePath);
                        }


                        inst.SetProgressPos(10, "Writting report");
                        ///Write json file ensure file is local
                        JsonSerializer serializer = new JsonSerializer();
                        using (StreamWriter sw = new StreamWriter(dataName, false))
                        {
                            using (JsonWriter writer = new JsonTextWriter(sw))
                            {
                                serializer.Serialize(writer, fileParm);
                            }
                        }
                        inst.SetProgressPos(15, "Launching application");


                        ///Launch autocad.
                        File.WriteAllText(scriptPath, string.Format(AutoCADConversion.Properties.Resources.AcadScript, lispPath.Replace(@"\", @"\\")));
                        File.WriteAllText(lispPath, string.Format(AutoCADConversion.Properties.Resources.ACADLisp, @"""" + OutputfilePath.Replace(@"\", @"\\") + @""""));

                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                        {
                            CreateNoWindow  = false,
                            UseShellExecute = true,
                            FileName        = CorePath,
                            WindowStyle     = System.Diagnostics.ProcessWindowStyle.Normal,
                            Arguments       = $"/i \"{fileParm.FileName}\" /s \"{scriptPath}\""
                        };

                        using (System.Diagnostics.Process exeProccess = System.Diagnostics.Process.Start(startInfo))
                        {
                            inst.SetProgressPos(20, "Launching application");
                            exeProccess?.WaitForExit();
                        }

                        //If Pdf has generated, then copy the file to the desitnation output
                        if (System.IO.File.Exists(OutputfilePath))
                        {
                            var allFiles = Directory.GetFiles(Path.GetDirectoryName(OutputfilePath), Path.GetFileNameWithoutExtension(OutputfilePath) + "*");
                            if (allFiles.Count() > 1)
                            {
                                List <string> files2Merge = new List <string>();
                                foreach (string f in allFiles)
                                {
                                    if (f.Equals(OutputfilePath, StringComparison.OrdinalIgnoreCase))
                                    {
                                        file2Delete.Add(OutputfilePath);
                                    }
                                    else if (Path.GetExtension(f).Equals(".dxf", StringComparison.OrdinalIgnoreCase))
                                    {
                                        file2Delete.Add(Path.ChangeExtension(OutputfilePath, ".dxf"));
                                    }
                                    else
                                    {
                                        files2Merge.Add(f);
                                        file2Delete.Add(f);
                                    }
                                }
                                if (files2Merge.Count > 0)
                                {
                                    files2Merge.Insert(0, OutputfilePath);
                                    PdfDocument finalDoc = new PdfDocument();
                                    PdfDocument.Merge(finalDoc, files2Merge.ToArray());
                                    File.Delete(OutputfilePath);
                                    finalDoc.Save(OutputfilePath);
                                    finalDoc.Close(true);
                                }
                            }
                            else
                            {
                                file2Delete.Add(OutputfilePath);
                                file2Delete.Add(Path.ChangeExtension(OutputfilePath, ".dxf"));
                            }

                            IEdmFile5 filePDF = CopyFileIntoVault(OutputfilePath, fileParm.OutputPath);
                            IEdmFile5 fileDXF = CopyFileIntoVault(Path.ChangeExtension(OutputfilePath, ".dxf"), fileParm.OutputPathDXF);


                            //If pdf is now in the vault
                            if (filePDF != null)
                            {
                                //Update variables, first get a copy of the files from the source
                                IEdmBatchListing4 var = (IEdmBatchListing4)vault.CreateUtility(EdmUtility.EdmUtil_BatchList);
                                var.AddFileCfg(fileParm.FileName, default(DateTime), 0);
                                var colsetNames = var.GetColumnSetNames();

                                //string atts = "";
                                //foreach (VariableMapperViewModel va in settings.Variables)
                                //{
                                //    if (va.MapVariable)
                                //        atts += "\n" + va.SourceVariable.Name;
                                //}


                                string         atts  = "\nDescription\nDescription2\nDescription3\nRevision\nDocument Number\nDrawnBy\nApprovedBy\nProject Name\nProject Number";
                                EdmListCol[]   cols  = default(EdmListCol[]);
                                EdmListFile2[] files = default(EdmListFile2[]);
                                var.CreateListEx(atts, (int)EdmCreateListExFlags.Edmclef_MayReadFiles, ref cols, null);
                                var.GetFiles2(ref files);

                                //Now copy the files to the variables.
                                IEdmBatchUpdate2 bUp = (IEdmBatchUpdate2)vault.CreateUtility(EdmUtility.EdmUtil_BatchUpdate);
                                foreach (EdmListFile2 getFile in files)
                                {
                                    for (int i = 0; i < cols.Length; i++)
                                    {
                                        bUp.SetVar(filePDF.ID, cols[i].mlVariableID, ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                        bUp.SetVar(fileDXF.ID, cols[i].mlVariableID, ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                    }
                                }
                                //Set SourcedState
                                bUp.SetVar(filePDF.ID, 171, "Released", "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                bUp.SetVar(fileDXF.ID, 171, "Released", "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //Set AutomaticallyGenerated
                                bUp.SetVar(filePDF.ID, 158, 1, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                bUp.SetVar(fileDXF.ID, 158, 1, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //foreach (EdmListFile2 getFile in files)
                                //{
                                //    for (int i = 0; i < cols.Length; i++)
                                //    {
                                //        VariableMapperViewModel va = settings.Variables.FirstOrDefault(t=> t.SourceVariable.Id == ((EdmListCol[])cols)[i].mlVariableID);
                                //        bUp.SetVar(Outfile.ID, va.DestinationVariable.Id , ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //    }
                                //}

                                ////copy the static text
                                //foreach (VariableMapperViewModel va in settings.Variables)
                                //{
                                //    if (!va.MapVariable)
                                //        bUp.SetVar(Outfile.ID, va.DestinationVariable.Id, va.Value, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //}

                                if (0 != bUp.CommitUpdate(out EdmBatchError2[] err))
                                {
                                    PDMAddin.log.Error("Variable errors");
                                }
                                //Check file in.
                                //IEdmFolder5 fldPDF = vault.GetFolderFromPath(Path.GetDirectoryName(fileParm.OutputPath));
                                // IEdmFolder5 fldDXF = vault.GetFolderFromPath(Path.GetDirectoryName(fileParm.OutputPathDXF));

                                filePDF.UnlockFile(0, "Automaticly created", (int)EdmUnlockFlag.EdmUnlock_IgnoreReferences);
                                fileDXF.UnlockFile(0, "Automaticly created", (int)EdmUnlockFlag.EdmUnlock_IgnoreReferences);
                            }
                        }
                    }
                }

                ///comlete

                inst.SetProgressPos(100, "finished");
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneOK);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                PDMAddin.log.Error(ex);
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneFailed, ex.ErrorCode, "The task failed!");
            }
            catch (Exception ex)
            {
                PDMAddin.log.Error(ex);
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneFailed, 0, "", "The task failed!");
            }
            finally
            {
                foreach (string f in file2Delete)
                {
                    if (File.Exists(f))
                    {
                        File.Delete(f);
                    }
                }
            }
        }