/// <summary>
        /// Returns profile image bytes that belong to specific student.
        /// </summary>
        /// <param name="studentId">Unique identifier for the student</param>'
        /// <param name="height">Height of resized image</param>
        /// <param name="width">Width of resized image</param>
        /// <returns>Array of bytes wrapped with file name</returns>
        public async Task <ResultMessage <BasicFileInfo> > GetStudentProfileImage(int studentId, int?width, int?height)
        {
            ResultMessage <StudentDTO> result = await _studentService.GetSingleOrDefault(s => s.StudentId == studentId && !s.Deleted);

            if (result.IsSuccess)
            {
                string photoPath = result.Result.Photo;
                if (photoPath == null)
                {
                    return(new ResultMessage <BasicFileInfo>(OperationStatus.NotFound));
                }

                ResultMessage <BasicFileInfo> downloadRes = await _docService.DownloadFromStorage(photoPath);

                if (!downloadRes.IsSuccess)
                {
                    return(new ResultMessage <BasicFileInfo>(OperationStatus.UnknownError));
                }

                BasicFileInfo image = downloadRes.Result;

                int widthRequest  = width.GetValueOrDefault(_resizeWidth);
                int heightRequest = width.GetValueOrDefault(_resizeHeight);

                byte[] resizedImgData = ResizeImage(image.FileData, widthRequest, heightRequest);

                BasicFileInfo resizedImg = new BasicFileInfo(image.FileName, resizedImgData);

                return(new ResultMessage <BasicFileInfo>(resizedImg));
            }
            else
            {
                return(new ResultMessage <BasicFileInfo>(OperationStatus.NotFound));
            }
        }
Exemple #2
0
        private void OnDocumentSynchronizingWithCentral(object sender, DocumentSynchronizingWithCentralEventArgs e)
        {
            tempPath = Path.GetDirectoryName(BasicFileInfo.Extract(e.Document.PathName).CentralPath) + @"\tracker\";
            try{
                var path = tempPath + documentName + "_" + username;

                if (!File.Exists(path))
                {
                    var di = Directory.CreateDirectory(Path.GetDirectoryName(path));
                    di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
                }
                if (deletedList.Count > 0)
                {
                    using (var tw = new StreamWriter(path, true, System.Text.Encoding.GetEncoding(1251)))
                    {
                        deletedList.ForEach((item) =>
                        {
                            tw.WriteLine(item.ToString());
                        });
                    }
                }
                deletedList.Clear();
                addedList.Clear();
            }
            catch {
            }
        }
Exemple #3
0
        public static void DocClosed(object sender, DocumentClosingEventArgs args)
        {
            Document currentDoc = args.Document;

            Autodesk.Revit.ApplicationServices.Application uiApp = currentDoc.Application;

            if (!currentDoc.IsFamilyDocument)
            {
                EventData ptdata = new EventData("ProjectTime");
                ptdata.DirSetup();
                string        fp    = currentDoc.PathName;
                BasicFileInfo bfi   = BasicFileInfo.Extract(fp);
                string        fpath = bfi.CentralPath.Split('\\').Last().Split('.').First();
                string        pnum  = currentDoc.ProjectInformation.Number.ToString();

                EventData odata = new EventData(pnum);
                string[]  Open  = File.ReadAllLines(odata.FileName);

                DateTime dtin = DateTime.MinValue;
                DateTime.TryParse(Open.Last().Split(',')[3], out dtin);
                if (dtin != DateTime.MinValue)
                {
                    long     timedif = ptdata.Time.Ticks - dtin.Ticks;
                    double   hours   = TimeSpan.FromTicks(timedif).TotalHours;
                    string[] lines   = new string[1];
                    lines[0] = ptdata.User + "," + pnum + "," + fpath + "," + ptdata.Time + "," + hours.ToString() + "," + Open.Last().Split(',')[4];
                    File.AppendAllLines(ptdata.FileName, lines);
                    File.Delete(odata.FileName);
                }
            }
        }
Exemple #4
0
        public Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = revit.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string path = doc.PathName;

            BasicFileInfo info = BasicFileInfo.Extract(
                path);

            DocumentVersion v = info.GetDocumentVersion();

            int n = v.NumberOfSaves;

            Util.InfoMsg(string.Format(
                             "Document '{0}' has GUID {1} and {2} save{3}.",
                             path, v.VersionGUID, n,
                             Util.PluralSuffix(n)));

            return(Result.Succeeded);
        }
