Esempio n. 1
0
        private static ViewScheduleExportOptions LoadSavedExportOptions()
        {
            var options          = new ViewScheduleExportOptions();
            var headerExportType = Settings.Default.ExportColumnHeader ? ExportColumnHeaders.OneRow : ExportColumnHeaders.None;

            if (Settings.Default.IncludeGroupedColumnHeaders)
            {
                headerExportType = ExportColumnHeaders.MultipleRows;
            }
            options.ColumnHeaders        = headerExportType;
            options.FieldDelimiter       = Settings.Default.FieldDelimiter != null ? Settings.Default.FieldDelimiter : ",";
            options.HeadersFootersBlanks = Settings.Default.ExportGrouppHeaderAndFooters;
            var textQualifier = Settings.Default.TextQualifier;

            if (textQualifier == "\"")
            {
                options.TextQualifier = ExportTextQualifier.DoubleQuote;
            }
            if (textQualifier == "\'")
            {
                options.TextQualifier = ExportTextQualifier.Quote;
            }
            if (textQualifier == string.Empty)
            {
                options.TextQualifier = ExportTextQualifier.None;
            }
            options.Title = Settings.Default.ExportTitle;
            return(options);
        }
Esempio n. 2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            #region//Utils
            //String Builder
            StringBuilder sb = new StringBuilder();

            //Collector
            Collector collector = new Collector();

            //UnitConvertor
            LengthUnitConverter converter = new LengthUnitConverter();

            // Application context.
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;
            #endregion

            #region//Check if we are in the Revit project , not in family one.
            if (doc.IsFamilyDocument)
            {
                Message.Display("Can't use command in family document", WindowType.Warning);
                return(Result.Cancelled);
            }
            #endregion

            #region//create new directory
            string append      = "schedules ";
            string pathName    = doc.PathName.ToString();
            string title       = doc.Title.ToString();
            int    titleLength = title.Length + 4;
            string newpath     = pathName.Remove(pathName.Length - titleLength, titleLength);

            string folder = newpath + append + DateTime.Now.ToString("yyyMMdd HH'u'mm'm'");
            Directory.CreateDirectory(folder);
            //sb.Append(folder);
            #endregion

            #region//ViewSchedule collector
            List <View> List_ViewSchedules = collector.GetViewSchedules(doc, ViewType.Schedule);
            //sb.Append("\n"+ List_ViewSchedules);
            #endregion

            #region//Export Options
            ViewScheduleExportOptions options = new ViewScheduleExportOptions();
            #endregion

            #region//Export Schedules
            foreach (ViewSchedule V in List_ViewSchedules)
            {
                V.Export(folder, V.Name + ".csv", options);
            }
            #endregion

            //TaskDialog.Show("TEST", sb.ToString());
            return(Result.Succeeded);
        }
        public static void ExportSchedules(Document curDoc)
        {
            int counter = 0;

            ViewScheduleExportOptions curOptions = new ViewScheduleExportOptions();

            curOptions.ColumnHeaders = ExportColumnHeaders.MultipleRows;

            //open form
            using (frmForm curForm = new frmForm(curDoc)) {
                //show form
                curForm.ShowDialog();

                if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    //Cancel pressed - do something
                    return;
                }
                else
                {
                    //check if folder path selected
                    if (!string.IsNullOrEmpty(curForm.getSelectedFolder()))
                    {
                        List <string> schedList = curForm.getSelectedSchedules();

                        //loop through each schedule and export
                        foreach (string tmpSched in schedList)
                        {
                            //get selected schedule
                            ViewSchedule curSched   = getScheduleByName(curDoc, tmpSched);
                            string       exportFile = curSched.Name + ".csv";

                            try {
                                curSched.Export(curForm.getSelectedFolder(), exportFile, curOptions);
                                counter = counter + 1;
                            } catch (Exception ex) {
                                TaskDialog.Show("Error", "Could not export schedule " + curSched.Name);
                            }
                        }
                    }
                    else
                    {
                        TaskDialog.Show("Error", "Please select an export folder path.");
                        return;
                    }
                }
            }

            //alert user
            TaskDialog.Show("Complete", "Exported " + counter + " schedules.");
        }
        private static string ExportScheduleCSV(ViewSchedule schedule, string scheduleExportDirectory)
        {
            ViewScheduleExportOptions exportOptions = new ViewScheduleExportOptions()
            {
                ColumnHeaders = ExportColumnHeaders.MultipleRows,
                Title         = false
            };

            var scheduleExportPath = Path.Combine(scheduleExportDirectory, string.Format("{0}.csv", RemoveInvalidCharacters(schedule.Name)));

            schedule.Export(scheduleExportDirectory, Path.GetFileName(scheduleExportPath), exportOptions);

            return(scheduleExportPath);
        }
