Exemplo n.º 1
0
        public static new void Parse(XNode node, DefinitionFile file)
        {
            UiView.Parse(node, file);

            var parser = new DefinitionParser(node);

            file["AutomataGrid"] = parser.ParseDelegate("AutomataGrid");
            file["EditEnabled"] = parser.ParseBoolean("EditEnabled");

            file["Zoom"] = parser.ParseDouble("Zoom");
            file["StateToPaint"] = parser.ParseInt("StateToPaint");

            file["Colors"] = parser.ParseDelegate("Colors");

            file["GridColor"] = parser.ParseColor("GridColor");
        }
        public bool CreateAndBindParam( DefinitionFile myDefinitionFile, Category cat, string paramName)
        {
            var myGroup = myDefinitionFile.Groups.get_Item("PsParameters");
            if (myGroup == null)
                myGroup = myDefinitionFile.Groups.Create("PsParameters");

            Definition myDefinition = myGroup.Definitions.Create(paramName, ParameterType.Text, true);

            CategorySet myCategories = Application.Create.NewCategorySet();
            myCategories.Insert(cat);

            TypeBinding typeBinding = Application.Create.NewTypeBinding(myCategories);

            BindingMap bindingMap = m_revitDoc.Document.ParameterBindings;

            bool typeBindOK = bindingMap.Insert(myDefinition, typeBinding, BuiltInParameterGroup.PG_GENERAL);
            return typeBindOK;
        }
Exemplo n.º 3
0
        public static DefinitionGroup GetOrCreateSharedParamsGroup(DefinitionFile sharedParametersFile, string groupName)
        {
            DefinitionGroups gs = sharedParametersFile.Groups;

            DefinitionGroup g = gs.get_Item(groupName);

            if (null == g)
            {
                try
                {
                    g = gs.Create(groupName);
                }
                catch (Exception e)
                {
                    string message = "Error binding shared parameter: " + e.Message;

                    TaskDialog.Show("Exception", message);
                }
            }

            return g;
        }
Exemplo n.º 4
0
 public new static void Parse(XNode node, DefinitionFile file)
 {
     Text.Parse(node, file);
 }
Exemplo n.º 5
0
 bool IDefinitionClass.Init(UiController controller, object binding, DefinitionFile file)
 {
     return(Init(controller, binding, file));
 }