Exemple #5
0
        private void DeleteFile(UIDocument UIdoc, Transaction t)
        {
            Document _doc             = UIdoc.Document;
            string   _filePath        = BasicFileInfo.Extract(_doc.PathName).CentralPath;
            string   _filename        = Path.GetFileNameWithoutExtension(_filePath);
            string   _filedir         = Path.GetDirectoryName(_filePath);
            string   _backupDir       = _filename + "_backup";
            string   _corruptFileName = "corrupt";
            string   fullPath         = Path.Combine(_filedir, _backupDir, _corruptFileName);

            if (File.Exists(fullPath))
            {
                MessageBoxResult question = MessageBox.Show($"Удалить файл {fullPath} ?", "Удалить коррупцию", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                if (question == MessageBoxResult.OK)
                {
                    t.Start("Удалить файл Corrupt");
                    try
                    {
                        File.Delete(fullPath);
                    }
                    catch (IOException exception)
                    {
                        MessageBox.Show("Ошибка", exception.Message);
                    }
                    TaskDialog.Show("Удалить файл", "Файл " + _corruptFileName + " удален.");
                    t.Commit();
                }
            }
            else
            {
                MessageBox.Show($"Файл {_corruptFileName} не найден по пути {fullPath}", "Ошибка");
            }
        }
        /// <summary>
        /// Retrieve the project identification information
        /// to store in the external database and return it
        /// as a dictionary in a JSON formatted string.
        /// </summary>
        string GetProjectDataJson(
            //string project_id,
            Document doc)
        {
            string path = doc.PathName.Replace('\\', '/');

            BasicFileInfo   file_info   = BasicFileInfo.Extract(path);
            DocumentVersion doc_version = file_info.GetDocumentVersion();
            ModelPath       model_path  = doc.GetWorksharingCentralModelPath();

            string central_server_path = null != model_path
        ? model_path.CentralServerPath
        : string.Empty;

            // Hand-written JSON formatting.

            string s = string.Format(
                //"\"_id\": \"{0}\","
                "\"projectinfo_uid\": \"{0}\","
                + "\"versionguid\": \"{1}\","
                + "\"numberofsaves\": {2},"
                + "\"title\": \"{3}\","
                + "\"centralserverpath\": \"{4}\","
                + "\"path\": \"{5}\","
                + "\"computername\": \"{6}\","
                + "\"jid\": \"{7}\"",
                //project_id,
                doc.ProjectInformation.UniqueId,
                doc_version.VersionGUID,
                doc_version.NumberOfSaves,
                doc.Title,
                central_server_path,
                path,
                System.Environment.MachineName,
                Util.GetProjectIdentifier(doc));

            return("{" + s + "}");

            #region Use JavaScriptSerializer
#if USE_JavaScriptSerializer
            // Use JavaScriptSerializer to format JSON data.

            ProjectData project_data = new ProjectData()
            {
                projectinfo_uid   = doc.ProjectInformation.UniqueId,
                versionguid       = doc_version.VersionGUID.ToString(),
                numberofsaves     = doc_version.NumberOfSaves,
                title             = doc.Title,
                centralserverpath = central_server_path,
                path         = path,
                computername = System.Environment.MachineName
            };

            return(new JavaScriptSerializer().Serialize(
                       project_data));
#endif // USE_JavaScriptSerializer
            #endregion // Use JavaScriptSerializer
        }
Exemple #7
0
        public bool WriteToRVTFile(string rvtFilePath, BasicFileInfo basicFileInfo)
        {
            if (!File.Exists(rvtFilePath))
            {
                return(false);
            }
            StorageMode    grfMode        = StorageMode.ReadWrite | StorageMode.ShareExclusive;
            OleRootStorage oleRootStorage = new OleRootStorage();
            string         text           = null;

            try
            {
                if (!oleRootStorage.Open(rvtFilePath, (int)grfMode))
                {
                    return(false);
                }
                var       modelDataStreamIdentifier = new ModelDataStreamIdentifier(ModelDataStreamType.mdstBasicFileInfo);
                OleStream oleStream = oleRootStorage.OpenStream(modelDataStreamIdentifier.StreamName, grfMode);
                text = Path.GetTempFileName();
                if (!WriteToStreamFile(text, basicFileInfo))
                {
                    return(false);
                }
                if (!oleStream.Import(text))
                {
                    return(false);
                }
                oleStream.Commit();
                oleRootStorage.Commit();
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                if (text != null)
                {
                    try
                    {
                        File.Delete(text);
                    }
                    catch (Exception)
                    {
                    }
                }
                oleRootStorage.Close(isSave: true);
            }
            return(true);
        }
        public static void UpdateSplashPage(Document currentDoc)
        {
            string        fp   = currentDoc.PathName;
            BasicFileInfo bfi  = BasicFileInfo.Extract(fp);
            string        proj = bfi.CentralPath.Split('\\').Last().Split('.').First();
            string        pdir = DBIdentifiers.Database + "ProjectData\\" + proj + "\\";

            if (Directory.Exists(pdir))
            {
                string[] files = Directory.GetFiles(pdir);
                PData    data  = PDataFromRevit(currentDoc);
                PDataParamUpdates(currentDoc, data);
            }
        }
Exemple #9
0
        public BasicFileInfo ReadFromRVTFile(string rvtFilePath)
        {
            if (!File.Exists(rvtFilePath))
            {
                return(null);
            }
            StorageMode    grfMode        = StorageMode.ReadWrite | StorageMode.ShareExclusive;
            OleRootStorage oleRootStorage = new OleRootStorage();
            BasicFileInfo  basicFileInfo  = null;
            string         text           = null;

            try
            {
                if (!oleRootStorage.Open(rvtFilePath, (int)grfMode))
                {
                    return(null);
                }
                var       modelDataStreamIdentifier = new ModelDataStreamIdentifier(ModelDataStreamType.mdstProjectInformation);
                OleStream oleStream = oleRootStorage.OpenStream(modelDataStreamIdentifier.StreamName, grfMode);
                text = Path.GetTempFileName();
                if (!oleStream.Export(text))
                {
                    return(null);
                }
                return(ReadFromStreamFile(text));
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
                if (text != null)
                {
                    try
                    {
                        File.Delete(text);
                    }
                    catch (Exception)
                    {
                    }
                }
                oleRootStorage.Close(isSave: false);
            }
        }
Exemple #10
0
        public static void ViewChangeTime(object sender, ViewActivatedEventArgs args)
        {
            View     closingView = args.PreviousActiveView;
            View     openedView  = args.CurrentActiveView;
            Document closingDoc  = closingView.Document;
            Document openedDoc   = openedView.Document;

            if (closingView != openedView)
            {
                EventData rdata = new EventData("ProjectTime");
                rdata.DirSetup();
                string        fp    = closingDoc.PathName;
                BasicFileInfo bfi   = BasicFileInfo.Extract(fp);
                string        fpath = bfi.CentralPath.Split('\\').Last().Split('.').First();
                string        pnum  = closingDoc.ProjectInformation.Number.ToString();

                EventData cdata = new EventData(pnum);
                string[]  Open  = File.ReadAllLines(cdata.FileName);

                DateTime dtin = DateTime.MinValue;
                DateTime.TryParse(Open.Last().Split(',')[3], out dtin);
                if (dtin != DateTime.MinValue)
                {
                    long     timedif = rdata.Time.Ticks - dtin.Ticks;
                    double   hours   = TimeSpan.FromTicks(timedif).TotalHours;
                    string[] clines  = new string[1];
                    clines[0] = rdata.User + "," + pnum + "," + fpath + "," + rdata.Time + "," + hours.ToString() + "," + Open.Last().Split(',')[4];
                    File.AppendAllLines(rdata.FileName, clines);
                    File.Delete(cdata.FileName);
                }

                if (!openedDoc.IsFamilyDocument)
                {
                    string        ofp    = openedDoc.PathName;
                    BasicFileInfo obfi   = BasicFileInfo.Extract(fp);
                    string        ofpath = obfi.CentralPath.Split('\\').Last().Split('.').First();
                    string        opnum  = openedDoc.ProjectInformation.Number.ToString();
                    EventData     odata  = new EventData(opnum);

                    string[] olines = new string[1];
                    olines[0] = odata.User + "," + opnum + "," + ofpath + "," + odata.Time + "," + openedView.Name;
                    File.AppendAllLines(odata.FileName, olines);
                }
            }
        }
Exemple #11
0
        private static void OnDocumentOpening(object source, DocumentOpeningEventArgs args)
        {
            try
            {
                var pathName = args.PathName;
                if (string.IsNullOrEmpty(pathName) || args.DocumentType != DocumentType.Project)
                {
                    return;
                }

                var fileInfo    = BasicFileInfo.Extract(pathName);
                var centralPath = fileInfo.CentralPath;
                Log.Initialize("HOK_Tools", string.IsNullOrEmpty(centralPath) ? string.Empty : centralPath);
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Exemple #12
0
        //This runs the events on startup
        public static void starttime(object sender, DocumentOpenedEventArgs args)
        {
            Document currentDoc = args.Document;

            Autodesk.Revit.ApplicationServices.Application uiApp = currentDoc.Application;
            if (!currentDoc.IsFamilyDocument)
            {
                string        fp    = currentDoc.PathName;
                BasicFileInfo bfi   = BasicFileInfo.Extract(fp);
                string        fpath = bfi.CentralPath.Split('\\').Last().Split('.').First();
                string        pnum  = currentDoc.ProjectInformation.Number.ToString();
                EventData     edata = new EventData(pnum);
                edata.DirSetup();

                string[] lines = new string[1];
                string   line  = edata.User + "," + pnum + "," + fpath + "," + edata.Time + ",Open";
                lines[0] = line;

                File.AppendAllLines(edata.FileName, lines);
            }
        }
 public SimpleBinaryFile(BasicFileInfo basicMetadata, byte[] content, int contentId) : this(basicMetadata, content, new SimpleVersion(contentId))
 {
 }
Exemple #14
0
        // https://forums.autodesk.com/t5/revit-api-forum/reload-revit-links-from/m-p/7722248
        public Result Execute1(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get application and document objects

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            // NO TRANSACTION NEEDS TO BE OPENED

            try
            {
                using (Transaction tx = new Transaction(doc))
                {
                    // Collect files linked in current project

                    FilteredElementCollector collector     = new FilteredElementCollector(doc);
                    ICollection <Element>    linkInstances = collector.OfClass(typeof(RevitLinkType)).ToElements();

                    // Check which elements are loaded > to be used as filter

                    List <bool> loaded = new List <bool>();
                    foreach (RevitLinkType i in linkInstances)
                    {
                        loaded.Add(RevitLinkType.IsLoaded(doc, i.Id));
                    }

                    // Convert ICollection into a list of RevitLinkTypes
                    int i1 = 0;

                    List <RevitLinkType> revLinkType = new List <RevitLinkType>();
                    foreach (RevitLinkType rli in linkInstances)
                    {
                        if (!loaded[i1++])
                        {
                            revLinkType.Add(rli);
                        }
                    }

                    // Put names of linked files into a list of strings
                    int i2 = 0;

                    List <string> linkNames = new List <string>();
                    foreach (Element eli in linkInstances)
                    {
                        if (!loaded[i2++])
                        {
                            linkNames.Add(eli.Name.Split(' ')[0]);
                        }
                    }

                    // Prompt user with files selection dialog

                    //Start:
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.InitialDirectory = (@"P:\");
                    openFileDialog1.Filter           = "RVT|*.rvt";
                    openFileDialog1.Multiselect      = true;
                    openFileDialog1.RestoreDirectory = true;

                    // If you select the files and hit OK (in the file browser)

                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        // Show which files (path + version) has been selected before linking them

                        StringBuilder userSelectionWVersion = new StringBuilder();
                        foreach (string fp in openFileDialog1.FileNames)
                        {
                            userSelectionWVersion.AppendLine(
                                fp.ToString()
                                + " which was created with " +
                                BasicFileInfo.Extract(fp).SavedInVersion.ToString().ToUpper());
                        }

                        // Recap the user with his selection + Revit version of the file

                        DialogResult linkCorrect = MessageBox.Show(
                            userSelectionWVersion.ToString(),
                            "You selected the files:",
                            MessageBoxButtons.OKCancel);

                        // Put paths of files selected by user into a list

                        if (linkCorrect == DialogResult.OK)
                        {
                            List <string> userSelectionNames = new List <string>();
                            foreach (string fp in openFileDialog1.FileNames)
                            {
                                userSelectionNames.Add(fp.ToString());
                            }

                            // Check which of the files that the user selected have the same name of the files linked in the project

                            IEnumerable <string> elementsToReload = userSelectionNames.Where(a => linkNames.Exists(b => a.Contains(b)));

                            // Show which files need to be reloaded

                            StringBuilder intersection = new StringBuilder();
                            foreach (string fp in elementsToReload)
                            {
                                intersection.AppendLine(fp.ToString());
                            }
                            DialogResult promptToLoad = MessageBox.Show(intersection.ToString(), "The following files need to be roloaded");

                            // Initialize + populate list of ModelPaths > path from where to reload

                            List <ModelPath> modPaths = new List <ModelPath>();

                            foreach (string fp in elementsToReload)
                            {
                                FileInfo  filePath = new FileInfo(fp);
                                ModelPath linkpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.ToString());
                                modPaths.Add(linkpath);
                            }

                            // Zip together file (as RevitLinkType) and the corresponding path to be reloaded from > Reload

                            foreach (var ab in revLinkType.Zip(modPaths, Tuple.Create))
                            {
                                ab.Item1.LoadFrom(ab.Item2, new WorksetConfiguration());
                            }
                        }
                        return(Result.Succeeded);
                    }
                }
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed

                DialogResult genericException = MessageBox.Show(ex.Message, "Oops there was problem!");

                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Exemple #15
0
 public SimpleStringFile(BasicFileInfo basicMetadata, string content, SimpleVersion version) :
     base(basicMetadata, Encoding.UTF8.GetBytes(content), version)
 {
 }
Exemple #16
0
 public SimpleStringFile(BasicFileInfo basicMetadata, string content) : this(basicMetadata, content, 0)
 {
 }
Exemple #17
0
 public SimpleStringFile(BasicFileInfo basicMetadata, string content, int contentId) : this(basicMetadata, content, new SimpleVersion(contentId))
 {
 }
Exemple #18
0
        private void CollectConfigurationOnOpening(object source, DocumentOpeningEventArgs args)
        {
            try
            {
                string pathName = args.PathName;
                if (!string.IsNullOrEmpty(pathName) && args.DocumentType == DocumentType.Project)
                {
                    BasicFileInfo fileInfo = BasicFileInfo.Extract(pathName);
                    if (fileInfo.IsWorkshared)
                    {
                        if (!socketOn)
                        {
                            ConnectSocket();
                        }

                        string centralPath = fileInfo.CentralPath;
                        if (!string.IsNullOrEmpty(centralPath))
                        {
                            //serch for config
                            LogUtil.AppendLog(centralPath + " Opening.");
                            Configuration configFound = ServerUtil.GetConfigurationByCentralPath(centralPath);
                            if (null != configFound)
                            {
                                //check if the single session should be activated
                                if (SingleSessionMonitor.CancelOpening(centralPath, configFound))
                                {
                                    if (args.Cancellable)
                                    {
                                        SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath);
                                        if ((bool)ssWindow.ShowDialog())
                                        {
                                            args.Cancel();
                                            return;
                                        }
                                    }
                                }

                                if (configDictionary.ContainsKey(centralPath))
                                {
                                    configDictionary.Remove(centralPath);
                                }
                                configDictionary.Add(centralPath, configFound);

                                Project projectFound = ServerUtil.GetProjectByConfigurationId(configFound._id);
                                if (null != projectFound)
                                {
                                    if (projectDictionary.ContainsKey(centralPath))
                                    {
                                        projectDictionary.Remove(centralPath);
                                    }
                                    projectDictionary.Add(centralPath, projectFound);
                                }

                                LogUtil.AppendLog("Configuration Found: " + configFound._id);
                            }
                            else
                            {
                                //not a seed file, just check if the single session is activated
                                if (SingleSessionMonitor.SingleSessionActivated)
                                {
                                    SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath);
                                    if ((bool)ssWindow.ShowDialog())
                                    {
                                        args.Cancel();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("CollectConfigurationOnOpening:" + ex.Message);
            }
        }
Exemple #19
0
        protected BasicFileInfo ReadFromStreamFile(string basicFileInfoFilename)
        {
            if (!File.Exists(basicFileInfoFilename))
            {
                return(null);
            }
            BasicFileInfo basicFileInfo = new BasicFileInfo();

            using (BinaryReader binaryReader = new BinaryReader(File.Open(basicFileInfoFilename, FileMode.Open), Encoding.Unicode))
            {
                try
                {
                    basicFileInfo.Version          = (BasicFileInfoStreamVersion)binaryReader.ReadInt32();
                    basicFileInfo.IsWorkshared     = binaryReader.ReadBoolean();
                    basicFileInfo.WorksharingState = (WorksharingState)binaryReader.ReadByte();
                    basicFileInfo.Username         = readString(binaryReader);
                    basicFileInfo.CentralPath      = readString(binaryReader);
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_Format)
                    {
                        basicFileInfo.Format       = readString(binaryReader);
                        basicFileInfo.BuildVersion = readString(binaryReader);
                    }
                    else
                    {
                        basicFileInfo.BuildVersion = readString(binaryReader);
                        basicFileInfo.Format       = extractYearFromBuildVersion(basicFileInfo.BuildVersion);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LastSavePath)
                    {
                        basicFileInfo.SavedPath = readString(binaryReader);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_OpenWorksetDefault)
                    {
                        basicFileInfo.OpenWorksetDefault = binaryReader.ReadInt32();
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_IsLT)
                    {
                        basicFileInfo.IsLT = binaryReader.ReadBoolean();
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_CentralModelIdentity)
                    {
                        basicFileInfo.CentralIdentity = new ModelIdentity(new GUIDValue(new Guid(readString(binaryReader))));
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LocaleWhenSaved)
                    {
                        basicFileInfo.LocaleWhenSaved = readString(binaryReader);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_AllLocalChangesSavedToCentral)
                    {
                        basicFileInfo.AllLocalChangesSavedToCentral = binaryReader.ReadBoolean();
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LatestCentralVersionAndEpisode)
                    {
                        basicFileInfo.LatestCentralVersion     = binaryReader.ReadInt32();
                        basicFileInfo.LatestCentralEpisodeGUID = new GUIDValue(new Guid(readString(binaryReader)));
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_UniqueDocumentVersionIdentifier)
                    {
                        basicFileInfo.UniqueDocumentVersionGUID     = new GUIDValue(Guid.Parse(readString(binaryReader)));
                        basicFileInfo.UniqueDocumentVersionSequence = int.Parse(readString(binaryReader));
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_ModelIdentity)
                    {
                        basicFileInfo.Identity = new ModelIdentity(new GUIDValue(new Guid(readString(binaryReader))));
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_IsSingleUserCloudModel)
                    {
                        basicFileInfo.IsSingleUserCloudModel = binaryReader.ReadBoolean();
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_Author)
                    {
                        basicFileInfo.Author = readString(binaryReader);
                        return(basicFileInfo);
                    }
                    return(basicFileInfo);
                }
                catch (Exception ex)
                {
                    return(null);
                }
                finally
                {
                    binaryReader.Close();
                }
            }
        }
Exemple #20
0
        private void appDocOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e)
        {
            Variables.logOpenEnd      = DateTime.Now;
            Variables.logOpenDuration = Variables.logOpenEnd - Variables.logOpenStart;

            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            Document doc = e.Document;

            #region Variables: Document & Application Variables
            string path = GetUNCPath(doc.PathName);

            BasicFileInfo fileInfo = BasicFileInfo.Extract(path);
            FileInfo      f        = new FileInfo(path);

            Variables.logComputerName    = Environment.MachineName;
            Variables.logChangesSaved    = fileInfo.AllLocalChangesSavedToCentral;
            Variables.logFileCentral     = GetUNCPath(fileInfo.CentralPath);
            Variables.logFileCentralName = Path.GetFileName(Variables.logFileCentral);
            Variables.logIsCentral       = fileInfo.IsCentral;
            Variables.logIsWorkshared    = fileInfo.IsWorkshared;
            Variables.logCreatedLocal    = fileInfo.IsCreatedLocal;

            Variables.logFileName = doc.Title;
            Variables.logFilePath = GetUNCPath(doc.PathName);
            Variables.logFileSize = Convert.ToInt32(f.Length / 1000000);

            Variables.logUsername      = app.Username;
            Variables.logVersionBuild  = app.VersionBuild;
            Variables.logVersionName   = app.VersionName;
            Variables.logVersionNumber = app.VersionNumber;
            #endregion

            #region Tracking: Start Logging Pinned Elements
            IEnumerable <Element> a = TrackChanges.Command.GetTrackedElements(doc);
            _start_state = TrackChanges.Command.GetSnapshot(a);
            #endregion


            #region Settings: Load settings if they exist (Extensible Storage)
            ParameterCommands.Load(doc);
            #endregion

            #region Post: Worksharing Warning-Opened Central Model
            bool patheq = string.Equals(Variables.logFileCentral, Variables.logFilePath);

            if (Variables.slackOn && Variables.slackWSWarn)
            {
                if (patheq && Variables.logIsWorkshared)
                {
                    string gif_lg_url = null;
                    string gif_sm_url = null;

                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Alarm").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);

                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }

                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }
                    }

                    var slackClient = new SlackClient(Variables.slackToken);

                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Worksharing Warning";
                    string icon_url = Variables.icon_revit;

                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "has opened the central model",
                        color    = "danger",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Description",
                                value  = "The user has opened the central model. Close the central model and create a new local file> to work from.",
                                @short = false
                            },
                            new Fields
                            {
                                title  = "User",
                                value  = Variables.logUsername,
                                @short = true
                            },
                            new Fields
                            {
                                title  = "File",
                                value  = Variables.logFileCentralName,
                                @short = true
                            }
                        },
                        image_url = gif_lg_url,
                        thumb_url = gif_sm_url
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_ws.Add(resp.ts);
                }
            }
            #endregion

            #region Post: Model Warning-File Size > 300MB
            if (Variables.slackOn && Variables.slackModelWarn)
            {
                string gif_lg_url = null;
                string gif_sm_url = null;

                if (Variables.logFileSize > 300)
                {
                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Gasp").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);

                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }

                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }

                        var slackClient = new SlackClient(Variables.slackToken);

                        string text     = "";
                        string channel  = Variables.slackChId;
                        string botname  = "Model Warning";
                        string icon_url = Variables.icon_revit;

                        var attachments = new Attachments
                        {
                            fallback = "The file size has gone above 300MB, time to do some model file size management.",
                            color    = "danger",
                            fields   =
                                new Fields[]
                            {
                                new Fields
                                {
                                    title  = "Description",
                                    value  = "The file size is above 300MB, time to do some model maintenance",
                                    @short = false
                                },
                                new Fields
                                {
                                    title  = "File Size",
                                    value  = Variables.logFileSize.ToString() + "MB",
                                    @short = true
                                },
                                new Fields
                                {
                                    title  = "File",
                                    value  = Variables.logFileCentralName,
                                    @short = true
                                }
                            },
                            image_url = gif_lg_url,
                            thumb_url = gif_sm_url
                        };

                        string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                        var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);

                        msgts_model.Add(resp.ts);
                    }
                }
                #endregion

                #region Post: Tracking-Pinned Element-Started

                if (Variables.slackOn && Variables.slackExtraTrackPin)
                {
                    var slackClient = new SlackClient(Variables.slackToken);

                    //Post pinned elements message
                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Pinning Info";
                    string icon_url = Variables.icon_revit;


                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "has started tracking pinned elements.",
                        color    = "good",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Status",
                                value  = Variables.logUsername + " has started tracking pinned elements.\n[" + Variables.logFileCentralName + "]",
                                @short = true
                            }
                        }
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_extra.Add(resp.ts);
                }
                #endregion
            }
        }