Esempio n. 5
0
        private bool ExportViewSchedule(ViewSchedule viewSchedule)
        {
            var result = false;

            try
            {
                var options = new ViewScheduleExportOptions
                {
                    ColumnHeaders = ExportColumnHeaders.OneRow,
                    Title         = false
                };

                var centralPath = GetCentralPath(m_doc);
                if (!string.IsNullOrEmpty(centralPath))
                {
                    var directoryName = Path.GetDirectoryName(centralPath);
                    using (var trans = new Transaction(m_doc))
                    {
                        try
                        {
                            trans.Start("Export Schedule");
                            if (directoryName != null)
                            {
                                TextFilePath = Path.Combine(directoryName, viewSchedule.Name + extension);
                                if (File.Exists(TextFilePath))
                                {
                                    File.Delete(TextFilePath);
                                }
                                viewSchedule.Export(directoryName, viewSchedule.Name + extension, options);
                            }
                            trans.Commit();
                        }
                        catch { trans.RollBack(); }
                    }
                }

                if (File.Exists(TextFilePath))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
                result = false;
            }
            return(result);
        }
Esempio n. 6
0
 public bool Export(ViewScheduleExportOptions options, string exportPath)
 {
     if (!System.IO.Directory.Exists(exportPath))
     {
         return(false);
     }
     try
     {
         RevitViewSchedule.Export(exportPath, ExportName, options);
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Esempio n. 7
0
        public void createGrossSchedule(String name, String fileName, Document doc)
        {
            ViewSchedule schedule         = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)).Where(x => x.Name == name + " Schedule").FirstOrDefault() as ViewSchedule;
            ViewScheduleExportOptions opt = new ViewScheduleExportOptions();

            opt.FieldDelimiter = ",";
            opt.Title          = false;
            string path = _export_folder_name;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string file = System.IO.Path.GetFileNameWithoutExtension(fileName) + ".csv";

            schedule.Export(path, file, opt);
        }
Esempio n. 8
0
        public void SOL1ScheduleExport()
        {
            var    doc           = this.ActiveUIDocument.Document;
            var    app           = doc.Application;
            string scheduleNames = String.Empty;

            var folder_env  = @"%USERPROFILE%\OneDrive - TTP AG\08_Testing\RTV-BAY_SOL1_Schedule_Export\Schedule Exports";
            var folder_path = Environment.ExpandEnvironmentVariables(folder_env);
            var _ext        = ".txt";
            var opt         = new ViewScheduleExportOptions();

            opt.HeadersFootersBlanks = false;
            opt.Title = true;

            var toExport = new List <string>()
            {
                "BAY_AKZ-Check_List_Doors",
                "BAY_AKZ-Check_List_General",
                "BAY_AKZ-Check_List_Windows",
                "BAY_Overview-Clean_Room_Classification",
                "BAY_Room Schedule Detailed",
                "SOL1_Raumbuch_DatenMaster",
                "SOL1_Tuerliste_DatenMaster"
            };

            var vsCol = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule));

            foreach (ViewSchedule vs in vsCol)
            {
                if (toExport.Contains(vs.Name))
                {
                    vs.Export(folder_path, vs.Name + _ext, opt);
                }
            }

//			var td = new TaskDialog("Info");
//			td.MainInstruction = "View Schedule in project:";
//			td.MainContent = scheduleNames;
//			td.Show();
        }