Exemplo n.º 6
0
        protected virtual bool Init(object controller, object binding, DefinitionFile definition)
        {
            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(UiView));

            Type controllerType = file["Controller"] as Type;

            _controller = controller as UiController;

            if (controllerType != null)
            {
                var newController = Activator.CreateInstance(controllerType) as UiController;

                if (newController != null)
                {
                    newController.Parent = _controller;
                    Controller           = newController;
                }
            }

            Binding = binding;

            object bindParameter = file["Binding"];

            if (bindParameter != null)
            {
                Object bind = DefinitionResolver.GetValueFromMethodOrField(Controller, binding, bindParameter);

                if (bind != null)
                {
                    Binding = bind;
                }
            }

            Id = DefinitionResolver.GetString(Controller, Binding, file["Id"]);

            if (file["Hidden"] != null && file["Visible"] == null)
            {
                _visiblityFlag   = DefinitionResolver.GetShared <bool>(Controller, Binding, file["Hidden"], false);
                _visibleIsHidden = true;
            }
            else
            {
                _visiblityFlag = DefinitionResolver.GetShared <bool>(Controller, Binding, file["Visible"], true);
            }

            Tag = DefinitionResolver.GetSharedString(Controller, Binding, file["Tag"]);

            Opacity = DefinitionResolver.GetShared <double>(Controller, Binding, file["Opacity"], 1);

            DisplayVisibility = Visible ? 1 : 0;

            _modal = DefinitionResolver.Get <bool>(Controller, Binding, file["Modal"], false);

            RegisterDelegate("ViewRemoved", file["ViewRemoved"]);
            RegisterDelegate("ViewAdded", file["ViewAdded"]);
            RegisterDelegate("ViewActivated", file["ViewActivated"]);
            RegisterDelegate("ViewDeactivated", file["ViewDeactivated"]);
            RegisterDelegate("ViewResized", file["ViewResized"]);

            _minWidth  = DefinitionResolver.Get <Length>(Controller, Binding, file["MinWidth"], Length.Zero);
            _minHeight = DefinitionResolver.Get <Length>(Controller, Binding, file["MinHeight"], Length.Zero);

            _showSpeed = (float)Math.Max(
                DefinitionResolver.Get <double>(Controller, Binding, file["ShowHideTime"], -1),
                DefinitionResolver.Get <double>(Controller, Binding, file["ShowTime"], -1));

            if (_showSpeed < 0)
            {
                _showSpeed = DefaultShowTime;
            }

            _showSpeed /= 1000.0f;

            _showSpeed = _showSpeed > 0 ? 1 / _showSpeed : float.MaxValue;

            _hideSpeed = (float)Math.Max(
                DefinitionResolver.Get <double>(Controller, Binding, file["ShowHideTime"], -1),
                DefinitionResolver.Get <double>(Controller, Binding, file["HideTime"], -1));

            if (_hideSpeed < 0)
            {
                _hideSpeed = DefaultHideTime;
            }

            _hideSpeed /= 1000.0f;

            _hideSpeed = _hideSpeed > 0 ? 1 / _hideSpeed : float.MaxValue;

            CreatePositionParameters(Controller, Binding, definition);

            DefinitionFile backgroundDrawable = file["BackgroundDrawable"] as DefinitionFile;

            Color defaultBackgroundColor = Color.Transparent;

            if (backgroundDrawable != null)
            {
                BackgroundDrawable = backgroundDrawable.CreateInstance(Controller, Binding) as IBackgroundDrawable;

                if (BackgroundDrawable != null)
                {
                    defaultBackgroundColor = Color.White;
                }
            }

            _backgroundColor = DefinitionResolver.GetColorWrapper(Controller, Binding, file["BackgroundColor"]) ?? new ColorWrapper(defaultBackgroundColor);

            DefinitionFile showTransitionEffectFile       = file["ShowTransitionEffect"] as DefinitionFile;
            DefinitionFile hideTransitionEffectFile       = file["HideTransitionEffect"] as DefinitionFile;
            DefinitionFile parentShowTransitionEffectFile = file["ParentShowTransitionEffect"] as DefinitionFile;
            DefinitionFile parentHideTransitionEffectFile = file["ParentHideTransitionEffect"] as DefinitionFile;

            if (showTransitionEffectFile != null)
            {
                _showTransitionEffect = showTransitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            if (hideTransitionEffectFile != null)
            {
                _hideTransitionEffect = hideTransitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            if (parentShowTransitionEffectFile != null)
            {
                _parentShowTransitionEffect = parentShowTransitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            if (parentHideTransitionEffectFile != null)
            {
                _parentHideTransitionEffect = parentHideTransitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// The information from a definition file is added to the datagrid and possibly to the combo box.
        /// 
        /// An excpetion is thrown when retrieving details for the definition file fails.
        /// </summary>
        /// <param name="theDefinitionFullFileName">the full file name of the definition file.</param>
        private void AddSopClassToDataGridFromDefinitionFile(string theDefinitionFullFileName)
        {
            DvtkApplicationLayer.Session theSession = GetSessionTreeViewManager().GetSession();
            Dvtk.Sessions.DefinitionFileDetails theDefinitionFileDetails;

            // Try to get detailed information about this definition file.
            theDefinitionFileDetails = theSession.Implementation.DefinitionManagement.GetDefinitionFileDetails(theDefinitionFullFileName);

            // No excpetion thrown when calling GetDefinitionFileDetails (otherwise this statement would not have been reached)
            // so this is a valid definition file. Add it to the data frid.
            DefinitionFile theDataGridDefinitionFileInfo =
                new DefinitionFile(IsDefinitionFileLoaded(theDefinitionFullFileName),
                System.IO.Path.GetFileName(theDefinitionFullFileName),
                theDefinitionFileDetails.SOPClassName,
                theDefinitionFileDetails.SOPClassUID,
                theDefinitionFileDetails.ApplicationEntityName,
                theDefinitionFileDetails.ApplicationEntityVersion,
                System.IO.Path.GetDirectoryName(theDefinitionFullFileName));

            if(!theDefinitionFullFileName.Contains("AllDimseCommands.def"))
                _DefinitionFilesInfoForDataGrid.Add(theDataGridDefinitionFileInfo);

            // If the AE title - version does not yet exist in the combo box, add it.
            bool IsAeTitleVersionAlreadyInComboBox = false;

            foreach (AeTitleVersion theAeTitleVersion in _ComboBoxAeTitle.Items)
            {
                if ( (theAeTitleVersion._AeTitle == theDefinitionFileDetails.ApplicationEntityName) &&
                    (theAeTitleVersion._Version == theDefinitionFileDetails.ApplicationEntityVersion) )
                {
                    IsAeTitleVersionAlreadyInComboBox = true;
                    break;
                }
            }

            if (!IsAeTitleVersionAlreadyInComboBox)
            {
                AeTitleVersion theAeTitleVersion = new AeTitleVersion(theDefinitionFileDetails.ApplicationEntityName, theDefinitionFileDetails.ApplicationEntityVersion);
                _ComboBoxAeTitle.Items.Add(theAeTitleVersion);
            }
        }
        public static void SetSharedParamFileInUserProgramFolder(Document rvtDocument)
        {
            string appTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "4Projects", "SharedParameterFiles");
            if (!Directory.Exists(appTempPath)) Directory.CreateDirectory(appTempPath);
            string sharedParameterFile = Path.Combine(appTempPath, "4P_shared_parameters.txt");

            //set shared parameter file
            rvtDocument.Application.SharedParametersFilename = sharedParameterFile;
            _definitionFile = rvtDocument.Application.GetSharedParamDefinitionFile(sharedParameterFile);
        }
Exemplo n.º 9
0
      /// <summary>
      /// load family parameters from the text file
      /// </summary>
      /// <param name="exist">
      /// indicate whether the shared parameter file exists
      /// </param>
      /// <returns>
      /// return true if succeeded; otherwise false
      /// </returns>
      private bool LoadSharedParameterFromFile(out bool exist)
      {
         exist = true;
         string filePath = m_assemblyPath + "\\SharedParameter.txt";
         if (!File.Exists(filePath))
         {
            exist = false;
            return true;
         }

         m_app.SharedParametersFilename = filePath;
         try
         {
            m_sharedFile = m_app.OpenSharedParameterFile();
         }
         catch (System.Exception e)
         {
            MessageManager.MessageBuff.AppendLine(e.Message);
            return false;
         }

         return true;
      }
Exemplo n.º 10
0
        /// <summary>
        /// Add shared parameters needed in this sample.
        /// parameter 1: one string parameter named as "BasalOpening" which  is used for customization of door opening for each country.
        /// parameter 2: one string parameter named as "InstanceOpening" to indicate the door's opening value.
        /// parameter 3: one YESNO parameter named as "Internal Door" to flag the door is internal door or not.
        /// </summary>
        /// <param name="app">Revit application.</param>
        public static void AddSharedParameters(UIApplication app)
        {
            // Create a new Binding object with the categories to which the parameter will be bound.
            CategorySet categories = app.Application.Create.NewCategorySet();

            // get door category and insert into the CategorySet.
            Category doorCategory = app.ActiveUIDocument.Document.Settings.Categories.
                                    get_Item(BuiltInCategory.OST_Doors);

            categories.Insert(doorCategory);

            // create one instance binding for "Internal Door" and "InstanceOpening" parameters;
            // and one type binding for "BasalOpening" parameters
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(categories);
            TypeBinding     typeBinding     = app.Application.Create.NewTypeBinding(categories);
            BindingMap      bindingMap      = app.ActiveUIDocument.Document.ParameterBindings;

            // Open the shared parameters file
            // via the private method AccessOrCreateSharedParameterFile
            DefinitionFile defFile = AccessOrCreateSharedParameterFile(app.Application);

            if (null == defFile)
            {
                return;
            }

            // Access an existing or create a new group in the shared parameters file
            DefinitionGroups defGroups = defFile.Groups;
            DefinitionGroup  defGroup  = defGroups.get_Item("DoorProjectSharedParameters");

            if (null == defGroup)
            {
                defGroup = defGroups.Create("DoorProjectSharedParameters");
            }

            // Access an existing or create a new external parameter definition belongs to a specific group.

            // for "BasalOpening"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "BasalOpening", BuiltInCategory.OST_Doors))
            {
                Definition basalOpening = defGroup.Definitions.get_Item("BasalOpening");

                if (null == basalOpening)
                {
                    basalOpening = defGroup.Definitions.Create("BasalOpening", ParameterType.Text, false);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(basalOpening, typeBinding, BuiltInParameterGroup.PG_GEOMETRY);
            }



            // for "InstanceOpening"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "InstanceOpening", BuiltInCategory.OST_Doors))
            {
                Definition instanceOpening = defGroup.Definitions.get_Item("InstanceOpening");

                if (null == instanceOpening)
                {
                    instanceOpening = defGroup.Definitions.Create("InstanceOpening", ParameterType.Text, true);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(instanceOpening, instanceBinding, BuiltInParameterGroup.PG_GEOMETRY);
            }

            // for "Internal Door"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "Internal Door", BuiltInCategory.OST_Doors))
            {
                Definition internalDoorFlag = defGroup.Definitions.get_Item("Internal Door");

                if (null == internalDoorFlag)
                {
                    internalDoorFlag = defGroup.Definitions.Create("Internal Door", ParameterType.YesNo, true);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(internalDoorFlag, instanceBinding);
            }
        }
Exemplo n.º 11
0
        private bool Populate(ProjectParameter parameter)
        {
            if (Utils.IsAlreadyBound(doc, parameter.Name))
            {
                Cancel();
                Message = "Parameters already exists. Command will not be executed.";
                return(false);
            }
            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create per doc Parameters");
                // get the current shared params definition file
                DefinitionFile sharedParamsFile = Utils.GetSharedParamsFile(uiapp.Application);
                if (null == sharedParamsFile)
                {
                    Message = "Please, make sure you have set the Shared Parameters file for this project.";
                    return(false);
                }
                // get or create the shared params group
                DefinitionGroup sharedParamsGroup = Utils.GetOrCreateSharedParamsGroup(
                    sharedParamsFile, parameter.GroupName);

                if (null == sharedParamsGroup)
                {
                    Message = "Error getting the shared params group.";
                    return(false);
                }
                // param
                Definition docParamDef = Utils.GetOrCreateSharedParamsDefinition(
                    sharedParamsGroup, ParameterType.Text, parameter.Name, parameter.Tooltip, true);

                if (null == docParamDef)
                {
                    Message = "Error creating visible per-doc parameter.";
                    return(false);
                }
                try
                {
                    CategorySet catSet = Utils.AssignableCategories(uiapp, doc);

                    Autodesk.Revit.DB.Binding binding = null;

                    if (parameter.Type.Equals("Instance"))
                    {
                        binding = uiapp.Application.Create.NewInstanceBinding(catSet);
                        if (parameter.GroupName.Equals("Budget"))
                        {
                            doc.ParameterBindings.Insert(docParamDef, binding);
                        }
                        else
                        {
                            doc.ParameterBindings.Insert(docParamDef, binding, BuiltInParameterGroup.PG_COUPLER_ARRAY);
                        }
                    }
                    else
                    {
                        binding = uiapp.Application.Create.NewTypeBinding(catSet);
                        if (parameter.GroupName.Equals("Budget"))
                        {
                            doc.ParameterBindings.Insert(docParamDef, binding);
                        }
                        else
                        {
                            doc.ParameterBindings.Insert(docParamDef, binding, BuiltInParameterGroup.PG_COUPLER_ARRAY);
                        }
                    }
                }
                catch (Exception e)
                {
                    Message = "Error binding shared parameter: " + e.Message;
                    return(false);
                }

                tx.Commit();

                return(true);
            }
        }
Exemplo n.º 12
0
        public static void ShowDefinitionFileInfo(DefinitionFile myDefinitionFile)
        {
            StringBuilder fileInformation = new StringBuilder(500);

            // get the file name
            fileInformation.AppendLine("File Name: " + myDefinitionFile.Filename);

            // iterate the Definition groups of this file
            foreach (DefinitionGroup myGroup in myDefinitionFile.Groups)
            {
                // get the group name
                fileInformation.AppendLine("Group Name: " + myGroup.Name);

                // iterate the difinitions
                foreach (Definition definition in myGroup.Definitions)
                {
                    // get definition name
                    fileInformation.AppendLine("Definition Name: " + definition.Name);
                }
            }
            TaskDialog.Show("Revit", fileInformation.ToString());
        }
Exemplo n.º 13
0
        public static List<RawSharedParameterInfo> RawGetSharedParametersInfo(DefinitionFile defFile)
        {
            RawSharedParameterInfo.FileName = defFile.Filename;

            List<RawSharedParameterInfo> paramList =
                (from DefinitionGroup dg in defFile.Groups
                 from ExternalDefinition d in dg.Definitions
                 select new RawSharedParameterInfo
                 {
                     Name = d.Name,
                     GUID = d.GUID.ToString(),
                     Owner = d.OwnerGroup.Name,
                     Group = d.ParameterGroup,
                     Type = d.ParameterType,
                     ReadOnly = d.IsReadOnly,
                     Visible = d.Visible,

                 }).ToList();
            return paramList;
        }
Exemplo n.º 14
0
      /// <summary>
      /// load family parameters from the text file
      /// </summary>
      /// <param name="exist">
      /// indicate whether the shared parameter file exists
      /// </param>
      /// <returns>
      /// return true if succeeded; otherwise false
      /// </returns>
      private bool LoadSharedParameterFromFile(out bool exist)
      {
          string usrFilePath = "";
          string myDocsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
          OpenFileDialog openFileDialog1 = new OpenFileDialog();

          openFileDialog1.InitialDirectory = myDocsFolder;
          openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
          openFileDialog1.FilterIndex = 1;
          openFileDialog1.RestoreDirectory = true;
          openFileDialog1.Title = "Please Select the Shared Parameter File";

          if (openFileDialog1.ShowDialog() == DialogResult.OK)
          {
              usrFilePath = openFileDialog1.FileName;

              exist = true;
              string filePath = usrFilePath;
              if (!File.Exists(filePath))
              {
                  exist = false;
                  return true;
              }

              m_app.SharedParametersFilename = filePath;
              try
              {
                  m_sharedFile = m_app.OpenSharedParameterFile();
              }
              catch (System.Exception e)
              {
                  MessageManager.MessageBuff.AppendLine(e.Message);
                  return false;
              }
              return true;
          }
          else
          {
              exist = false;
              return false;
          }
      }
Exemplo n.º 15
0
        //static public BuiltInCategory Target = BuiltInCategory.OST_Walls;
        //static public string Target = "Drawing1.dwg";
        //static public BuiltInCategory Target = BuiltInCategory.OST_IOSModelGroups; // doc.Settings.Categories.get_Item returns null
        //static public string Target = "Model Groups"; // doc.Settings.Categories.get_Item throws an exception SystemInvalidOperationException "Operation is not valid due to the current state of the object."
        //static public BuiltInCategory Target = BuiltInCategory.OST_Lines; // model lines
        //static public BuiltInCategory Target = BuiltInCategory.OST_SWallRectOpening; // Rectangular Straight Wall Openings, case 1260656 [Add Parameters Wall Opening]
        //static public BuiltInCategory Target = BuiltInCategory.OST_Materials; // can I attach a shared parameter to a material element? Yes, absolutely, no problem at all.

        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Application   app   = uiapp.Application;
            Document      doc   = uiapp.ActiveUIDocument.Document;
            Category      cat   = null;

            #region Determine model group category
#if DETERMINE_MODEL_GROUP_CATEGORY
            List <Element> modelGroups = new List <Element>();
            //Filter fType = app.Create.Filter.NewTypeFilter( typeof( Group ) ); // "Binding the parameter to the category Model Groups is not allowed"
            Filter fType     = app.Create.Filter.NewTypeFilter(typeof(GroupType)); // same result "Binding the parameter to the category Model Groups is not allowed"
            Filter fCategory = app.Create.Filter.NewCategoryFilter(BuiltInCategory.OST_IOSModelGroups);
            Filter f         = app.Create.Filter.NewLogicAndFilter(fType, fCategory);
            if (0 < doc.get_Elements(f, modelGroups))
            {
                cat = modelGroups[0].Category;
            }
#endif // DETERMINE_MODEL_GROUP_CATEGORY
            #endregion // Determine model group category

            if (null == cat)
            {
                // The category we are defining the parameter for

                try
                {
                    cat = doc.Settings.Categories.get_Item(Target);
                }
                catch (Exception ex)
                {
                    message = "Error obtaining the shared param document category: "
                              + ex.Message;
                    return(Result.Failed);
                }
                if (null == cat)
                {
                    message = "Unable to obtain the shared param document category.";
                    return(Result.Failed);
                }
            }

            // Get the current shared params definition file

            DefinitionFile sharedParamsFile = LabUtils.GetSharedParamsFile(app);
            if (null == sharedParamsFile)
            {
                message = "Error getting the shared params file.";
                return(Result.Failed);
            }

            // Get or create the shared params group

            DefinitionGroup sharedParamsGroup
                = LabUtils.GetOrCreateSharedParamsGroup(
                      sharedParamsFile, LabConstants.SharedParamsGroupAPI);

            if (null == sharedParamsGroup)
            {
                message = "Error getting the shared params group.";
                return(Result.Failed);
            }

            // Visibility of the new parameter: the
            // Category.AllowsBoundParameters property
            // determines whether a category is allowed to
            // have user-visible shared or project parameters.
            // If it is false, it may not be bound to visible
            // shared parameters using the BindingMap. Note
            // that non-user-visible parameters can still be
            // bound to these categories.

            bool visible = cat.AllowsBoundParameters;

            // Get or create the shared params definition

            Definition fireRatingParamDef
                = LabUtils.GetOrCreateSharedParamsDefinition(
                      sharedParamsGroup, ParameterType.Number,
                      LabConstants.SharedParamsDefFireRating, visible);

            if (null == fireRatingParamDef)
            {
                message = "Error in creating shared parameter.";
                return(Result.Failed);
            }

            // Create the category set for binding and add the category
            // we are interested in, doors or walls or whatever:

            CategorySet catSet = app.Create.NewCategorySet();
            try
            {
                catSet.Insert(cat);
            }
            catch (Exception)
            {
                message = string.Format(
                    "Error adding '{0}' category to parameters binding set.",
                    cat.Name);
                return(Result.Failed);
            }

            // Bind the parameter.

            try
            {
                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Bind Fire Rating Shared Parameter");

                    Binding binding = app.Create.NewInstanceBinding(catSet);

                    // We could check if already bound, but looks
                    // like Insert will just ignore it in that case.

                    doc.ParameterBindings.Insert(fireRatingParamDef, binding);

                    // You can also specify the parameter group here:

                    //doc.ParameterBindings.Insert( fireRatingParamDef, binding, BuiltInParameterGroup.PG_GEOMETRY );

                    t.Commit();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Exemplo n.º 16
0
        protected override bool Init(object controller, object binding, DefinitionFile definition)
        {
            if (!base.Init(controller, binding, definition))
            {
                return(false);
            }

            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(UiButton));

            Icon = DefinitionResolver.GetShared <Texture2D>(Controller, Binding, file["Icon"], null);

            if (Icon == null)
            {
                Icon = new SharedValue <Texture2D>();
            }

            _gestureMargin = DefinitionResolver.Get <Margin>(Controller, Binding, file["GestureMargin"], Margin.None);

            _text = DefinitionResolver.GetSharedString(Controller, Binding, file["Text"]);

            if (_text == null)
            {
                _text = new SharedString();
            }

            if (file["Hold"] != null)
            {
                RegisterDelegate("Hold", file["Hold"]);
                _processHold = true;
            }

            RegisterDelegate("Release", file["Release"]);
            RegisterDelegate("Push", file["Push"]);

            RegisterDelegate("Click", file["Click"]);

            List <DefinitionFile> drawableFiles = file["Drawables"] as List <DefinitionFile>;

            if (file["Disabled"] != null && file["Enabled"] == null)
            {
                _enabledFlag       = DefinitionResolver.GetShared <bool>(Controller, Binding, file["Disabled"], false);
                _enabledFlagInvert = true;
            }
            else
            {
                _enabledFlag       = DefinitionResolver.GetShared <bool>(Controller, Binding, file["Enabled"], true);
                _enabledFlagInvert = false;
            }

            if (drawableFiles != null)
            {
                foreach (var def in drawableFiles)
                {
                    ButtonDrawable drawable = def.CreateInstance(Controller, Binding) as ButtonDrawable;

                    if (drawable != null)
                    {
                        _drawables.Add(drawable);
                    }
                }
            }

            _pushSound    = DefinitionResolver.Get <SoundEffect>(Controller, Binding, file["PushSound"], null);
            _releaseSound = DefinitionResolver.Get <SoundEffect>(Controller, Binding, file["ReleaseSound"], null);
            _actionSound  = DefinitionResolver.Get <SoundEffect>(Controller, Binding, file["ActionSound"], null);

            ButtonMode = DefinitionResolver.Get <UiButtonMode>(Controller, Binding, file["Mode"], UiButtonMode.Release);

            _repeatStart    = (float)DefinitionResolver.Get <int>(Controller, Binding, file["RepeatStart"], 0) / 1000f;
            _repeatInterval = (float)DefinitionResolver.Get <int>(Controller, Binding, file["RepeatInterval"], 0) / 1000f;

            return(true);
        }
Exemplo n.º 17
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)

        {
            //Get application and documnet objects

            UIApplication uiApp = commandData.Application;
            Document      doc   = uiApp.ActiveUIDocument.Document;
            Application   app   = doc.Application;

            try
            {
                //DO KLASY readSP
                //Open Shared Parameter file and collect SharedParam ExteralDefinition
                List <ExternalDefinition> spFileExternalDef = new List <ExternalDefinition>();
                DefinitionFile            spFile            = doc.Application.OpenSharedParameterFile();
                DefinitionGroups          gr = spFile.Groups;

                foreach (DefinitionGroup dG in gr)
                {
                    foreach (ExternalDefinition eD in dG.Definitions)
                    {
                        spFileExternalDef.Add(eD);
                    }
                }
                //@DO KLASY
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                //TODO:DO KLASY readExcel
                //Load ExcelFile and Categories to assign
                string spFileName    = spFile.Filename;
                string excelFileName = "";
                TaskDialog.Show("Info", "Wybierz plik excel z kategoriami przypisaymi do parametrów");

                WF.OpenFileDialog openFileDialog1 = new WF.OpenFileDialog();

                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter           = "Excel files (*.xlsx;*.xlsm;*.xls)|.xlsx;*.xlsm;*.xls";
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == WF.DialogResult.OK)
                {
                    excelFileName = openFileDialog1.FileName;
                }

                Excel.Application xlApp       = new Excel.Application();
                Excel.Workbook    xlWorkbook  = xlApp.Workbooks.Open(excelFileName);
                Excel._Worksheet  xlWorksheet = xlWorkbook.Sheets[1];
                Excel.Range       xlRange     = xlWorksheet.UsedRange;

                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;
                List <List <string> > categoryListFromExcel = new List <List <string> >();

                //wartości odejmowane od iteratorów wynikają z konstrukcji przykłądowego excela -> łatwiej opóścić od razu niepotrzebne kolumny i wiersze
                for (int i = 8; i <= rowCount; i++)
                {
                    List <string> sublist = new List <string>();
                    for (int j = 11; j <= colCount; j++)
                    {
                        sublist.Add(xlRange.Cells[i, j].Value);
                        sublist.RemoveAll(item => item == null);
                    }
                    categoryListFromExcel.Add(sublist);
                }

                //cleanup
                GC.Collect();
                GC.WaitForPendingFinalizers();

                //rule of thumb for releasing com objects:
                //  never use two dots, all COM objects must be referenced and released individually
                //  ex: [somthing].[something].[something] is bad

                //release com objects to fully kill excel process from running in the background
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);

                //close and release
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp);
                //@DO KLASY readExcel
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                //TODO:DO KLASY category list
                Categories categories = doc.Settings.Categories;

                SortedList <string, Category> allCategories = new SortedList <string, Category>();

                foreach (Category c in categories)
                {
                    allCategories.Add(c.Name, c);
                }

                List <List <Category> > categoryList = new List <List <Category> >();
                foreach (List <string> sub in categoryListFromExcel)
                {
                    List <Category> sublist = new List <Category>();
                    foreach (string cat in sub)
                    {
                        sublist.Add(allCategories[cat]);
                    }
                    categoryList.Add(sublist);
                }

                //@DO KLASY category list
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                //TODO:(3) generalnie to trzeba dodać jeszcze iterator do wyboru pomiędzy parametrem Type i Instance i ewentualnie grupę do któej ma zostać dodany parametr
                //TODO:(3) trzeba zobaczyc co jest z ... Array group = Enum.GetValues(typeof(BuiltInParameterGroup));
                Transaction trans = new Transaction(doc, "Dodanie SP");

                trans.Start();

                List <CategorySet> catSetList = new List <CategorySet>();
                BindingMap         bindMap    = doc.ParameterBindings;
                for (int i = 0; i < spFileExternalDef.Count; i++)
                {
                    CategorySet catSet = app.Create.NewCategorySet();
                    foreach (Category n in categoryList[i])
                    {
                        catSet.Insert(n);
                    }
                    InstanceBinding bind = app.Create.NewInstanceBinding(catSet);

                    Array group = Enum.GetValues(typeof(BuiltInParameterGroup));

                    var allSomeEnumValues     = (BuiltInParameterGroup[])Enum.GetValues(typeof(BuiltInParameterGroup));
                    BuiltInParameterGroup hgs = allSomeEnumValues[97];


                    bindMap.Insert(spFileExternalDef[i], bind);
                }

                trans.Commit();

                TaskDialog.Show("Info", "Dodanie parametrów współdzielonych zostało zakończone");
                return(Result.Succeeded);
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                // If user decided to cancel the operation return Result.Canceled
                return(Result.Cancelled);
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed
                message = ex.Message;
                return(Result.Failed);
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument  uiDoc = commandData.Application.ActiveUIDocument;
            Application app   = commandData.Application.Application;
            Document    doc   = uiDoc.Document;

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("PerDocParameter");

                // get the current shared params definition file
                DefinitionFile sharedParamsFile = SharedParameter.GetSharedParamsFile(app);
                if (null == sharedParamsFile)
                {
                    TaskDialog.Show("Per document parameter", "Error getting the shared params file.");
                    return(Result.Failed);
                }
                // get or create the shared params group
                DefinitionGroup sharedParamsGroup = SharedParameter.GetOrCreateSharedParamsGroup(sharedParamsFile, kParamGroupName);
                if (null == sharedParamsGroup)
                {
                    TaskDialog.Show("Per document parameter", "Error getting the shared params group.");
                    return(Result.Failed);
                }
                // visible param
                Definition docParamDefVisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Integer, kParamNameVisible, true);
                if (null == docParamDefVisible)
                {
                    TaskDialog.Show("Per document parameter", "Error creating visible per-doc parameter.");
                    return(Result.Failed);
                }
                // invisible param
                Definition docParamDefInvisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Integer, kParamNameInvisible, false);
                if (null == docParamDefInvisible)
                {
                    TaskDialog.Show("Per document parameter", "Error creating invisible per-doc parameter.");
                    return(Result.Failed);
                }
                // bind the param
                try
                {
                    CategorySet catSet = app.Create.NewCategorySet();
                    catSet.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_ProjectInformation));
                    Binding binding = app.Create.NewInstanceBinding(catSet);
                    doc.ParameterBindings.Insert(docParamDefVisible, binding);
                    doc.ParameterBindings.Insert(docParamDefInvisible, binding);
                }
                catch (Exception e)
                {
                    TaskDialog.Show("Per document parameter", "Error binding shared parameter: " + e.Message);
                    return(Result.Failed);
                }
                // set the initial values
                // get the singleton project info element
                Element projInfoElem = GetProjectInfoElem(doc);

                if (null == projInfoElem)
                {
                    TaskDialog.Show("Per document parameter", "No project info elem found. Aborting command...");
                    return(Result.Failed);
                }
                // for simplicity, access params by name rather than by GUID:
                //projInfoElem.get_Parameter(kParamNameVisible).Set(55);
                //projInfoElem.get_Parameter(kParamNameInvisible).Set(0);

                // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete:
                // 'This property is obsolete in Revit 2015, as more than one parameter can have the same name on a given element.
                // Use Element.Parameters to obtain a complete list of parameters on this Element,
                // or Element.GetParameters(String) to get a list of all parameters by name,
                // or Element.LookupParameter(String) to return the first available parameter with the given name.

                // modified code for Revit 2015
                projInfoElem.LookupParameter(kParamNameVisible).Set(55);
                projInfoElem.LookupParameter(kParamNameVisible).Set(0);
                transaction.Commit();
            }


            return(Result.Succeeded);
        }