Exemple #21
0
        private void appDocClosing(object sender, Autodesk.Revit.DB.Events.DocumentClosingEventArgs e)
        {
            BasicFileInfo fileInfo = BasicFileInfo.Extract(Variables.logFilePath);

            #region Post: Worksharing Warning-Close without saving

            if (Variables.slackOn && Variables.slackWSWarn)
            {
                if (fileInfo.AllLocalChangesSavedToCentral == false)
                {
                    string gif_lg_url = null;
                    string gif_sm_url = null;

                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Disappointed").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);
                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }
                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }
                    }
                    var slackClient = new SlackClient(Variables.slackToken);

                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Worksharing Warning";
                    string icon_url = Variables.icon_revit;

                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "did not save to central before closing",
                        color    = "danger",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Description",
                                value  = "The user has closed the model without saving their changes back to the central model. Open the model and save changes back to the central model.",
                                @short = false
                            },
                            new Fields
                            {
                                title  = "User",
                                value  = Variables.logUsername,
                                @short = true
                            },
                            new Fields
                            {
                                title  = "File",
                                value  = Variables.logFileCentralName,
                                @short = true
                            }
                        },
                        image_url = gif_lg_url,
                        thumb_url = gif_sm_url
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_ws.Add(resp.ts);
                }
            }
            #endregion
        }
 public SimpleBinaryFile(BasicFileInfo basicMetadata, byte[] content, SimpleVersion version) :
     base(basicMetadata, (offset, length) => new ReadOnlyMemory <byte>(content, (int)offset, length), version)
 {
 }