Esempio n. 9
0
        } = 0;                                                      // number of schedules exported
        #endregion

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // add event handler for when the app does not find the ArpUtilies.dll assembly
            //AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            #region variables
            UIApplication uiapp = commandData.Application;
            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // element selection
            ICollection <ElementId> selIds = uidoc.Selection.GetElementIds();

            // excel export settings
            ViewScheduleExportOptions export_options = new ViewScheduleExportOptions();

            // paths to check Excel install
            string excelPaths_FileName = "OpenInExcel_UserPaths.txt";
            string assemblyPath        = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string excelPaths_FilePath = Path.Combine(assemblyPath, excelPaths_FileName);

            // paths to export schedule
            string temp_folder = Path.GetTempPath();
            #endregion

            // check if file exists
            if (!Data.Helpers.CheckFileExists(excelPaths_FilePath))
            {
                warningMsgMain = "File missing";
                warningMsgBody = string.Format("Could not find the File: {0}{0}{1} in {2}{0}{0}Contact [email protected] for help.",
                                               Environment.NewLine,
                                               excelPaths_FileName,
                                               assemblyPath);
                using (UI.Info.Form_Warning thisForm = new UI.Info.Form_Warning())
                {
                    thisForm.ShowDialog();
                }
                return(Result.Cancelled);
            }

            // check if excel is installed in usual paths
            if (!Data.Helpers.CheckExcelInstall(excelPaths_FilePath))
            {
                warningMsgMain = "Excel not found";
                warningMsgBody = string.Format("Could not find Excel installed in the usual paths.{0}{0}" +
                                               "Please install Excel or add your Excel path to the OpenInExcel_UserPaths.txt " +
                                               "(located in {1}) and try again.{0}{0}" +
                                               "Contact [email protected] for help.", Environment.NewLine, assemblyPath);

                using (UI.Info.Form_Warning thisForm = new UI.Info.Form_Warning())
                {
                    thisForm.ShowDialog();
                }
                return(Result.Cancelled);
            }

            // if there are not schedules selected or open throw a message
            if (!Data.Helpers.GetSelectedSchedules(doc, selIds).Any())
            {
                using (UI.Info.Form_Info1 thisForm = new UI.Info.Form_Info1())
                {
                    thisForm.ShowDialog();
                }
                return(Result.Cancelled);
            }

            // go ahead and export the selected schedules
            if (Data.Helpers.GetSelectedSchedules(doc, selIds).Any())
            {
                // start counters. For this application Use Time and Execution time will be the same.
                useTime.Start();

                Random randomNumber = new Random();

                // create excel name with schedule name + random number
                foreach (View v in Data.Helpers.GetSelectedSchedules(doc, selIds))
                {
                    Ana_NoOfExports += 1;   // count number of schedules exported

                    string scheduleName       = Data.Helpers.ReplaceIllegalCharaters(v.Name);
                    string txtFileName        = scheduleName + "_" + randomNumber.Next(1000) + ".txt";
                    string scheduleExportPath = Path.Combine(temp_folder, txtFileName);

                    // export schedule to .txt
                    ViewSchedule viewSchedule = v as ViewSchedule;
                    viewSchedule.Export(temp_folder, txtFileName, export_options);

                    // open .txt schedule with excel
                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                    excelApp.Visible = true; // make the running excel instance visible
                    Workbook wb = excelApp.Workbooks.Open(scheduleExportPath);
                }
                useTime.Stop();
                UseTimeElapseS  = useTime.Elapsed.Seconds.ToString();
                ExecTimeElapseS = UseTimeElapseS;
            }
            //try
            //{
            //    Utilities.GetAnalyticsCSV(doc, app);
            //    Data.Helpers.ScheduleToExcelAnalytics(doc, app, UseTimeElapseS, ExecTimeElapseS, Ana_NoOfExports);
            //}
            //catch (Exception)
            //{
            //}
            return(Result.Succeeded);
        }