Exemplo n.º 19
0
        /// <summary>
        /// When moving the mouse over other "loaded" check box while keeping the left mouse button pressed,
        /// change the "loaded" state to the new state when the left mouse button was pressed.
        /// </summary>
        /// <param name="e"></param>
        private void DataGrid_MouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                System.Windows.Forms.DataGrid.HitTestInfo theHitTestInfo;

                theHitTestInfo = DataGridSpecifySopClasses.HitTest(e.X, e.Y);

                switch (theHitTestInfo.Type)
                {
                case System.Windows.Forms.DataGrid.HitTestType.Cell:
                    // If this is the "loaded" column...
                    if (theHitTestInfo.Column == 0)
                    {
                        // If another "loaded" check box is pointed to, not the one where the state has
                        // last been changed...
                        if (theHitTestInfo.Row != _MouseEventInfoForDataGrid_LoadedStateChangedForRow)
                        {
                            DefinitionFile theDefinitionFile     = (DefinitionFile)_DefinitionFilesInfoForDataGrid[theHitTestInfo.Row];
                            bool           theCurrentLoadedState = theDefinitionFile.Loaded;

                            // Only if the state will change...
                            if (theCurrentLoadedState != _MouseEventInfoForDataGrid_LoadedStatedAfterMouseDown)
                            {
                                // Get the column style for the "loaded" column.
                                DataGridColumnStyle theDataGridColumnStyle;
                                theDataGridColumnStyle = DataGridSpecifySopClasses.TableStyles[0].GridColumnStyles[0];

                                // Change the "loaded" stated in _DefinitionFilesInfoForDataGrid and the data grid itself.
                                DataGridSpecifySopClasses.BeginEdit(theDataGridColumnStyle, theHitTestInfo.Row);
                                theDefinitionFile.Loaded = _MouseEventInfoForDataGrid_LoadedStatedAfterMouseDown;
                                DataGridSpecifySopClasses.EndEdit(theDataGridColumnStyle, theHitTestInfo.Row, false);

                                // Change the "loaded" state in the session object.
                                string theFullFileName = System.IO.Path.Combine(theDefinitionFile.DefinitionRoot, theDefinitionFile.Filename);

                                if (_MouseEventInfoForDataGrid_LoadedStatedAfterMouseDown)
                                {
                                    // The definition file was not loaded yet. Load it now.
                                    theSession.DefinitionManagement.LoadDefinitionFile(theFullFileName);
                                }
                                else
                                {
                                    // The definition file was loaded. Unload it now.
                                    theSession.DefinitionManagement.UnLoadDefinitionFile(theFullFileName);
                                }

                                // Remember the cell we've changed. We don't want to change the loaded
                                // state with each minor mouse move.
                                _MouseEventInfoForDataGrid_LoadedStateChangedForRow = theHitTestInfo.Row;
                            }
                            else
                            // State will not change. The cell under the mouse will not be selected. This
                            // results in scrolling that will not work when the mouse is moved to the bottom
                            // of the datagrid.
                            //
                            // To solve this, explicitly make the cell under the mouse selected.
                            {
                                DataGridCell currentSelectedCell = DataGridSpecifySopClasses.CurrentCell;
                                DataGridCell newSelectedCell     = new DataGridCell(theHitTestInfo.Row, currentSelectedCell.ColumnNumber);

                                DataGridSpecifySopClasses.CurrentCell = newSelectedCell;
                            }
                        }
                    }
                    break;
                }
            }
        }
 public static DefinitionFile SetDefinitionFile(this Element element, string sharedParameterFile)
 {
     Application application = element.Document.Application;
     //if it is already open it is returned from the cashed static field
     if (_definitionFile != null && application.SharedParametersFilename == sharedParameterFile) return _definitionFile;
     _definitionFile = application.GetSharedParamDefinitionFile(sharedParameterFile);
     return _definitionFile;
 }