Exemple #23
0
        public void BasicFileInfo()
        {
            var bfi = new BasicFileInfo(Resources.ProjectRvt);

            Assert.IsTrue(bfi.WorksharingEnabled);
        }
        public bool UpgradeRevitProject(Document document, string revitFileName)
        {
            bool upgraded = false;

            try
            {
                BasicFileInfo     basicFileInfo     = BasicFileInfo.Extract(revitFileName);
                FileSaveAsOptions fileSaveAsOptions = projectSettings.UpgradeOptions.UpgradeVersionSaveAsOptions;

                LogFileManager.AppendLog("Upgrade Revit Project: " + revitFileName);
                LogFileManager.AppendLog("The Original Revit file was saved in " + basicFileInfo.SavedInVersion);

                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                if (basicFileInfo.IsWorkshared)
                {
                    WorksharingSaveAsOptions worksharingSaveAsOptions = new WorksharingSaveAsOptions();
                    worksharingSaveAsOptions.OpenWorksetsDefault = FindWorksetOption(fileSaveAsOptions.WorksetConfiguration);
                    worksharingSaveAsOptions.SaveAsCentral       = fileSaveAsOptions.MakeCentral;

                    saveAsOptions.MaximumBackups = fileSaveAsOptions.NumOfBackups;
                    saveAsOptions.SetWorksharingOptions(worksharingSaveAsOptions);
                }

                bool isFinalUpgrade = projectSettings.UpgradeOptions.IsFinalUpgrade;
                if (isFinalUpgrade)
                {
                    string backupDirectory = FindBackupDirectory(revitFileName);
                    if (!string.IsNullOrEmpty(backupDirectory))
                    {
                        string fileName    = Path.GetFileName(revitFileName);
                        string newFilePath = Path.Combine(backupDirectory, fileName);
                        File.Copy(revitFileName, newFilePath, true);
                        if (File.Exists(newFilePath))
                        {
                            document.SaveAs(revitFileName, saveAsOptions);
                            LogFileManager.AppendLog("Backup Saved: " + newFilePath);
                            if (fileSaveAsOptions.Relinquish)
                            {
                                RelinquishOptions roptions = new RelinquishOptions(false);
                                roptions.UserWorksets = true;
                                TransactWithCentralOptions coptions = new TransactWithCentralOptions();
                                WorksharingUtils.RelinquishOwnership(document, roptions, coptions);
                                LogFileManager.AppendLog("Relinquish all worksets created by the current user.");
                            }
                            upgraded = true;
                        }
                    }
                    else
                    {
                        LogFileManager.AppendLog("File Not Saved", "The backup directory cannot be found.");
                        upgraded = false;
                    }
                }
                else
                {
                    string reviewDirectory = FindReviewDirectory(revitFileName);
                    if (string.IsNullOrEmpty(reviewDirectory))
                    {
                        reviewDirectory = fileSaveAsOptions.ReviewLocation;
                    }
                    string fileName = Path.GetFileName(revitFileName);
                    if (!string.IsNullOrEmpty(reviewDirectory))
                    {
                        revitFileName = Path.Combine(reviewDirectory, fileName);
                        document.SaveAs(revitFileName, saveAsOptions);
                        LogFileManager.AppendLog("File Saved: " + revitFileName);
                        if (fileSaveAsOptions.Relinquish)
                        {
                            RelinquishOptions roptions = new RelinquishOptions(false);
                            roptions.UserWorksets = true;
                            TransactWithCentralOptions coptions = new TransactWithCentralOptions();
                            WorksharingUtils.RelinquishOwnership(document, roptions, coptions);
                            LogFileManager.AppendLog("Relinquish all worksets created by the current user.");
                        }
                        upgraded = true;
                    }
                    else
                    {
                        LogFileManager.AppendLog("File Not Saved", "The review directory cannot be found.");
                        upgraded = false;
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogFileManager.AppendLog("[Error] Upgrade Revit Project", message);
            }
            return(upgraded);
        }
Exemple #25
0
 protected SimpleFile(BasicFileInfo basicMetadata, Func <long, int, ReadOnlyMemory <byte> > contentFetcher, SimpleVersion version) : base(basicMetadata, version, _defaultSecurity)
 {
     _contentFetcher = contentFetcher;
 }
        public Document OpenRevitDocument(string revitFileName)
        {
            Document doc = null;

            try
            {
                LogFileManager.AppendLog("Open Revit Document: " + revitFileName);
                BasicFileInfo   basicFileInfo   = BasicFileInfo.Extract(revitFileName);
                FileOpenOptions fileOpenOptions = projectSettings.UpgradeOptions.UpgradeVersionOpenOptions;

                if (basicFileInfo.IsWorkshared)
                {
                    ModelPath   modelPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(revitFileName);
                    OpenOptions openOptions = new OpenOptions();
                    openOptions.Audit = fileOpenOptions.Audit;
                    if (fileOpenOptions.DetachAndPreserveWorksets)
                    {
                        openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                    }

                    IList <WorksetPreview> wsPreviews      = new List <WorksetPreview>();
                    IList <WorksetId>      worksetIds      = new List <WorksetId>();
                    WorksetConfiguration   wsConfiguration = new WorksetConfiguration();

                    try
                    {
                        wsPreviews = WorksharingUtils.GetUserWorksetInfo(modelPath);
                        if (wsPreviews.Count > 0)
                        {
                            foreach (WorksetPreview wsPreview in wsPreviews)
                            {
                                worksetIds.Add(wsPreview.Id);
                            }

                            if (fileOpenOptions.OpenAllWorkset)
                            {
                                wsConfiguration.Open(worksetIds);
                            }
                            else
                            {
                                wsConfiguration.Close(worksetIds);
                            }
                            openOptions.SetOpenWorksetsConfiguration(wsConfiguration);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogFileManager.AppendLog("[Warning] Open Worksets", ex.Message);
                    }
                    doc = uiApp.Application.OpenDocumentFile(modelPath, openOptions);
                }
                else
                {
                    doc = uiApp.Application.OpenDocumentFile(revitFileName);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogFileManager.AppendLog("[Error] Open Revit Document", message);
            }
            return(doc);
        }
 public SimpleBinaryFile(BasicFileInfo basicMetadata, byte[] content) : this(basicMetadata, content, 0)
 {
 }
Exemple #28
0
        protected void UpgradeFile(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            BasicFileInfo fileInfo = BasicFileInfo.Extract(modelPath);

            if (fileInfo.Format.Equals("2019"))
            {
                return;
            }

            string pathName = doc.PathName;

            string[]  pathParts = pathName.Split('\\');
            string[]  nameParts = pathParts[pathParts.Length - 1].Split('.');
            string    extension = nameParts[nameParts.Length - 1];
            string    filePath  = "revitupgrade." + extension;
            ModelPath path      = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            SaveAsOptions saveOpts = new SaveAsOptions();

            // Check for permanent preview view
            if (doc
                .GetDocumentPreviewSettings()
                .PreviewViewId
                .Equals(ElementId.InvalidElementId))
            {
                // use 3D view as preview
                View view = new FilteredElementCollector(doc)
                            .OfClass(typeof(View))
                            .Cast <View>()
                            .Where(vw =>
                                   vw.ViewType == ViewType.ThreeD && !vw.IsTemplate
                                   )
                            .FirstOrDefault();

                if (view != null)
                {
                    saveOpts.PreviewViewId = view.Id;
                }
            }
            doc.SaveAs(path, saveOpts);
        }
Exemple #29
0
        protected bool WriteToStreamFile(string basicFileInfoFilename, BasicFileInfo basicFileInfo)
        {
            bool flag = false;

            if (!File.Exists(basicFileInfoFilename))
            {
                return(false);
            }
            using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(basicFileInfoFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None), Encoding.Unicode))
            {
                try
                {
                    binaryWriter.Write((int)basicFileInfo.Version);
                    binaryWriter.Write(basicFileInfo.IsWorkshared);
                    binaryWriter.Write((byte)basicFileInfo.WorksharingState);
                    writeString(binaryWriter, basicFileInfo.Username);
                    writeString(binaryWriter, basicFileInfo.CentralPath);
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_Format)
                    {
                        writeString(binaryWriter, basicFileInfo.Format);
                        writeString(binaryWriter, basicFileInfo.BuildVersion);
                    }
                    else
                    {
                        writeString(binaryWriter, basicFileInfo.BuildVersion);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LastSavePath)
                    {
                        writeString(binaryWriter, basicFileInfo.SavedPath);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_OpenWorksetDefault)
                    {
                        binaryWriter.Write(basicFileInfo.OpenWorksetDefault);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_IsLT)
                    {
                        binaryWriter.Write(basicFileInfo.IsLT);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_CentralModelIdentity)
                    {
                        writeString(binaryWriter, basicFileInfo.CentralIdentity.IdentityGUID.GUID.ToString());
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LocaleWhenSaved)
                    {
                        writeString(binaryWriter, basicFileInfo.LocaleWhenSaved);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_AllLocalChangesSavedToCentral)
                    {
                        binaryWriter.Write(basicFileInfo.AllLocalChangesSavedToCentral);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_LatestCentralVersionAndEpisode)
                    {
                        binaryWriter.Write(basicFileInfo.LatestCentralVersion);
                        writeString(binaryWriter, basicFileInfo.LatestCentralEpisodeGUID.GUID.ToString());
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_UniqueDocumentVersionIdentifier)
                    {
                        writeString(binaryWriter, basicFileInfo.UniqueDocumentVersionGUID.GUID.ToString());
                        writeString(binaryWriter, basicFileInfo.UniqueDocumentVersionSequence.ToString());
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_ModelIdentity)
                    {
                        writeString(binaryWriter, basicFileInfo.Identity.IdentityGUID.GUID.ToString());
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_IsSingleUserCloudModel)
                    {
                        binaryWriter.Write(basicFileInfo.IsSingleUserCloudModel);
                    }
                    if (basicFileInfo.Version >= BasicFileInfoStreamVersion.BFISV_Author)
                    {
                        writeString(binaryWriter, basicFileInfo.Author);
                    }
                    binaryWriter.Write(Environment.NewLine);
                    binaryWriter.Write(basicFileInfo.ToString().ToCharArray());
                    binaryWriter.Write(Environment.NewLine);
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
                finally
                {
                    binaryWriter.Close();
                }
            }
        }