Esempio n. 10
0
        public void createCountSchedule(String name, ElementId elementId)
        {
            ViewSchedule schedule = new FilteredElementCollector(CachedDoc).OfClass(typeof(ViewSchedule)).Where(x => x.Name == name + " Schedule").FirstOrDefault() as ViewSchedule;

            if (schedule == null)
            {
                Transaction tSchedule = new Transaction(CachedDoc, "Create Schedule");
                tSchedule.Start();

                //Create an empty view schedule for doors.
                //schedule = ViewSchedule.CreateSchedule(CachedDoc, new ElementId(BuiltInCategory.INVALID), ElementId.InvalidElementId);
                schedule      = ViewSchedule.CreateSchedule(CachedDoc, elementId, ElementId.InvalidElementId);
                schedule.Name = name + " Schedule";

                ElementId keynoteId = new ElementId(BuiltInParameter.KEYNOTE_PARAM);
                //Iterate all the schedulable fields gotten from the doors view schedule.
                foreach (SchedulableField schedulableField in schedule.Definition.GetSchedulableFields())
                {
                    //See if the FieldType is ScheduleFieldType.Instance.
                    if (schedulableField.FieldType == ScheduleFieldType.Count || schedulableField.ParameterId == keynoteId)
                    {
                        //Get ParameterId of SchedulableField.
                        ElementId parameterId = schedulableField.ParameterId;

                        //Add a new schedule field to the view schedule by using the SchedulableField as argument of AddField method of Autodesk.Revit.DB.ScheduleDefinition class.
                        ScheduleField field = schedule.Definition.AddField(schedulableField);

                        //See if the parameterId is a BuiltInParameter.
                        if (Enum.IsDefined(typeof(BuiltInParameter), parameterId.IntegerValue))
                        {
                            BuiltInParameter bip = (BuiltInParameter)parameterId.IntegerValue;
                            //Get the StorageType of BuiltInParameter.
                            Autodesk.Revit.DB.StorageType st = CachedDoc.get_TypeOfStorage(bip);
                            //if StorageType is String or ElementId, set GridColumnWidth of schedule field to three times of current GridColumnWidth.
                            //And set HorizontalAlignment property to left.
                            if (st == Autodesk.Revit.DB.StorageType.String || st == Autodesk.Revit.DB.StorageType.ElementId)
                            {
                                field.GridColumnWidth     = 3 * field.GridColumnWidth;
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Left;
                            }
                            //For other StorageTypes, set HorizontalAlignment property to center.
                            else
                            {
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Center;
                            }
                        }

                        if (field.ParameterId == keynoteId)
                        {
                            ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                            schedule.Definition.AddSortGroupField(sortGroupField);
                            schedule.Definition.IsItemized = false;
                        }
                        if (schedulableField.FieldType == ScheduleFieldType.Count)
                        {
                        }
                    }
                }


                tSchedule.Commit();
                tSchedule.Dispose();
            }
            else
            {
                schedule.RefreshData();
            }

            ViewScheduleExportOptions opt = new ViewScheduleExportOptions();

            opt.FieldDelimiter = ",";
            opt.Title          = false;

            string path = _export_folder_name;


            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }


            string file = System.IO.Path.GetFileNameWithoutExtension(name) + ".csv";

            schedule.Export(path, file, opt);
        }