Exemplo n.º 21
0
        //static Util.SpellingErrorCorrector
        //  _spellingErrorCorrector = null;

        void ProblemAddingParameterBindingForCategory(
            Document doc)
        {
            Application app = doc.Application;

            //if( null == _spellingErrorCorrector )
            //{
            //  _spellingErrorCorrector
            //    = new Util.SpellingErrorCorrector( app );
            //}

            DefinitionFile sharedParametersFile
                = app.OpenSharedParameterFile();

            DefinitionGroup group = sharedParametersFile
                                    .Groups.Create("Reinforcement");

            //Definition def = group.Definitions.Create( // 2014
            //  "ReinforcementParameter", ParameterType.Text );

            //ExternalDefinitionCreationOptions opt // 2021
            //  = new ExternalDefinitionCreationOptions(
            //    "ReinforcementParameter", ParameterType.Text );

            ExternalDefinitionCreationOptions opt // 2022
                = new ExternalDefinitionCreationOptions(
                      "ReinforcementParameter", SpecTypeId.String.Text);

            Definition def = group.Definitions.Create(opt); // 2015

            // To handle both ExternalDefinitonCreationOptions
            // and ExternalDefinitionCreationOptions:

            //def = _spellingErrorCorrector.NewDefinition(
            //  group.Definitions, "ReinforcementParameter",
            //  //ParameterType.Text // 2021
            //  SpecTypeId.String.Text ); // 2022

            List <BuiltInCategory> bics
                = new List <BuiltInCategory>();

            //bics.Add(BuiltInCategory.OST_AreaRein);
            //bics.Add(BuiltInCategory.OST_FabricAreas);
            //bics.Add(BuiltInCategory.OST_FabricReinforcement);
            //bics.Add(BuiltInCategory.OST_PathRein);
            //bics.Add(BuiltInCategory.OST_Rebar);

            bics.Add(BuiltInCategory
                     .OST_IOSRebarSystemSpanSymbolCtrl);

            CategorySet catset = new CategorySet();

            foreach (BuiltInCategory bic in bics)
            {
                catset.Insert(
                    doc.Settings.Categories.get_Item(bic));
            }

            InstanceBinding binding
                = app.Create.NewInstanceBinding(catset);

            doc.ParameterBindings.Insert(def, binding,
                                         BuiltInParameterGroup.PG_CONSTRUCTION);
        }
Exemplo n.º 22
0
        private void Stream(ArrayList data, DefinitionFile defFile)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(DefinitionFile)));

            data.Add(new Snoop.Data.String("Filename", defFile.Filename));
            data.Add(new Snoop.Data.Object("Groups", defFile.Groups));
        }