Esempio n. 11
0
        public void createMaterialTakeOffSchedule(String name, ElementId elementId)
        {
            //Get UIDocument
            UIDocument uidoc = _cachedCmdData.Application.ActiveUIDocument;
            //Get Document
            Document doc = uidoc.Document;

            ViewSchedule schedule = new FilteredElementCollector(CachedDoc).OfClass(typeof(ViewSchedule)).Where(x => x.Name == name + " Schedule").FirstOrDefault() as ViewSchedule;

            if (schedule == null)
            {
                Transaction tSchedule = new Transaction(CachedDoc, "Create Schedule");
                tSchedule.Start();

                //Create an empty view schedule for doors.
                schedule      = ViewSchedule.CreateMaterialTakeoff(CachedDoc, elementId);
                schedule.Name = name + " Schedule";

                ElementId volumeId = new ElementId(BuiltInParameter.MATERIAL_VOLUME);
                ElementId areaId   = new ElementId(BuiltInParameter.MATERIAL_AREA);
                //Iterate all the schedulable fields gotten from the doors view schedule.
                foreach (SchedulableField schedulableField in schedule.Definition.GetSchedulableFields())
                {
                    //See if the FieldType is ScheduleFieldType.Instance.
                    if (schedulableField.ParameterId == volumeId || schedulableField.ParameterId == areaId || schedulableField.GetName(doc).Equals("Material: Keynote"))
                    {
                        //Get ParameterId of SchedulableField.
                        ElementId parameterId = schedulableField.ParameterId;

                        //Add a new schedule field to the view schedule by using the SchedulableField as argument of AddField method of Autodesk.Revit.DB.ScheduleDefinition class.
                        ScheduleField field = schedule.Definition.AddField(schedulableField);

                        //See if the parameterId is a BuiltInParameter.
                        if (Enum.IsDefined(typeof(BuiltInParameter), parameterId.IntegerValue))
                        {
                            BuiltInParameter bip = (BuiltInParameter)parameterId.IntegerValue;
                            //Get the StorageType of BuiltInParameter.
                            Autodesk.Revit.DB.StorageType st = CachedDoc.get_TypeOfStorage(bip);
                            //if StorageType is String or ElementId, set GridColumnWidth of schedule field to three times of current GridColumnWidth.
                            //And set HorizontalAlignment property to left.
                            if (st == Autodesk.Revit.DB.StorageType.String || st == Autodesk.Revit.DB.StorageType.ElementId)
                            {
                                field.GridColumnWidth     = 3 * field.GridColumnWidth;
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Left;
                            }
                            //For other StorageTypes, set HorizontalAlignment property to center.
                            else
                            {
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Center;
                            }
                        }

                        if (schedulableField.GetName(doc).Equals("Material: Keynote"))
                        {
                            ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                            schedule.Definition.AddSortGroupField(sortGroupField);
                            schedule.Definition.IsItemized = false;
                        }

                        if (field.ParameterId == volumeId)
                        {
                            FormatOptions formatOpt = new FormatOptions(DisplayUnitType.DUT_CUBIC_FEET, UnitSymbolType.UST_CF, 0.01);
                            formatOpt.UseDefault = false;
                            field.SetFormatOptions(formatOpt);
                            field.DisplayType = ScheduleFieldDisplayType.Totals;
                        }

                        if (field.ParameterId == areaId)
                        {
                            FormatOptions formatOpt = new FormatOptions(DisplayUnitType.DUT_SQUARE_FEET, UnitSymbolType.UST_SF, 0.01);
                            formatOpt.UseDefault = false;
                            field.SetFormatOptions(formatOpt);
                            field.DisplayType = ScheduleFieldDisplayType.Totals;
                        }
                    }
                }


                tSchedule.Commit();
                tSchedule.Dispose();
            }
            else
            {
                schedule.RefreshData();
            }

            ViewScheduleExportOptions opt = new ViewScheduleExportOptions();

            opt.FieldDelimiter = ",";
            opt.Title          = false;

            string path = _export_folder_name;


            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }


            string file = System.IO.Path.GetFileNameWithoutExtension(name) + ".csv";

            schedule.Export(path, file, opt);
        }