Exemplo n.º 23
0
        public new static void Parse(XNode node, DefinitionFile file)
        {
            UiContainer.Parse(node, file);

            DefinitionParser parser = new DefinitionParser(node);

            file["Items"]            = parser.ParseDelegate("Items");
            file["Mode"]             = parser.ParseEnum <Mode>("Mode");
            file["Reverse"]          = parser.ParseBoolean("Reverse");
            file["MaxAddFirstTime"]  = parser.ParseInt("MaxAddFirstTime");
            file["MaxAddOneTime"]    = parser.ParseInt("MaxAddOneTime");
            file["ExceedRule"]       = parser.ParseEnum <ScrollingService.ExceedRule>("ExceedRule");
            file["WheelScrollSpeed"] = parser.ParseDouble("WheelScrollSpeed");
            file["MaxScrollExceed"]  = parser.ParseLength("MaxScrollExceed");

            Dictionary <Type, DefinitionFile> additionalTemplates = new Dictionary <Type, DefinitionFile>();

            foreach (var cn in node.Nodes)
            {
                switch (cn.Tag)
                {
                case "UiListBox.ItemTemplate":
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiListBox.ItemTemplate must have exactly 1 child.");

                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    if (string.IsNullOrEmpty(cn.Attribute("DataType")))
                    {
                        if (file["Template"] != null)
                        {
                            string error = node.NodeError("UiListBox default template already defined.");

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        file["Template"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                    }
                    else
                    {
                        Type type = Type.GetType(cn.Attribute("DataType"));

                        if (type == null)
                        {
                            string error = node.NodeError("Cannot find type: {0}", cn.Attribute("DataType"));

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        additionalTemplates.Add(type, DefinitionFile.LoadFile(cn.Nodes[0]));
                    }
                }
                break;
                }
            }

            if (additionalTemplates.Count > 0)
            {
                file["AdditionalTemplates"] = additionalTemplates;
            }
        }
Exemplo n.º 24
0
        private bool LoadSharedParameterFromFile(out bool exist)
        {
            exist = true;

            // verify that the file exists before continuing
            if (!File.Exists(_sharedFilePath))
            {
                exist = false;
                return true;
            }

            // if the file exists make it the current shared parameter file
            _app.SharedParametersFilename = _sharedFilePath;

            try
            {
                // access the shared parameter file
                _sharedFile = _app.OpenSharedParameterFile();
            }
            catch (System.Exception e)
            {
                TaskDialog.Show("Error", e.Message);
                return false;
            }

            return true;
        }
Exemplo n.º 25
0
        protected override bool Init(object controller, object binding, DefinitionFile definition)
        {
            if(!base.Init(controller, binding, definition))
            {
                return false;
            }

            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(UiScrollBar));

            _grid = DefinitionResolver.GetShared<AutomataGrid>(Controller, Binding, file["AutomataGrid"], null);
            _editEnabled = DefinitionResolver.GetShared<bool>(Controller, Binding, file["EditEnabled"], true);

            _zoom = DefinitionResolver.GetShared<double>(Controller, Binding, file["Zoom"], 16);

            _colors = DefinitionResolver.Get<Color[]>(Controller, Binding, file["Colors"], null);
            _gridColor = DefinitionResolver.GetColorWrapper(Controller, Binding, file["GridColor"]);

            _stateToPaint = DefinitionResolver.GetShared<int>(Controller, Binding, file["StateToPaint"], 0);

            _calculatedForSize = new Point(_grid.Value.Width, _grid.Value.Height);

            return true;
        }
Exemplo n.º 26
0
 void CreatePositionParameters(UiController controller, object binding, DefinitionFile file)
 {
     PositionParameters = new PositionParameters();
     PositionParameters.Init(controller, binding, file);
 }
Exemplo n.º 27
0
        private void AddSharedParameters(Application app, Document doc, CategorySet myCategorySet)
        {
            //Save the previous shared param file path
            string previousSharedParam = app.SharedParametersFilename;

            //Extract shared param to a txt file
            string tempPath = System.IO.Path.GetTempPath();
            string SPPath   = Path.Combine(tempPath, "FileProperties.txt");

            if (!File.Exists(SPPath))
            {
                //extract the familly
                List <string> files = new List <string>();
                files.Add("FileProperties.txt");
                Tools.ExtractEmbeddedResource(tempPath, "TimeStamp.Resources", files);
            }

            //set the shared param file
            app.SharedParametersFilename = SPPath;

            //Retrive shared parameters
            DefinitionFile myDefinitionFile = app.OpenSharedParameterFile();

            DefinitionGroup definitionGroup = myDefinitionFile.Groups.get_Item("FileProperties");

            foreach (Definition paramDef in definitionGroup.Definitions)
            {
                // Get the BingdingMap of current document.
                BindingMap bindingMap = doc.ParameterBindings;

                //the parameter does not exist
                if (!bindingMap.Contains(paramDef))
                {
                    //Create an instance of InstanceBinding
                    InstanceBinding instanceBinding = app.Create.NewInstanceBinding(myCategorySet);

                    bindingMap.Insert(paramDef, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                }
                //the parameter is not added to the correct categories
                else if (bindingMap.Contains(paramDef))
                {
                    InstanceBinding currentBinding = bindingMap.get_Item(paramDef) as InstanceBinding;
                    currentBinding.Categories = myCategorySet;
                    bindingMap.ReInsert(paramDef, currentBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                }
            }

            //SetAllowVaryBetweenGroups for these parameters
            string[] parameterNames = { "BIM42_Date", "BIM42_Version", "BIM42_File", "BIM42_Discipline" };

            DefinitionBindingMapIterator definitionBindingMapIterator = doc.ParameterBindings.ForwardIterator();

            definitionBindingMapIterator.Reset();

            while (definitionBindingMapIterator.MoveNext())
            {
                InternalDefinition paramDef = definitionBindingMapIterator.Key as InternalDefinition;
                if (paramDef != null)
                {
                    if (parameterNames.Contains(paramDef.Name))
                    {
                        paramDef.SetAllowVaryBetweenGroups(doc, true);
                    }
                }
            }

            //Reset to the previous shared parameters text file
            app.SharedParametersFilename = previousSharedParam;
            File.Delete(SPPath);
        }
Exemplo n.º 28
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document famdoc = commandData.Application.ActiveUIDocument.Document;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            string oldSharedParamFilePath = app.SharedParametersFilename;

            if (!famdoc.IsFamilyDocument)
            {
                message = "Инструмнет доступен только в редакторе семейств";
                return(Result.Failed);
            }

            System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
            openDialog.Title       = "Выберите семейство-аналог";
            openDialog.Multiselect = false;

            if (openDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            string familyPath = openDialog.FileName;

            Document           analogFamilyDoc           = commandData.Application.Application.OpenDocumentFile(familyPath);
            ParametersInFamily pif                       = new ParametersInFamily(analogFamilyDoc);
            List <SharedParameterContainer> analogParams = pif.parameters;


            string     familyFolder = Path.GetDirectoryName(familyPath);
            string     familyTitle  = analogFamilyDoc.Title.Remove(analogFamilyDoc.Title.Length - 4);
            string     txtPath      = Path.Combine(familyFolder, familyTitle + ".txt");
            FileStream fs           = File.Create(txtPath);

            fs.Close();

            commandData.Application.Application.SharedParametersFilename = txtPath;
            DefinitionFile defFile = app.OpenSharedParameterFile();

            foreach (SharedParameterContainer spc in analogParams)
            {
                DefinitionGroup tempGroup = defFile.Groups.Create(spc.name);
                Definitions     defs      = tempGroup.Definitions;
                ExternalDefinitionCreationOptions defOptions = new ExternalDefinitionCreationOptions(spc.name, spc.intDefinition.ParameterType);
                defOptions.GUID = spc.guid;

                spc.exDefinition = defs.Create(defOptions) as ExternalDefinition;
            }

            FamilyManager fMan = famdoc.FamilyManager;

            int    c = 0, ex = 0, er = 0;
            string errMsg = "";

            foreach (SharedParameterContainer spc in analogParams)
            {
                bool checkExists = ParametersInFamily.ParamIsExists(famdoc, spc);
                if (checkExists)
                {
                    ex++;
                    continue;
                }
                try
                {
                    using (Transaction t = new Transaction(famdoc))
                    {
                        t.Start("Добавление параметров");
                        fMan.AddParameter(spc.exDefinition, spc.paramGroup, spc.isInstance);
                        t.Commit();
                    }
                    c++;
                }
                catch (Exception exc)
                {
                    er++;
                    errMsg = exc.Message;
                }
            }



            analogFamilyDoc.Close(false);
            System.IO.File.Delete(txtPath);
            app.SharedParametersFilename = oldSharedParamFilePath;

            string msg = "Успешно добавлено параметров: " + c;

            if (ex > 0)
            {
                msg += "\nУже присутствовали в семействе: " + ex;
            }
            if (er > 0)
            {
                msg += "\nНе удалось добавить: " + er + "\n" + errMsg;
            }
            TaskDialog.Show("Добавление параметров", msg);

            return(Result.Succeeded);
        }
Exemplo n.º 29
0
 public new static void Parse(XNode node, DefinitionFile file)
 {
     ButtonDrawable.Parse(node, file);
 }
Exemplo n.º 30
0
        protected override bool Init(object controller, object binding, DefinitionFile definition)
        {
            if (!base.Init(controller, binding, definition))
            {
                return(false);
            }

            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(UiRichView));

            string defaultFont        = file["Font"] as string;
            int    defaultFontSize    = DefinitionResolver.Get <int>(Controller, Binding, file["FontSize"], 0);
            int    defaultFontSpacing = DefinitionResolver.Get <int>(Controller, Binding, file["FontSpacing"], int.MaxValue);

            for (int idx = 0; idx < (int)FontType.Count; ++idx)
            {
                FontType type    = (FontType)idx;
                string   font    = string.Format("{0}.Font", type);
                string   spacing = string.Format("{0}.FontSpacing", type);
                string   resize  = string.Format("{0}.FontResize", type);

                string fontName    = file[font] as string;
                int    fontSpacing = DefinitionResolver.Get <int>(Controller, Binding, file[spacing], defaultFontSpacing == int.MaxValue ? 0 : defaultFontSpacing);
                int    fontResize  = DefinitionResolver.Get <int>(Controller, Binding, file[resize], 0);

                if (fontName == null)
                {
                    fontName = defaultFont;
                }

                FontFace fontObj = FontManager.Instance.FindFont(fontName);

                if (defaultFont == null)
                {
                    defaultFont = fontName;
                }

                if (defaultFontSpacing == int.MaxValue)
                {
                    defaultFontSpacing = fontSpacing;
                }

                _fonts[idx] = new FontInfo()
                {
                    Font        = fontObj,
                    FontSpacing = (float)fontSpacing / 1000.0f,
                    FontResize  = fontResize
                };
            }

            for (int idx = 0; idx < (int)SizeType.Count; ++idx)
            {
                SizeType type = (SizeType)idx;
                string   size = string.Format("{0}.FontSize", type);

                int fontSize = DefinitionResolver.Get <int>(Controller, Binding, file[size], defaultFontSize);

                if (defaultFontSize == 0)
                {
                    defaultFontSize = fontSize;
                }

                _sizes[idx] = fontSize;
            }

            _bulletText = DefinitionResolver.GetString(Controller, Binding, file["BulletText"]) ?? "* ";
            //_bulletText = _bulletText.Replace(" ", ((char)0xa0).ToString());

            _horizontalRulerHeight = DefinitionResolver.Get <Length>(Controller, Binding, file["HorizontalRulerHeight"], new Length(0, 0, 1));
            _indentSize            = DefinitionResolver.Get <Length>(Controller, Binding, file["Indent"], Length.Zero);
            _paragraphSpacing      = DefinitionResolver.Get <Length>(Controller, Binding, file["ParagraphSpacing"], Length.Zero);
            _imageNotLoaded        = DefinitionResolver.Get <Texture2D>(Controller, Binding, file["ImageNotLoaded"], AdvancedDrawBatch.OnePixelWhiteTexture);
            _lineHeight            = (float)DefinitionResolver.Get <int>(Controller, Binding, file["LineHeight"], 100) / 100.0f;
            _justify = DefinitionResolver.Get <bool>(Controller, Binding, file["Justify"], false);

            _linkResolver = DefinitionResolver.Get <ILinkResolver>(Controller, Binding, file["LinkResolver"], this);

            _baseLineCorrection = DefinitionResolver.Get <bool>(Controller, Binding, file["EnableBaseLineCorrection"], false);

            Type processorType = file["Processor"] as Type;

            if (processorType != null)
            {
                _richProcessor = Activator.CreateInstance(processorType) as IRichProcessor;
            }

            Text = DefinitionResolver.GetString(Controller, Binding, file["Text"]);

            _colorNormal          = DefinitionResolver.GetColorWrapper(Controller, Binding, file["TextColor"]) ?? UiLabel.DefaultTextColor;
            _colorClickable       = DefinitionResolver.GetColorWrapper(Controller, Binding, file["LinkColor"]) ?? UiLabel.DefaultTextColor;
            _colorClickableActive = DefinitionResolver.GetColorWrapper(Controller, Binding, file["ActiveLinkColor"]) ?? _colorClickable;
            _colorRuler           = DefinitionResolver.GetColorWrapper(Controller, Binding, file["HorizontalRulerColor"]) ?? UiLabel.DefaultTextColor;

            HorizontalContentAlignment horzAlign = DefinitionResolver.Get <HorizontalContentAlignment>(Controller, Binding, file["HorizontalContentAlignment"], HorizontalContentAlignment.Left);
            VerticalContentAlignment   vertAlign = DefinitionResolver.Get <VerticalContentAlignment>(Controller, Binding, file["VerticalContentAlignment"], VerticalContentAlignment.Top);

            _textAlign = UiHelper.TextAlignFromContentAlignment(horzAlign, vertAlign);

            _clickMargin = DefinitionResolver.Get <Length>(Controller, Binding, file["ClickMargin"], Length.Zero);

            RegisterDelegate("UrlClick", file["UrlClick"]);

            EnabledGestures = (GestureType.Down | GestureType.Up | GestureType.Move | GestureType.Tap);

            return(true);
        }
Exemplo n.º 31
0
        /// <summary>
        /// The method generates a new shared parameter,
        /// then binding it to a particular category in a document
        /// </summary>
        /// <param name="parameterName">Shared Parameter Name</param>
        /// <param name="parameterType">Shared Parameter Type</param>
        /// <param name="categories">Categories to bind the parameter to</param>
        /// <param name="parameterGroup"></param>
        /// <param name="isInstance">Whether the parameter is an instance or type one</param>
        /// <param name="isModifiable">Whether the user is allowed to modify the parameter</param>
        /// <param name="isVisible">Is it visible to the user</param>
        /// <param name="defGroupName">The name of a group in a shared parameter file</param>
        /// <param name="createTmpFile">Is a temp shared parameter file to be generated</param>
        /// <param name="guid">The guid of the shared parameter</param>
        internal void CreateSharedParameter(
            string parameterName,
            ParameterType parameterType,
            IList <BuiltInCategory> categories,
            BuiltInParameterGroup parameterGroup,
            bool isInstance, bool isModifiable, bool isVisible,
            string defGroupName = "Custom", bool createTmpFile = false,
            Guid guid           = default(Guid))
        {
            string tempFilePath = null;

            try {
                // Get access to the file
                DefinitionFile defFile =
                    m_doc.Application.OpenSharedParameterFile();

                if (defFile == null || createTmpFile)
                {
                    // set the location of a new .txt file
                    tempFilePath =
                        System.IO.Path.GetTempFileName() + ".txt";

                    // Create the .txt file containing shared parameter definitions
                    using (System.IO.Stream s = System.IO.File.Create(tempFilePath)) {
                        s.Close();
                    }

                    // set the file as a shared parameter source file to the application
                    m_doc.Application.SharedParametersFilename = tempFilePath;
                    defFile =
                        m_doc.Application.OpenSharedParameterFile();
                }

                // Create a new group called
                DefinitionGroup defGroup =
                    defFile.Groups.FindDefinitionGroup(defGroupName);
                if (defGroup == null)
                {
                    defGroup = defFile.Groups.Create(defGroupName);
                }

                // Create a new defintion
                ExternalDefinitionCreationOptions defCrtOptns =
                    new ExternalDefinitionCreationOptions
                        (parameterName, parameterType);
                defCrtOptns.UserModifiable = isModifiable;
                defCrtOptns.Visible        = isVisible;
                if (guid != default(Guid))
                {
                    defCrtOptns.GUID = guid;
                }

                // Insert the definition into the group
                Definition def =
                    defGroup.Definitions.Create(defCrtOptns);

                // Lay out the categories to which the params
                // will be bound
                CategorySet categorySet = new CategorySet();

                foreach (BuiltInCategory category in categories)
                {
                    categorySet.Insert(m_doc.Settings.Categories.get_Item(category));
                }

                // Define a binding type
                Binding binding = null;
                if (isInstance)
                {
                    binding = new InstanceBinding(categorySet);
                }
                else
                {
                    binding = new TypeBinding(categorySet);
                }

                // Bind the parameter to the active document
                using (Transaction t = new Transaction(m_doc)) {
                    t.Start("Add Read Only Parameter");
                    m_doc.ParameterBindings.Insert
                        (def, binding, parameterGroup);
                    t.Commit();
                }

                Autodesk.Revit.UI.TaskDialog.Show("Success",
                                                  string.Format("The paramter {0} has been successfully added to the document",
                                                                def.Name));
            }
            finally {
                if (tempFilePath != null)
                {
                    System.IO.File.Delete(tempFilePath);
                    m_doc.Application.SharedParametersFilename = null;
                }
            }
        }
Exemplo n.º 32
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (doc.IsFamilyDocument)
            {
                message = "This command can only be used in a project, not in a family file.";
                return(Result.Failed);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create per doc Parameters");
                // get the current shared params definition file
                DefinitionFile sharedParamsFile = LabUtils.GetSharedParamsFile(app.Application);
                if (null == sharedParamsFile)
                {
                    message = "Error getting the shared params file.";
                    return(Result.Failed);
                }
                // get or create the shared params group
                DefinitionGroup sharedParamsGroup = LabUtils.GetOrCreateSharedParamsGroup(
                    sharedParamsFile, LabConstants.ParamGroupName);

                if (null == sharedParamsGroup)
                {
                    message = "Error getting the shared params group.";
                    return(Result.Failed);
                }
                // visible param
                Definition docParamDefVisible = LabUtils.GetOrCreateSharedParamsDefinition(
                    sharedParamsGroup, ParameterType.Integer, LabConstants.ParamNameVisible, true);

                if (null == docParamDefVisible)
                {
                    message = "Error creating visible per-doc parameter.";
                    return(Result.Failed);
                }
                // invisible param
                Definition docParamDefInvisible = LabUtils.GetOrCreateSharedParamsDefinition(
                    sharedParamsGroup, ParameterType.Integer, LabConstants.ParamNameInvisible, false);

                if (null == docParamDefInvisible)
                {
                    message = "Error creating invisible per-doc parameter.";
                    return(Result.Failed);
                }
                // bind the param
                try
                {
                    CategorySet catSet = app.Application.Create.NewCategorySet();

                    catSet.Insert(doc.Settings.Categories.get_Item(
                                      BuiltInCategory.OST_ProjectInformation));

                    Binding binding = app.Application.Create.NewInstanceBinding(catSet);
                    doc.ParameterBindings.Insert(docParamDefVisible, binding);
                    doc.ParameterBindings.Insert(docParamDefInvisible, binding);
                }
                catch (Exception e)
                {
                    message = "Error binding shared parameter: " + e.Message;
                    return(Result.Failed);
                }
                // set the initial values
                // get the singleton project info element
                Element projInfoElem = LabUtils.GetProjectInfoElem(doc);

                if (null == projInfoElem)
                {
                    message = "No project info element found. Aborting command...";
                    return(Result.Failed);
                }

                // For simplicity, access params by name rather than by GUID
                // and simply the first best one found under that name:

                projInfoElem.LookupParameter(LabConstants.ParamNameVisible).Set(55);
                projInfoElem.LookupParameter(LabConstants.ParamNameInvisible).Set(0);

                tx.Commit();
            }
            return(Result.Succeeded);
        }
Exemplo n.º 33
0
        protected override void Init(Controllers.UiController controller, object binding, DefinitionFile definition)
        {
            base.Init(controller, binding, definition);

            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(TransformGroup));

            _reverse = DefinitionResolver.Get <bool>(controller, binding, file["Reverse"], false);

            List <DefinitionFile> drawableFiles = file["Drawables"] as List <DefinitionFile>;

            if (drawableFiles != null)
            {
                foreach (var def in drawableFiles)
                {
                    ButtonDrawable drawable = def.CreateInstance(controller, binding) as ButtonDrawable;

                    if (drawable != null)
                    {
                        _drawables.Add(drawable);
                    }
                }
            }

            _transitionPushed = (file["TransitionEffect"] as DefinitionFile).CreateInstance(controller, binding) as TransitionEffect;
        }
Exemplo n.º 34
0
        protected IFCImportCache(Document doc, string fileName)
        {
            // Get all categories of current document
            Settings documentSettings = doc.Settings;

            DocumentCategories    = documentSettings.Categories;
            GenericModelsCategory = DocumentCategories.get_Item(BuiltInCategory.OST_GenericModel);

            ProjectInfo projectInfo = doc.ProjectInformation;

            ProjectInformationId = (projectInfo == null) ? ElementId.InvalidElementId : projectInfo.Id;

            // Cache the original shared parameters file, and create and read in a new one.
            OriginalSharedParametersFile             = doc.Application.SharedParametersFilename;
            doc.Application.SharedParametersFilename = fileName + ".sharedparameters.txt";

            try
            {
                DefinitionFile definitionFile = doc.Application.OpenSharedParameterFile();
                if (definitionFile == null || definitionFile.Groups.IsEmpty)
                {
                    StreamWriter definitionFileStream = new StreamWriter(doc.Application.SharedParametersFilename, false);
                    definitionFileStream.Close();
                    definitionFile = doc.Application.OpenSharedParameterFile();
                }

                if (definitionFile == null)
                {
                    throw new InvalidOperationException("Can't create definition file for shared parameters.");
                }

                DefinitionGroup definitionInstanceGroup = definitionFile.Groups.get_Item("IFC Parameters");
                if (definitionInstanceGroup == null)
                {
                    definitionInstanceGroup = definitionFile.Groups.Create("IFC Parameters");
                }
                InstanceGroupDefinitions = definitionInstanceGroup.Definitions;

                DefinitionGroup definitionTypeGroup = definitionFile.Groups.get_Item("IFC Type Parameters");
                if (definitionTypeGroup == null)
                {
                    definitionTypeGroup = definitionFile.Groups.Create("IFC Type Parameters");
                }
                TypeGroupDefinitions = definitionTypeGroup.Definitions;
            }
            catch (System.Exception)
            {
            }


            // Cache list of schedules.
            FilteredElementCollector viewScheduleCollector = new FilteredElementCollector(doc);
            ICollection <Element>    viewSchedules         = viewScheduleCollector.OfClass(typeof(ViewSchedule)).ToElements();

            foreach (Element viewSchedule in viewSchedules)
            {
                ScheduleDefinition definition = (viewSchedule as ViewSchedule).Definition;
                if (definition == null)
                {
                    continue;
                }

                ElementId categoryId = definition.CategoryId;
                if (categoryId == ElementId.InvalidElementId)
                {
                    continue;
                }

                string    viewScheduleName = viewSchedule.Name;
                ElementId viewScheduleId   = viewSchedule.Id;

                ViewSchedules[Tuple.Create(categoryId, false, viewScheduleName)] = viewScheduleId;
                ViewSchedules[Tuple.Create(categoryId, true, viewScheduleName)]  = viewScheduleId;
                ViewScheduleNames.Add(viewScheduleName);
            }

            // Find the status bar, so we can add messages.
            StatusBar = RevitStatusBar.Create();
        }