Esempio n. 12
0
        /// <summary>
        /// The Execute
        /// </summary>
        /// <param name="commandData">The commandData<see cref="ExternalCommandData"/></param>
        /// <param name="message">The message<see cref="string"/></param>
        /// <param name="elements">The elements<see cref="ElementSet"/></param>
        /// <returns>The <see cref="Result"/></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiapp = commandData.Application;
            var uidoc = uiapp.ActiveUIDocument;
            var doc   = uidoc.Document;

            /*
             *
             *
             * Selection selection = uidoc.Selection;
             * ICollection<ElementId> selectedIds = uidoc.Selection.GetElementIds();
             * string xx = "";
             * ICollection<Element> col = new FilteredElementCollector(doc).OfClass(typeof(Wall)).ToElements();
             * foreach (Element e in col)
             * {
             *
             *  foreach (Parameter para in e.GetOrderedParameters())
             *  {
             *
             *      if (para.IsShared == true)
             *      {
             *          var xxx = doc.GetElement(para.Id);
             *          var sharedParameterElement = doc.GetElement(para.Id) as SharedParameterElement;
             *          xx += sharedParameterElement.Name + " : " + sharedParameterElement.GetDefinition().Visible.ToString() + "\n";
             *
             *      }
             *  }
             * }
             * TaskDialog.Show("revit", xx);
             *
             */



            //* Set time out
            //https://stackoverflow.com/questions/48968193/restsharp-the-operation-has-timed-out/49677943
            //https://stackoverflow.com/questions/46584175/restsharp-timeout-not-working

            /* RevitElementRoute route = new RevitElementRoute(ProjectProvider.Ins.CurrentProject._id);
             * RestRequest req = new RestRequest(route.url(), Method.POST);
             * req.AddHeader("Content-Type", "application/json");
             * req.AddHeader("Authorization", "Bearer " + TokenUser.token.token);
             *
             * string body = JsonConvert.SerializeObject(RevitElementList.InModel.Values);
             * req.RequestFormat = DataFormat.Json;
             *
             * req.AddJsonBody(body);
             *
             * Route.Client.Timeout = Int32.MaxValue;
             * IRestResponse res = Route.Client.Execute(req);
             * if (res.StatusCode.ToString() == "OK")
             * {
             *    TaskDialog.Show("Success", "Operation is finished");
             *   return Result.Succeeded;
             * }
             *
             * if (res.ErrorException != null)
             * {
             *   string messagex = "Opps! There has been an error while uploading your model. " + res.ErrorException.Message;
             *   throw new Exception(messagex);
             * }
             */

            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ViewSchedule));

            ViewScheduleExportOptions opt = new ViewScheduleExportOptions();
            string path  = Path.GetTempPath();
            string name  = "";
            string namex = "";

            foreach (ViewSchedule vs in col)
            {
                name  = vs.Name + ".txt";
                namex = vs.Name;
                vs.Export(path, name, opt);
                break;
            }

            string filename = Path.Combine(path, name);

            ProjectManagement.Utils.RevitUtils.ScheduleUtil.ScheduleDataParser parser = new ProjectManagement.Utils.RevitUtils.ScheduleUtil.ScheduleDataParser(filename);
            var table = parser.Table;



            List <string> list = new List <string>();

            for (int i = 1; i < parser.Table.Rows.Count; i++)
            {
                string itemChild = "";
                string item      = "";
                for (int j = 0; j < parser.Table.Columns.Count; j++)
                {
                    if (j != parser.Table.Columns.Count - 1)
                    {
                        itemChild += "\"" + parser.Table.Columns[j].ColumnName + "\":\"" + parser.Table.Rows[i][j] + "\",";
                    }
                    else
                    {
                        itemChild += "\"" + parser.Table.Columns[j].ColumnName + "\":\"" + parser.Table.Rows[i][j] + "\"";
                    }
                }
                item = "{" + itemChild + "}";
                list.Add(item);
            }
            string bodychild = "[";

            for (int i = 0; i < list.Count; i++)
            {
                if (i != list.Count - 1)
                {
                    bodychild += list[i] + ",";
                }
                else
                {
                    bodychild += list[i] + "]";
                }
            }
            string body = "{\"name\":\"" + namex + "\",\"" + "isShared\":\"true\"," + "\"data\":" + bodychild + "}";

            string      url = string.Format("{0}/{1}/schedules", Route.UserProjects, ProjectProvider.Instance.CurrentProject._id);
            RestRequest req = new RestRequest(url, Method.POST);

            req.AddHeader("Content-Type", "application/json");
            req.AddHeader("Authorization", "Bearer " + AuthProvider.Instance.token.token);
            req.RequestFormat = DataFormat.Json;
            req.AddJsonBody(body);
            IRestResponse res = Route.Client.Execute(req);

            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
            File.Delete(@filename);

            return(Result.Succeeded);
        }
Esempio n. 13
0
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_viewModel.ExportExcelFolderPath))
            {
                _viewModel.ExportExcelFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            #region Code

            List <ViewScheduleExtension> viewScheduleExport = new List <ViewScheduleExtension>();
            foreach (ViewScheduleExtension viewSchedule in _viewModel.AllViewSchedules)
            {
                if (viewSchedule.IsExport)
                {
                    viewScheduleExport.Add(viewSchedule);
                }
            }

            if (viewScheduleExport.Count == 0)
            {
                MessageBox.Show("Please select the Schedules which will be exported!");
                return;
            }

            if (_viewModel.IsMultiWorkbooks)
            {
                foreach (var vse in viewScheduleExport)
                {
                    ViewSchedule selectedSchedule = vse.ViewSchedule;
                    string       filePath         = Path.Combine(_viewModel.ExportExcelFolderPath, selectedSchedule.Name + ".xlsx");

                    try
                    {
                        string filePathTxt = Path.Combine(_viewModel.ExportExcelFolderPath,
                                                          string.Concat(selectedSchedule.Name, ".txt"));

                        List <string> scheduleExportFieldName = selectedSchedule.GetNameOfFields();

                        ViewScheduleExportOptions viewScheduleExportOption = new ViewScheduleExportOptions();
                        selectedSchedule.Export(_viewModel.ExportExcelFolderPath, Path.GetFileName(filePathTxt),
                                                viewScheduleExportOption);

                        DataTable dataTable = ExcelUtils.ReadFile(filePathTxt, scheduleExportFieldName.Count);

                        FileInfo existingFile = new FileInfo(filePath);
                        using (var package = new ExcelPackage(existingFile))
                        {
                            ExcelUtils.ExportDataTableToExcel(package, dataTable,
                                                              selectedSchedule.Name, filePath);
                        }

                        File.Delete(filePathTxt);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else
            {
                string title = _viewModel.Doc.Title;
                title = title.Substring(0, title.Length - 4);
                string filePath = Path.Combine(_viewModel.ExportExcelFolderPath,
                                               string.Concat(title, ".xlsx"));
                FileInfo existingFile = new FileInfo(filePath);
                using (var package = new ExcelPackage(existingFile))
                {
                    foreach (var vse in viewScheduleExport)
                    {
                        ViewSchedule selectedSchedule = vse.ViewSchedule;
                        try
                        {
                            string filePathTxt = Path.Combine(_viewModel.ExportExcelFolderPath,
                                                              string.Concat(selectedSchedule.Name, ".txt"));

                            List <string> scheduleExportFieldName = selectedSchedule.GetNameOfFields();

                            ViewScheduleExportOptions viewScheduleExportOption = new ViewScheduleExportOptions();
                            selectedSchedule.Export(_viewModel.ExportExcelFolderPath, Path.GetFileName(filePathTxt),
                                                    viewScheduleExportOption);

                            DataTable dataTable = ExcelUtils.ReadFile(filePathTxt, scheduleExportFieldName.Count);

                            ExcelUtils.ExportDataTableToExcel(package, dataTable,
                                                              selectedSchedule.Name, filePath);

                            File.Delete(filePathTxt);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            if (MessageBox.Show("Do you want to open folder that store exported files?", "Open folder",
                                MessageBoxButton.YesNo)
                == MessageBoxResult.Yes)
            {
                try
                {
                    Process.Start(_viewModel.ExportExcelFolderPath);
                }
                catch (Exception)
                {
                }
            }

            #endregion

            DialogResult = true;
            Close();
        }
Esempio n. 14
0
        private void CreateTable(string _tableName)
        {
            tableIsBeingFiltered = false;
            FilteredElementCollector vsCol;

            vsCol = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule));

            ViewScheduleExportOptions vsOpt;

            vsOpt = new ViewScheduleExportOptions();

            vsOpt.Title = false;
            vsOpt.HeadersFootersBlanks = false;
            vsOpt.FieldDelimiter       = ",";

            string dir = "";

            dir = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string fileName = "";

            fileName = _tableName + ".txt";

            string file = "";

            file = dir + @"\" + fileName;

            //iterate through all the ViewSchedules until you get the selected one
            foreach (ViewSchedule vs in vsCol)
            {
                if (vs.ViewName == _tableName)
                {
                    vs.Export(dir, fileName, vsOpt); //export the ViewSchedule to MyDocuments
                }
            }

            //read from the file that was just exported above
            //read only the first line
            //the first line contains the fields to create in the database table
            System.IO.StreamReader sr = new System.IO.StreamReader(file);

            string entry = "";

            entry = sr.ReadLine();

            char[]   cs = new char[] { ',' };
            string[] ar = entry.Split(cs, StringSplitOptions.None);

            string curParam   = "";
            int    curArIndex = 0;

            //create a string builder to dynamically create an sql query string
            StringBuilder commandText = new StringBuilder();

            commandText.Append("CREATE TABLE " + _tableName + " (");
            commandText.Append("ID int PRIMARY KEY IDENTITY,");
            commandText.Append("ElementId varchar(MAX),");

            //interate through all the parameter names in the ar array
            //append them to the string builder
            do
            {
                curParam = ar[curArIndex];
                curParam = curParam.Replace(@"""", "");

                if (curArIndex < ar.Length - 1)
                {
                    commandText.Append(curParam + " varchar(MAX),");
                }
                else if (curArIndex == ar.Length - 1)
                {
                    commandText.Append(curParam + " varchar(MAX));");
                }

                curArIndex++;
            } while (curArIndex <= ar.Length - 1);

            //connect to the database and create the table
            con.Open();
            SqlCommand command = new SqlCommand();

            command.Connection  = con;
            command.CommandType = CommandType.Text;
            command.CommandText = commandText.ToString();
            command.ExecuteNonQuery();
            con.Close();

            LoadTable(_tableName);
            LoadElements(_tableName);
        }