Exemplo n.º 35
0
        private static bool InsertBinding(UIApplication uiapp, DefinitionFile definitionFile, BCFParameters bcfParam, List <BuiltInCategory> bltCategories)
        {
            bool inserted = false;

            try
            {
                Document doc = uiapp.ActiveUIDocument.Document;
                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Insert Binding");
                    try
                    {
                        DefinitionBindingMapIterator iter = doc.ParameterBindings.ForwardIterator();
                        CategorySet catSet = uiapp.Application.Create.NewCategorySet();
                        foreach (BuiltInCategory bltCat in bltCategories)
                        {
                            Category category = doc.Settings.Categories.get_Item(bltCat);
                            if (null != category)
                            {
                                catSet.Insert(category);
                            }
                        }

                        //see if the project parameter already exists
                        Definition definitionFound = FindExistingDefinition(doc, bcfParam);
                        if (null != definitionFound)
                        {
                            ElementBinding elemBinding = (ElementBinding)doc.ParameterBindings.get_Item(definitionFound);
                            if (null != elemBinding)
                            {
                                bool reinsert = false;
                                foreach (Category cat in catSet)
                                {
                                    if (!elemBinding.Categories.Contains(cat))
                                    {
                                        reinsert = true;
                                    }
                                }

                                if (reinsert)
                                {
                                    InstanceBinding binding = uiapp.Application.Create.NewInstanceBinding(catSet);
                                    inserted = doc.ParameterBindings.ReInsert(definitionFound, binding);
                                    trans.Commit();
                                }
                                return(inserted);
                            }
                        }


                        Definition bcfDefinition = null;
                        foreach (DefinitionGroup group in definitionFile.Groups)
                        {
                            if (group.Name == "HOK BCF")
                            {
                                foreach (Definition definition in group.Definitions)
                                {
                                    if (definition.Name == bcfParam.ToString())
                                    {
                                        bcfDefinition = definition;
                                        break;
                                    }
                                }
                                break;
                            }
                        }

                        if (null != bcfDefinition)
                        {
                            InstanceBinding binding = uiapp.Application.Create.NewInstanceBinding(catSet);
                            inserted = doc.ParameterBindings.Insert(bcfDefinition, binding);
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message;
                        trans.RollBack();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(bcfParam.ToString() + " Failed to insert binding." + ex.Message, "Insert Binding", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(inserted);
        }
Exemplo n.º 36
0
        private void InsertIntoProjectParameters()
        {
            DefinitionFile sharedParametersFile = null;

            sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application);

            Dictionary <string, BuiltInParameterGroup> groupDict = new Dictionary <string, BuiltInParameterGroup>();

            groupDict = BrowserGroupDictionary();

            Category        revitCategory   = null;
            CategorySet     categorySet     = null;
            InstanceBinding instanceBinding = null;

            Autodesk.Revit.DB.Binding typeBinding = null;
            BindingMap bindingMap = null;

            bool emptyValueFlag = false;

            foreach (DataGridViewRow row in dgvSharedParameters.Rows)
            {
                string category     = row.Cells["clmCategory"].Value.ToString();
                string binding      = row.Cells["clmBinding"].Value.ToString();
                string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString();

                if (category == "" || binding == "" || browserGroup == "")
                {
                    emptyValueFlag = true;
                    break;
                }
            }

            if (!emptyValueFlag)
            {
                Transaction trans = new Transaction(myRevitDoc, "Insert Into Project Parameters");

                trans.Start();

                foreach (DataGridViewRow row in dgvSharedParameters.Rows)
                {
                    string name         = row.Cells["clmParamName"].Value.ToString();
                    string group        = row.Cells["clmGroup"].Value.ToString();
                    string category     = row.Cells["clmCategory"].Value.ToString();
                    string binding      = row.Cells["clmBinding"].Value.ToString();
                    string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString();

                    revitCategory = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(category);
                    categorySet   = myCommandData.Application.Application.Create.NewCategorySet();
                    categorySet.Insert(revitCategory);
                    instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                    typeBinding     = myCommandData.Application.Application.Create.NewTypeBinding(categorySet);
                    bindingMap      = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings;

                    ExternalDefinition extDef = GetSharedParameter(sharedParametersFile, group, name);

                    BuiltInParameterGroup paramGroup;

                    paramGroup = groupDict[browserGroup];

                    if (binding == "Type")
                    {
                        bindingMap.Insert(extDef, typeBinding, paramGroup);
                    }
                    else
                    {
                        bindingMap.Insert(extDef, instanceBinding, paramGroup);
                    }
                }

                trans.Commit();

                TaskDialog.Show("Insert into Project Parameters", "The Shared Parameters were inserted successfully");
                this.Close();
            }
            else
            {
                TaskDialog td = new TaskDialog("Insert into Project Parameters");
                td.MainInstruction = "Invalid value(s)";
                td.MainContent     = "Specify a value for Binding, Category, and Properties Group for each parameter before inserting into Project Parameters";
                td.Show();
            }
        }
        /// <summary>
        /// Create a new shared parameter
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="cat">Category to bind the parameter definition</param>
        /// <param name="nameSuffix">Parameter name suffix</param>
        /// <param name="typeParameter">Create a type parameter? If not, it is an instance parameter.</param>
        /// <returns></returns>
        bool CreateSharedParameter(
            Document doc,
            Category cat,
            int nameSuffix,
            bool typeParameter)
        {
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca
                = app.Create;

            // get or set the current shared params filename:

            string filename
                = app.SharedParametersFilename;

            if (0 == filename.Length)
            {
                string       path = _filename;
                StreamWriter stream;
                stream = new StreamWriter(path);
                stream.Close();
                app.SharedParametersFilename = path;
                filename = app.SharedParametersFilename;
            }

            // get the current shared params file object:

            DefinitionFile file
                = app.OpenSharedParameterFile();

            if (null == file)
            {
                Util.ErrorMsg(
                    "Error getting the shared params file.");

                return(false);
            }

            // get or create the shared params group:

            DefinitionGroup group
                = file.Groups.get_Item(_groupname);

            if (null == group)
            {
                group = file.Groups.Create(_groupname);
            }

            if (null == group)
            {
                Util.ErrorMsg(
                    "Error getting the shared params group.");

                return(false);
            }

            // set visibility of the new parameter:

            // Category.AllowsBoundParameters property
            // indicates if a category can have user-visible
            // shared or project parameters. If it is false,
            // it may not be bound to visible shared params
            // using the BindingMap. Please note that
            // non-user-visible parameters can still be
            // bound to these categories.

            bool visible = cat.AllowsBoundParameters;

            // get or create the shared params definition:

            string defname = _defname + nameSuffix.ToString();

            Definition definition = group.Definitions.get_Item(
                defname);

            if (null == definition)
            {
                //definition = group.Definitions.Create( defname, _deftype, visible ); // 2014

                ExternalDefinitionCreationOptions opt
                    = new ExternalDefinitionCreationOptions(
                          defname, _deftype);

                opt.Visible = visible;

                definition = group.Definitions.Create(opt); // 2015
            }
            if (null == definition)
            {
                Util.ErrorMsg(
                    "Error creating shared parameter.");

                return(false);
            }

            // create the category set containing our category for binding:

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(cat);

            // bind the param:

            try
            {
                Binding binding = typeParameter
          ? ca.NewTypeBinding(catSet) as Binding
          : ca.NewInstanceBinding(catSet) as Binding;

                // we could check if it is already bound,
                // but it looks like insert will just ignore
                // it in that case:

                doc.ParameterBindings.Insert(definition, binding);

                // we can also specify the parameter group here:

                //doc.ParameterBindings.Insert( definition, binding,
                //  BuiltInParameterGroup.PG_GEOMETRY );

                Debug.Print(
                    "Created a shared {0} parameter '{1}' for the {2} category.",
                    (typeParameter ? "type" : "instance"),
                    defname, cat.Name);
            }
            catch (Exception ex)
            {
                Util.ErrorMsg(string.Format(
                                  "Error binding shared parameter to category {0}: {1}",
                                  cat.Name, ex.Message));
                return(false);
            }
            return(true);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument  uidoc = commandData.Application.ActiveUIDocument;
            Application app   = commandData.Application.Application;
            Document    doc   = uidoc.Document;

            // Get the current shared params definition file
            DefinitionFile sharedParamsFile = GetSharedParamsFile(app);

            if (null == sharedParamsFile)
            {
                message = "Error getting the shared params file.";
                return(Result.Failed);
            }

            // Get or create the shared params group
            DefinitionGroup sharedParamsGroup = GetOrCreateSharedParamsGroup(
                sharedParamsFile, kSharedParamsGroupAPI);

            if (null == sharedParamsGroup)
            {
                message = "Error getting the shared params group.";
                return(Result.Failed);
            }

            Category cat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Doors);

            // Visibility of the new parameter:
            // Category.AllowsBoundParameters property indicates if a category can
            // have shared or project parameters. If it is false, it may not be bound
            // to shared parameters using the BindingMap. Please note that non-user-visible
            // parameters can still be bound to these categories.
            bool visible = cat.AllowsBoundParameters;

            // Get or create the shared params definition
            Definition fireRatingParamDef = GetOrCreateSharedParamsDefinition(
                sharedParamsGroup, ParameterType.Number, kSharedParamsDefFireRating, visible);

            if (null == fireRatingParamDef)
            {
                message = "Error in creating shared parameter.";
                return(Result.Failed);
            }

            // Create the category set for binding and add the category
            // we are interested in, doors or walls or whatever:
            CategorySet catSet = app.Create.NewCategorySet();

            try
            {
                catSet.Insert(cat);
            }
            catch (Exception)
            {
                message = string.Format(
                    "Error adding '{0}' category to parameters binding set.",
                    cat.Name);
                return(Result.Failed);
            }

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("Bind parameter");
                // Bind the param
                try
                {
                    Binding binding = app.Create.NewInstanceBinding(catSet);
                    // We could check if already bound, but looks like Insert will just ignore it in such case
                    doc.ParameterBindings.Insert(fireRatingParamDef, binding);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    transaction.RollBack();
                    return(Result.Failed);
                }
            }

            return(Result.Succeeded);
        }
        public static BindSharedParamResult BindSharedParam(
            Document doc,
            Category cat,
            string paramName,
            string grpName,
            ParameterType paramType,
            bool visible,
            bool instanceBinding)
        {
            try // generic
            {
                Application app = doc.Application;

                // This is needed already here to
                // store old ones for re-inserting

                CategorySet catSet = app.Create.NewCategorySet();

                // Loop all Binding Definitions
                // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !?
                // For multiple categories, there is really one
                // pair per each category, even though the
                // Definitions are the same...

                DefinitionBindingMapIterator iter
                    = doc.ParameterBindings.ForwardIterator();

                while (iter.MoveNext())
                {
                    Definition     def = iter.Key;
                    ElementBinding elemBind
                        = (ElementBinding)iter.Current;

                    // Got param name match

                    if (paramName.Equals(def.Name,
                                         StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Check for category match - Size is always 1!

                        if (elemBind.Categories.Contains(cat))
                        {
                            // Check Param Type

                            if (paramType != def.ParameterType)
                            {
                                return(BindSharedParamResult.eWrongParamType);
                            }

                            // Check Binding Type

                            if (instanceBinding)
                            {
                                if (elemBind.GetType() != typeof(InstanceBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }
                            else
                            {
                                if (elemBind.GetType() != typeof(TypeBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }

                            // Check Visibility - cannot (not exposed)
                            // If here, everything is fine,
                            // ie already defined correctly

                            return(BindSharedParamResult.eAlreadyBound);
                        }

                        // If here, no category match, hence must
                        // store "other" cats for re-inserting

                        else
                        {
                            foreach (Category catOld
                                     in elemBind.Categories)
                            {
                                catSet.Insert(catOld); // 1 only, but no index...
                            }
                        }
                    }
                }

                // If here, there is no Binding Definition for
                // it, so make sure Param defined and then bind it!

                DefinitionFile defFile
                    = GetOrCreateSharedParamsFile(app);

                DefinitionGroup defGrp
                    = GetOrCreateSharedParamsGroup(
                          defFile, grpName);

                Definition definition
                    = GetOrCreateSharedParamDefinition(
                          defGrp, paramType, paramName, visible);

                catSet.Insert(cat);

                InstanceBinding bind = null;

                if (instanceBinding)
                {
                    bind = app.Create.NewInstanceBinding(
                        catSet);
                }
                else
                {
                    bind = app.Create.NewTypeBinding(catSet);
                }

                // There is another strange API "feature".
                // If param has EVER been bound in a project
                // (in above iter pairs or even if not there
                // but once deleted), Insert always fails!?
                // Must use .ReInsert in that case.
                // See also similar findings on this topic in:
                // http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html
                // - the code-idiom below may be more generic:

                if (doc.ParameterBindings.Insert(
                        definition, bind))
                {
                    return(BindSharedParamResult.eSuccessfullyBound);
                }
                else
                {
                    if (doc.ParameterBindings.ReInsert(
                            definition, bind))
                    {
                        return(BindSharedParamResult.eSuccessfullyBound);
                    }
                    else
                    {
                        return(BindSharedParamResult.eFailed);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(
                                    "Error in Binding Shared Param: {0}",
                                    ex.Message));

                return(BindSharedParamResult.eFailed);
            }
        }
Exemplo n.º 40
0
        public bool LoadSharedParameterFile()
        {
            string myDocsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
              OpenFileDialog ofd = new OpenFileDialog();

              ofd.InitialDirectory = myDocsFolder;
              ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
              ofd.FilterIndex = 1;
              ofd.RestoreDirectory = true;
              ofd.Title = "Please Select the Shared Parameter File";

              if (ofd.ShowDialog() == DialogResult.OK)
              {
            m_sharedFilePath = ofd.FileName;
            if (!File.Exists(m_sharedFilePath))
            {
              return true;
            }

            m_app.SharedParametersFilename = m_sharedFilePath;
            try
            {
              m_sharedFile = m_app.OpenSharedParameterFile();
            }
            catch (System.Exception e)
            {
              MessageBox.Show(e.Message);
              return false;
            }
            return true;
              }
              else
              {
            return false;
              }
        }
Exemplo n.º 41
0
        protected override bool Init(object controller, object binding, DefinitionFile definition)
        {
            if (!base.Init(controller, binding, definition))
            {
                return(false);
            }

            InitChildren(Controller, Binding, definition);

            DefinitionFileWithStyle file = new DefinitionFileWithStyle(definition, typeof(UiContentSlider));

            if (file["SelectedIndex"] is MethodName || file["SelectedIndex"] is FieldName)
            {
                object value = DefinitionResolver.GetValueFromMethodOrField(Controller, Binding, file["SelectedIndex"]);

                if (value is SharedValue <int> )
                {
                    _sharedSelectedIndex = value as SharedValue <int>;
                    _selectedIndex       = _sharedSelectedIndex.Value;
                }

                if (value is int)
                {
                    _selectedIndex = (int)value;
                }
            }
            else
            {
                _selectedIndex = DefinitionResolver.Get <int>(Controller, Binding, file["SelectedIndex"], 0);
            }

            _cycle = DefinitionResolver.Get <bool>(Controller, Binding, file["Cycle"], false);

            double speed = DefinitionResolver.Get <double>(Controller, Binding, file["TransitionTime"], 500) / 1000.0;

            _transitionSpeed = (float)(speed > 0 ? 1 / speed : 10000000);

            DefinitionFile transitionEffectFile = file["ShowTransitionEffectNext"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                _transitionEffectShowNext = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            transitionEffectFile = file["HideTransitionEffectNext"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                _transitionEffectHideNext = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            transitionEffectFile = file["ShowTransitionEffectPrev"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                _transitionEffectShowPrev = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            transitionEffectFile = file["HideTransitionEffectPrev"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                _transitionEffectHidePrev = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
            }

            transitionEffectFile = file["ShowTransitionEffect"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                if (_transitionEffectShowPrev == null)
                {
                    _transitionEffectShowPrev = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
                }

                if (_transitionEffectShowNext == null)
                {
                    _transitionEffectShowNext = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
                }
            }

            transitionEffectFile = file["HideTransitionEffect"] as DefinitionFile;

            if (transitionEffectFile != null)
            {
                if (_transitionEffectHidePrev == null)
                {
                    _transitionEffectHidePrev = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
                }

                if (_transitionEffectHideNext == null)
                {
                    _transitionEffectHideNext = transitionEffectFile.CreateInstance(Controller, Binding) as TransitionEffect;
                }
            }

            if (_transitionEffectHideNext == null)
            {
                if (_transitionEffectShowNext != null)
                {
                    _transitionEffectHideNext = _transitionEffectShowNext.Reverse();
                }
            }

            if (_transitionEffectHidePrev == null)
            {
                if (_transitionEffectShowPrev != null)
                {
                    _transitionEffectHidePrev = _transitionEffectShowPrev.Reverse();
                }
            }

            if (_children.Count > 0)
            {
                _current = _children[_selectedIndex];
            }

            _previous = null;

            return(true);
        }
        /// <summary>
        ///  Creates new shared parameter if it does not exist and bind it to the type or instance of the objects 
        /// </summary>
        /// <param name="paramType">Type of the parameter</param>
        /// <param name="categoriesForParam">Category of elements to bind the parameter to</param>
        /// <param name="defaultGroupName">Group name of the parameters</param>
        /// <param name="parameterName">Name of the parameter</param>
        /// <returns>TRUE if shared parameter is created, FALSE otherwise</returns>
        public static bool SetNewSharedParameter(this Element element, ParameterType paramType, CategorySet categoriesForParam, string parameterName, BuiltInParameterGroup group)
        {
            string defaultGroupName = "4P_imported_parameters"; //this is a hack to avoid multiple parameters with the same name.

            if (categoriesForParam == null) return false;
            if (categoriesForParam.Size == 0) return false;
            foreach (Category cat in categoriesForParam)
            {
                if (cat == null) return false;
                if (!cat.AllowsBoundParameters) return false;
            }

            Application application = element.Document.Application;
            Document document = element.Document;
            if (_definitionFile == null)
            {
                //ask for the location of the shared parameters file
                var dialog = new Microsoft.Win32.OpenFileDialog();
                dialog.CheckFileExists = false;
                dialog.Title = "Set shared pID file...";
                dialog.ShowDialog();
                string shrFilePath = dialog.FileName;
                if (shrFilePath == null)
                {
                    _definitionFile = application.OpenSharedParameterFile();
                    if (_definitionFile == null) SetSharedParamFileInUserProgramFolder(document);
                }
                else
                {
                    SetDefinitionFile(element, shrFilePath);
                }
            }
            if (_definitionFile == null) throw new Exception("Definition file must be set before creation of the new parameters.");

            DefinitionFile myDefinitionFile = _definitionFile;

            // Get parameter or create new one
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            Definition myDefinition = null;
            bool found = false;

            foreach (DefinitionGroup gr in myGroups)
            {
                foreach (Definition def in gr.Definitions)
                {
                    if (def.Name == parameterName)
                    {
                        myDefinition = def;
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }

            //if there is not such a parameter new one is created in default group
            if (myDefinition == null)
            {
                DefinitionGroup myGroup = myGroups.get_Item(defaultGroupName);
                if (myGroup == null)
                {
                    myGroup = myGroups.Create(defaultGroupName);
                }

                // Create a type definition
                myDefinition = myGroup.Definitions.get_Item(parameterName);
                if (myDefinition == null)
                {
                    myDefinition = myGroup.Definitions.Create(parameterName, paramType);

                }
            }

            //Create an object of TypeBinding or InstanceBinding according to the Categories and "typeBinding" variable
            Binding binding = null;
            // Get the BingdingMap of current document.
            BindingMap bindingMap = document.ParameterBindings;
            binding = bindingMap.get_Item(myDefinition);

            bool bindOK = false;
            if (!element.CanHaveTypeAssigned() && !(element is Material) && !(element is ProjectInfo))
            {
                if (binding != null)
                {
                    TypeBinding typeBinding = binding as TypeBinding;
                    if (typeBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to instances. It cannot be bound to the type at the same time");
                    foreach (Category cat in categoriesForParam) typeBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewTypeBinding(categoriesForParam);
                }
            }
            else
            {
                if (binding != null)
                {
                    InstanceBinding instBinding = binding as InstanceBinding;
                    if (instBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to types. It cannot be bound to the instance at the same time");
                    foreach (Category cat in categoriesForParam) instBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewInstanceBinding(categoriesForParam);
                }
            }

            // Bind the definitions to the document
            bindOK = bindingMap.Insert(myDefinition, binding, group);
            return bindOK;
        }
            public static void AddSharedParameters(Document doc)
        {

            Transaction tx = new Transaction(doc);

            // ___ tilføjer Sharedparameter
            tx.Start("adding offset parameter");
            string orgSharedFilePath = doc.Application.SharedParametersFilename;
            doc.Application.SharedParametersFilename = @"C:\Temp\N_Shared_Parameters_GUID_TEST.txt";
            DefinitionFile DefFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroup grp = DefFile.Groups.get_Item("URI");
            Definition Def1 = grp.Definitions.get_Item("URI");
            Definition Def2 = grp.Definitions.get_Item("Host");
            Definition Def3 = grp.Definitions.get_Item("SpaceTypeURI");

            // create a category set and insert all categories to it
            CategorySet allCategories = doc.Application.Create.NewCategorySet();

            foreach (Category category in doc.Settings.Categories)
            {
                if (category.AllowsBoundParameters)
                {
                    allCategories.Insert(category);
                }
            }

            // Add shared parameter Def1 to all categories
            Binding binding = doc.Application.Create.NewTypeBinding(allCategories);
            binding = doc.Application.Create.NewInstanceBinding(allCategories);

            BindingMap map = (new UIApplication(doc.Application)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(Def1, binding, BuiltInParameterGroup.PG_IDENTITY_DATA);

            // Get category "Project Information"
            CategorySet projInfoCategory = doc.Application.Create.NewCategorySet();
            Category projInfoCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_ProjectInformation);
            projInfoCategory.Insert(projInfoCat);

            // Add shared parameter Def2 to project information category
            Binding binding1 = doc.Application.Create.NewTypeBinding(projInfoCategory);
            binding1 = doc.Application.Create.NewInstanceBinding(projInfoCategory);

            map = (new UIApplication(doc.Application)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(Def2, binding1, BuiltInParameterGroup.PG_IDENTITY_DATA);

            // Create a category set with rooms and spaces
            CategorySet spacesCategory = doc.Application.Create.NewCategorySet();
            Category roomsCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Rooms);
            Category spacesCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_MEPSpaces);
            spacesCategory.Insert(roomsCat);
            spacesCategory.Insert(spacesCat);

            // Add shared parameter Def3 to space categories
            Binding binding2 = doc.Application.Create.NewTypeBinding(spacesCategory);
            binding2 = doc.Application.Create.NewInstanceBinding(spacesCategory);

            map = (new UIApplication(doc.Application)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(Def3, binding2, BuiltInParameterGroup.PG_IDENTITY_DATA);

            doc.Application.SharedParametersFilename = orgSharedFilePath;
            tx.Commit();



        }
Exemplo n.º 44
0
 /// <summary>
 /// Helper to get shared params group.
 /// </summary>
 public static DefinitionGroup GetOrCreateSharedParamsGroup(
     DefinitionFile sharedParametersFile,
     string groupName)
 {
     DefinitionGroup g = sharedParametersFile.Groups.get_Item( groupName );
       if( null == g )
       {
     try
     {
       g = sharedParametersFile.Groups.Create( groupName );
     }
     catch( Exception )
     {
       g = null;
     }
       }
       return g;
 }
Exemplo n.º 45
0
        public new static void Parse(XNode node, DefinitionFile file)
        {
            UiStackPanel.Parse(node, file);
            DefinitionParser parser = new DefinitionParser(node);

            file["Items"] = parser.ParseDelegate("Items");

            Dictionary <Type, DefinitionFile> additionalTemplates = new Dictionary <Type, DefinitionFile>();

            foreach (var cn in node.Nodes)
            {
                switch (cn.Tag)
                {
                case "UiItemsStack.ItemTemplate":
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiItemsStack.ItemTemplate must have exactly 1 child.");

                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    if (string.IsNullOrEmpty(cn.Attribute("DataType")))
                    {
                        if (file["Template"] != null)
                        {
                            string error = node.NodeError("UiItemsStack default template already defined.");

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        file["Template"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                    }
                    else
                    {
                        Type type = Type.GetType(cn.Attribute("DataType"));

                        if (type == null)
                        {
                            string error = node.NodeError("Cannot find type: {0}", cn.Attribute("DataType"));

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        additionalTemplates.Add(type, DefinitionFile.LoadFile(cn.Nodes[0]));
                    }
                }
                break;
                }

                if (!cn.Tag.Contains('.'))
                {
                    throw new Exception("UiItemsStack cannot have any children.");
                }
            }

            if (additionalTemplates.Count > 0)
            {
                file["AdditionalTemplates"] = additionalTemplates;
            }
        }
Exemplo n.º 46
0
 private DefinitionGroup OpenGroup(string groupName, DefinitionFile definitionFile)
 {
     return definitionFile.Groups.get_Item(groupName)
         ?? definitionFile.Groups.Create(groupName);
 }
Exemplo n.º 47
0
        public static void Parse(XNode node, DefinitionFile file)
        {
            var parser = new DefinitionParser(node);

            file["Id"] = parser.ParseString("Id");

            string controller     = node.Attribute("Controller");
            Type   controllerType = null;

            if (!string.IsNullOrEmpty(controller))
            {
                controllerType = Type.GetType(controller);
                if (controllerType == null)
                {
                    throw new Exception(string.Format("Cannot find controller type: {0}.", controller));
                }
            }

            file["Controller"] = controllerType;

            file["Binding"] = parser.ParseDelegate("Binding");

            file["Modal"] = parser.ParseBoolean("Modal");

            file["Visible"] = parser.ParseBoolean("Visible");
            file["Hidden"]  = parser.ParseBoolean("Hidden");

            file["BackgroundColor"] = parser.ParseColor("BackgroundColor");

            file["Opacity"] = parser.ParseDouble("Opacity");

            file["ViewRemoved"] = parser.ParseDelegate("ViewRemoved");
            file["ViewAdded"]   = parser.ParseDelegate("ViewAdded");

            file["ViewActivated"]   = parser.ParseDelegate("ViewActivated");
            file["ViewDeactivated"] = parser.ParseDelegate("ViewDeactivated");

            file["ViewResized"] = parser.ParseDelegate("ViewResized");

            file["MinWidth"]  = parser.ParseLength("MinWidth", false);
            file["MinHeight"] = parser.ParseLength("MinHeight", false);

            file["ShowHideTime"] = parser.ParseDouble("ShowHideTime");

            file["HideTime"] = parser.ParseDouble("HideTime");
            file["ShowTime"] = parser.ParseDouble("ShowTime");

            file["Tag"] = parser.ParseString("Tag");

            PositionParameters.Parse(node, file);

            foreach (var cn in node.Nodes)
            {
                if (cn.Tag == "UiView.BackgroundDrawable")
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiView.BackgroundDrawable must have exactly 1 child.");
                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    file["BackgroundDrawable"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                }

                if (cn.Tag == "UiView.ShowTransitionEffect")
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiView.ShowTransitionEffect must have exactly 1 child.");
                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    file["ShowTransitionEffect"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                }

                if (cn.Tag == "UiView.HideTransitionEffect")
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiView.HideTransitionEffect must have exactly 1 child.");
                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    file["HideTransitionEffect"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                }

                if (cn.Tag == "UiView.ParentShowTransitionEffect")
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiView.NavigateToTransitionEffect must have exactly 1 child.");
                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    file["ParentShowTransitionEffect"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                }

                if (cn.Tag == "UiView.ParentHideTransitionEffect")
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiView.NavigateFromTransitionEffect must have exactly 1 child.");
                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    file["ParentHideTransitionEffect"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                }
            }
        }
        public InitializeResult Initialize(PluginEnvironment env, Assembly assembly, IMessageReceiver receiver)
        {
            // Data files contained in [datadrectory]/wordnet
            string basedir = (string)env.GetConfig("datadirectory") + Path.DirectorySeparatorChar + "wordnet" + Path.DirectorySeparatorChar;
            MemcachedClient cache = MemcacheSource.DefaultClient();

            nounIndexSource = new BackedMemcachedSource<Index>(new IndexFile(basedir, WordNetAccess.PartOfSpeech.Noun), "WN:I:N:", cache);
            verbIndexSource = new BackedMemcachedSource<Index>(new IndexFile(basedir, WordNetAccess.PartOfSpeech.Verb), "WN:I:V:", cache);
            adjIndexSource = new BackedMemcachedSource<Index>(new IndexFile(basedir, WordNetAccess.PartOfSpeech.Adj), "WN:I:A:", cache);
            advIndexSource = new BackedMemcachedSource<Index>(new IndexFile(basedir, WordNetAccess.PartOfSpeech.Adv), "WN:I:R:", cache);

            if (!advIndexSource.TestMemcached(10, 10)) {
                nounIndexSource.LoadIntoMemcached();
                verbIndexSource.LoadIntoMemcached();
                adjIndexSource.LoadIntoMemcached();
                advIndexSource.LoadIntoMemcached();
            }

            nounOffsetsSource = new MapDataSource<string, Index, long[]>(nounIndexSource, IndexFile.ExtractOffsets, null);
            verbOffsetsSource = new MapDataSource<string, Index, long[]>(verbIndexSource, IndexFile.ExtractOffsets, null);
            adjOffsetsSource = new MapDataSource<string, Index, long[]>(adjIndexSource, IndexFile.ExtractOffsets, null);
            advOffsetsSource = new MapDataSource<string, Index, long[]>(advIndexSource, IndexFile.ExtractOffsets, null);

            env.SetDataSource<string, long[]>(WordNetAccess.NounIndexSourceName, nounOffsetsSource);
            env.SetDataSource<string, long[]>(WordNetAccess.VerbIndexSourceName, verbOffsetsSource);
            env.SetDataSource<string, long[]>(WordNetAccess.AdjIndexSourceName, adjOffsetsSource);
            env.SetDataSource<string, long[]>(WordNetAccess.AdvIndexSourceName, advOffsetsSource);

            nounDefinitionSource = new DefinitionFile(basedir, WordNetAccess.PartOfSpeech.Noun);
            verbDefinitionSource = new DefinitionFile(basedir, WordNetAccess.PartOfSpeech.Verb);
            adjDefinitionSource = new DefinitionFile(basedir, WordNetAccess.PartOfSpeech.Adv);
            advDefinitionSource = new DefinitionFile(basedir, WordNetAccess.PartOfSpeech.Adv);

            env.SetDataSource<long, WordNetDefinition>(WordNetAccess.NounDefinitionSourceName, nounDefinitionSource);
            env.SetDataSource<long, WordNetDefinition>(WordNetAccess.VerbDefinitionSourceName, verbDefinitionSource);
            env.SetDataSource<long, WordNetDefinition>(WordNetAccess.AdjDefinitionSourceName, adjDefinitionSource);
            env.SetDataSource<long, WordNetDefinition>(WordNetAccess.AdvDefinitionSourceName, advDefinitionSource);

            return InitializeResult.Success();
        }
Exemplo n.º 49
0
        /// <summary>
        /// The information from a definition file is added to the datagrid and possibly to the combo box.
        /// 
        /// An excpetion is thrown when retrieving details for the definition file fails.
        /// </summary>
        /// <param name="theDefinitionFullFileName">the full file name of the definition file.</param>
        private void AddSopClassToDataGridFromDefinitionFile(string theDefinitionFullFileName)
        {
            Dvtk.Sessions.DefinitionFileDetails theDefinitionFileDetails;

            // Try to get detailed information about this definition file.
            theDefinitionFileDetails = theSession.DefinitionManagement.GetDefinitionFileDetails(theDefinitionFullFileName);

            // No excpetion thrown when calling GetDefinitionFileDetails (otherwise this statement would not have been reached)
            // so this is a valid definition file. Add it to the data frid.
            DefinitionFile theDataGridDefinitionFileInfo =
                new DefinitionFile(IsDefinitionFileLoaded(theDefinitionFullFileName),
                System.IO.Path.GetFileName(theDefinitionFullFileName),
                theDefinitionFileDetails.SOPClassName,
                theDefinitionFileDetails.SOPClassUID,
                theDefinitionFileDetails.ApplicationEntityName,
                theDefinitionFileDetails.ApplicationEntityVersion,
                System.IO.Path.GetDirectoryName(theDefinitionFullFileName));

            if (!theDefinitionFullFileName.Contains("AllDimseCommands.def"))
                _DefinitionFilesInfoForDataGrid.Add(theDataGridDefinitionFileInfo);
        }