Exemplo n.º 1
0
        private static XElement GenerateBasicSubmitDocument(IModelInstance instance, DateTime utcTime)
        {
            var xml = new XElement("formSubmit",
                                   new XAttribute("time", utcTime.ToString("o", CultureInfo.InvariantCulture)));

            var fields = new XElement("fields");

            foreach (var field in instance.Fields.Where(f => f.Label != null && f.Value != null))
            {
                string value;

                if (field.Value is DateTime dateTime)
                {
                    value = dateTime.ToString("o", CultureInfo.InvariantCulture);
                }
                else
                {
                    value = FormattingUtils.FormatFieldValue(field);
                }

                fields.Add(new XElement("field",
                                        new XAttribute("name", field.Name),
                                        new XAttribute("label", field.Label),
                                        new XAttribute("value", value)));
            }

            xml.Add(fields);

            return(xml);
        }
Exemplo n.º 2
0
        private static void SaveAttachments(IModelInstance instance, string dir, string timeStamp)
        {
            var formFiles = new List <FormFile>();

            foreach (var field in instance.Fields)
            {
                if (field.ValueType == typeof(FormFile) && field.Value != null)
                {
                    formFiles.Add((FormFile)field.Value);
                }
                else if (field.ValueType == typeof(IEnumerable <FormFile>) && field.Value != null)
                {
                    formFiles.AddRange((IEnumerable <FormFile>)field.Value);
                }
            }

            foreach (var formFile in formFiles)
            {
                var file = Path.Combine(dir, timeStamp + "_" + formFile.FileName);
                file = EnsureUniqueFileName(file);

                formFile.InputStream.Seek(0, SeekOrigin.Begin);

                using (var fileStream = File.Create(file))
                {
                    formFile.InputStream.CopyTo(fileStream);
                }
            }
        }
Exemplo n.º 3
0
 public virtual IList <IDomElement> GetChildElementsByType(IModelInstance modelInstance, Type elementType)
 {
     lock (_document)
     {
         XmlNodeList childNodes = _element.ChildNodes;
         return(DomUtil.FilterNodeListByType(childNodes, modelInstance, elementType));
     }
 }
Exemplo n.º 4
0
        public virtual IModelElementInstance NewInstance(IModelInstance modelInstance)
        {
            ModelInstanceImpl modelInstanceImpl = (ModelInstanceImpl)modelInstance;
            IDomDocument      document          = modelInstanceImpl.Document;
            IDomElement       domElement        = document.CreateElement(_typeNamespace, _typeName);

            return(NewInstance(modelInstanceImpl, domElement));
        }
Exemplo n.º 5
0
        public static object CreateAdapter(ScriptEngine engine, IModelInstance instance, string propertyName)
        {
            AjaxPage page = new AjaxPage();

            using (page.BeginContext(instance.Instance, null))
            {
                Adapter realAdapter = (Adapter)Binding.Parse("", "{@ " + propertyName + "}").Evaluate(page).Value;
                return(realAdapter == null ? null : new AdapterWrapper(engine, realAdapter));
            }
        }
Exemplo n.º 6
0
        //TODO 入口 IModelElementInstance解析
        /// <summary>
        /// Returns the <seealso cref="ModelElementInstanceImpl ModelElement"/> for a DOM element.
        /// If the model element does not yet exist, it is created and linked to the DOM.
        /// </summary>
        /// <param name="domElement"> the child element to create a new <seealso cref="ModelElementInstanceImpl ModelElement"/> for </param>
        /// <returns> the child model element </returns>
        public static IModelElementInstance GetModelElement(IDomElement domElement, IModelInstance modelInstance)
        {
            IModelElementInstance modelElement = domElement.ModelElementInstance;

            if (modelElement == null)
            {
                IModelElementType modelType = GetModelElement(domElement, modelInstance, domElement.NamespaceUri);
                modelElement = ((ModelElementTypeImpl)modelType).NewInstance(modelInstance, domElement);
                domElement.ModelElementInstance = modelElement;
            }
            return(modelElement);
        }
Exemplo n.º 7
0
 private bool OnAcceptModel(IModelInstance modelInstance)
 {
     // NOTICE: We don't use Linq, as It would allocated objects and triggers GC
     foreach (var test in acceptModels)
     {
         if (!test(modelInstance))
         {
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 8
0
        public virtual void SetReferenceTargetElement <T>(IModelElementInstance referenceSourceElement, T referenceTargetElement)
            where T : IModelElementInstance
        {
            IModelInstance        modelInstance             = referenceSourceElement.ModelInstance;
            string                referenceTargetIdentifier = ReferenceTargetAttribute.GetValue <String>(referenceTargetElement);
            IModelElementInstance existingElement           = modelInstance.GetModelElementById(referenceTargetIdentifier);

            if (existingElement == null || existingElement.Id != referenceTargetElement.Id)
            {
                throw new ModelReferenceException("Cannot create reference to model element " + referenceTargetElement + ": element is not part of model. Please connect element to the model first.");
            }
            SetReferenceIdentifier(referenceSourceElement, referenceTargetIdentifier);
        }
Exemplo n.º 9
0
        public void TestOpenMIModelFactoryGetInstances()
        {
            IOpenDaModelProvider simpleStochModelFactory = new Models.SimpleOscillatorModelFactory();

            simpleStochModelFactory.Initialize(@"..\..\testData\dummyModel\Model", "dummy-omifile.omi");
            ModelFactory.InsertModelFactory(simpleStochModelFactory);
            ModelFactory modelFactoryOpenMI = new ModelFactory();

            modelFactoryOpenMI.Initialize(null, new[] { "OpenDA.DotNet.OpenMI.Models.SimpleOscillatorModelFactory" });
            IModelInstance modelInstance = modelFactoryOpenMI.GetInstance(null, (int)OutputLevel.ModelDefault);

            modelInstance.Finish();
        }
Exemplo n.º 10
0
        public void OscillatorModelTest()
        {
            IModelFactory oscillatorModelFactory = new SimpleOscillatorModelFactory();

            oscillatorModelFactory.Initialize(".", new[] { "../../testData/OpenDaOscillBB/OscillatorModel.xml" });

            string[]       modelInstanceArguments = new[] { "this argument is not used" };
            IModelInstance modelInstance          = oscillatorModelFactory.GetInstance(modelInstanceArguments,
                                                                                       (int)OutputLevel.ModelDefault);

            IList <string> exchangeItemIDs = modelInstance.ExchangeItemIDs;

            Assert.IsTrue(exchangeItemIDs.Count > 0, "At least one EI");
            IExchangeItem thirdExchangeItem = modelInstance.GetExchangeItem(exchangeItemIDs[2]);

            Assert.AreEqual(AbstractModelInstance.StartTimeId, thirdExchangeItem.Id, "3th exchange item is t_start");

            double startTime = modelInstance.TimeHorizon.BeginTime.MJD;
            double endTime   = modelInstance.TimeHorizon.EndTime.MJD;
            double inBetween = startTime + (startTime + endTime) * 3 / 8;

            modelInstance.Compute(new Time(inBetween));

            IExchangeItem stateExchangeItem0 = modelInstance.GetExchangeItem(SimpleOscillatorModelInstance.State0Id);
            IExchangeItem stateExchangeItem1 = modelInstance.GetExchangeItem(SimpleOscillatorModelInstance.State1Id);

            // check state values
            double[] stateInBetween0 = stateExchangeItem0.ValuesAsDoubles;
            double[] stateInBetween1 = stateExchangeItem1.ValuesAsDoubles;

            Assert.AreEqual(1, stateInBetween0.Length, "#values in state");
            Assert.AreEqual(1, stateInBetween1.Length, "#values in state");
            Assert.AreEqual(-0.0189262285d, stateInBetween0[0], 1e-10, "stateInBetween[0]");
            Assert.AreEqual(0.19278554285d, stateInBetween1[0], 1e-10, "stateInBetween[1]");

            modelInstance.Compute(new Time(endTime));

            // check state values
            double[] stateValuesAtEnd0 = stateExchangeItem0.ValuesAsDoubles;
            double[] stateValuesAtEnd1 = stateExchangeItem1.ValuesAsDoubles;
            Assert.AreEqual(0.00509791929d, stateValuesAtEnd0[0], 1e-10, "stateValuesAtEnd[0]");
            Assert.AreEqual(0.00234214853d, stateValuesAtEnd1[0], 1e-10, "stateValuesAtEnd[1]");

            // assert that previous state values were a copy and are therefore unchanged
            Assert.AreEqual(-0.0189262285d, stateInBetween0[0], 1e-10, "stateValues[0]");
            Assert.AreEqual(0.19278554285d, stateInBetween1[0], 1e-10, "stateValues[1]");

            modelInstance.Finish();
        }
        public static void SetDefaultValues(IModelInstance instance)
        {
            var def = GetFormByName(instance.Name);

            foreach (var field in instance.Fields)
            {
                if (!def.DefaultValues.TryGetValue(field.Name, out var defaultValueSetter))
                {
                    continue;
                }

                var runtimeTree = FunctionFacade.BuildTree(defaultValueSetter);

                field.Value = runtimeTree.GetValue();
            }
        }
Exemplo n.º 12
0
        protected IEnumerable <FormFile> GetFiles(IModelInstance instance)
        {
            var files = new List <FormFile>();

            foreach (var field in instance.Fields)
            {
                if (field.ValueType == typeof(FormFile) && field.Value != null)
                {
                    files.Add((FormFile)field.Value);
                }
                else if (field.ValueType == typeof(IEnumerable <FormFile>) && field.Value != null)
                {
                    files.AddRange((IEnumerable <FormFile>)field.Value);
                }
            }

            return(files);
        }
Exemplo n.º 13
0
        public void RunMikeSheSimulation()
        {
            string modelConfigDir = @"c:\devel_nils\Test_5x5\Distributed\base\";
            string modelconfigOmi = "MIKESHE_WM_Test_5x5.omi";
            MikeSheOpenMIModelFactory mikeSheOpenMIModelFactory = new MikeSheOpenMIModelFactory();

            mikeSheOpenMIModelFactory.Initialize(modelConfigDir, new[] { modelconfigOmi });

            OpenDA.DotNet.OpenMI.Bridge.ModelFactory.InsertModelFactory(mikeSheOpenMIModelFactory);

            ModelFactory openDaModelFactory = new ModelFactory();

            openDaModelFactory.Initialize(null, null);

            IModelInstance modelInstance = openDaModelFactory.GetInstance(new string[] {}, outputLevel: 0);

            modelInstance.Compute(modelInstance.TimeHorizon.EndTime);
        }
Exemplo n.º 14
0
        public static IHtmlString RenderModelFields(IModelInstance instance, BaseFormBuilderRequestContext context)
        {
            var renderingMarkup = RenderingLayoutFacade.GetRenderingLayout(instance.Name);

            foreach (var field in instance.Fields.Where(f => f.Label != null))
            {
                var fieldElement = renderingMarkup.Body.Descendants().SingleOrDefault(el => el.Name == Namespaces.Xhtml + "p" && el.Value.Trim() == "%" + field.Name + "%");
                if (fieldElement == null)
                {
                    continue;
                }

                var html     = context.FormRenderer.FieldFor(context, field).ToString();
                var newValue = XElement.Parse(html);

                fieldElement.ReplaceWith(newValue);
            }

            return(new HtmlString(renderingMarkup.Body.ToString()));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RenderModel" /> class.
        /// </summary>
        /// <param name="pipeline">The pipeline.</param>
        /// <param name="modelInstance">The model instance.</param>
        /// <exception cref="System.ArgumentNullException">pipeline</exception>
        public RenderModel(RenderPipeline pipeline, IModelInstance modelInstance)
        {
            if (pipeline == null)
            {
                throw new ArgumentNullException("pipeline");
            }

            Pipeline      = pipeline;
            ModelInstance = modelInstance;
            Model         = modelInstance.Model;
            Parameters    = modelInstance.Parameters;

            var modelRendererState = Pipeline.GetOrCreateModelRendererState();
            var slotCount          = modelRendererState.ModelSlotCount;

            RenderMeshes = new List <RenderMesh> [slotCount];
            if (Model != null)
            {
                modelRendererState.PrepareRenderModel(this);
            }
        }
Exemplo n.º 16
0
        public override void Submit(IModelInstance instance)
        {
            using (var data = new DataConnection())
            {
                var templateKey = instance.Name + "." + Name;
                var template    = data.Get <IMailTemplate>().Single(t => t.Key == templateKey);
                var builder     = new FormModelMailMessageBuilder(template, instance);

                if (IncludeAttachments && instance.HasFileUpload)
                {
                    var files = GetFiles(instance);

                    AddFilesToMessage(files, builder);
                }

                using (var msg = builder.BuildMailMessage())
                {
                    MailsFacade.EnqueueMessage(msg);
                }
            }
        }
Exemplo n.º 17
0
        public static void SaveSubmit(IModelInstance instance, bool includeAttachments, DateTime utcTime)
        {
            var timeStamp = utcTime.ToString("yyyy-MM-dd HH.mm.ss", CultureInfo.InvariantCulture);
            var dir       = Path.Combine(ModelsFacade.RootPath, instance.Name, "Submits");
            var file      = Path.Combine(dir, timeStamp + ".xml");
            var xml       = GenerateBasicSubmitDocument(instance, utcTime);

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

            xml.Save(EnsureUniqueFileName(file));

            if (!includeAttachments || !instance.HasFileUpload)
            {
                return;
            }

            SaveAttachments(instance, dir, timeStamp);
        }
Exemplo n.º 18
0
        public static void SaveSubmitDebug(IModelInstance instance, HttpContextBase ctx)
        {
            var utcTime   = DateTime.UtcNow;
            var timeStamp = utcTime.ToString("yyyy-MM-dd HH.mm.ss", CultureInfo.InvariantCulture);
            var dir       = Path.Combine(ModelsFacade.RootPath, instance.Name, "Debug");
            var file      = Path.Combine(dir, timeStamp + ".xml");
            var xml       = GenerateBasicSubmitDocument(instance, utcTime);

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

            var debugData = new XElement("debug",
                                         new XElement("url", ctx.Request?.Url?.ToString()),
                                         new XElement("clientIp", ctx.Request.UserHostAddress),
                                         new XElement("ua", ctx.Request.UserAgent));

            xml.AddFirst(debugData);

            xml.Save(EnsureUniqueFileName(file));
            SaveAttachments(instance, dir, timeStamp);
        }
Exemplo n.º 19
0
        protected internal static IModelElementType GetModelElement(IDomElement domElement, IModelInstance modelInstance, string namespaceUri)
        {
            string            localName = domElement.LocalName;
            IModelElementType modelType = modelInstance.Model.GetTypeForName(namespaceUri, localName);

            if (modelType == null)
            {
                IModel model = modelInstance.Model;
                string actualNamespaceUri = model.GetActualNamespace(namespaceUri);

                if (!string.ReferenceEquals(actualNamespaceUri, null))
                {
                    modelType = GetModelElement(domElement, modelInstance, actualNamespaceUri);
                }
                else
                {
                    modelType = ((ModelInstanceImpl)modelInstance).RegisterGenericType(namespaceUri, localName);
                }
            }
            return(modelType);
        }
 public FormModelMailMessageBuilder(IMailTemplate template, IModelInstance instance) : base(template)
 {
     _instance = instance;
 }
Exemplo n.º 21
0
        public static ViewModelInstance Create(IModelContainer container, IModelSubject subject, IModelInstance instance, ViewModelInstance parentInstance, ref int nextInstanceID)
        {
            ViewModelInstance viewInstance = new ViewModelInstance()
            {
                ObjectState = instance != null ? instance.ObjectState : ObjectState.New, ContainerID = container.ContainerID, SubjectID = subject != null ? subject.SubjectID : 0, InstanceID = instance != null ? instance.InstanceID : nextInstanceID--, ParentInstanceID = parentInstance != null ? parentInstance.InstanceID : null
            };

            foreach (EAV.Model.IModelAttribute attribute in container.Attributes.OrderBy(it => it.Sequence))
            {
                viewInstance.Values.Add(ViewModelAttributeValue.Create(attribute, instance != null ? instance.Values.SingleOrDefault(it => it.AttributeID == attribute.AttributeID) : null));
            }

            foreach (IModelChildContainer childContainer in container.ChildContainers.OrderBy(it => it.Sequence))
            {
                viewInstance.ChildContainers.Add(ViewModelContainer.Create(childContainer, subject, viewInstance, ref nextInstanceID));
            }

            return(viewInstance);
        }
Exemplo n.º 22
0
 public ElementByTypeListFilter(Type type, IModelInstance modelInstance)
 {
     this.Type  = type;
     this.Model = modelInstance;
 }
Exemplo n.º 23
0
 public ModelTypeInstanceContext(IDomElement domElement, IModelInstance model, ModelElementTypeImpl modelType)
 {
     this._domElement = domElement;
     this._model      = model;
     this._modelType  = modelType;
 }
Exemplo n.º 24
0
 public ModelElementInstanceImpl(ModelTypeInstanceContext instanceContext)
 {
     this._domElement   = instanceContext.DomElement;
     this.modelInstance = instanceContext.Model;
     this._elementType  = instanceContext.ModelType;
 }
Exemplo n.º 25
0
        public static object CreateEntity(ScriptEngine engine, IModelInstance instance)
        {
            Marshaler marshaller = new Marshaler(engine);

            return(marshaller.Wrap(instance.Instance));
        }
Exemplo n.º 26
0
        public virtual IModelElementInstance NewInstance(IModelInstance modelInstance, IDomElement domElement)
        {
            ModelTypeInstanceContext modelTypeInstanceContext = new ModelTypeInstanceContext(domElement, modelInstance, this);

            return(CreateModelElementInstance(modelTypeInstanceContext));
        }
Exemplo n.º 27
0
 /// <summary>
 /// Filter a <seealso cref="NodeList"/> retaining all elements with a specific type
 ///
 /// </summary>
 /// <param name="nodeList">  the <seealso cref="NodeList"/> to filter </param>
 /// <param name="modelInstance">  the model instance </param>
 /// <param name="type">  the type class to filter for </param>
 /// <returns> the list of all Elements which match the filter </returns>
 public static IList <IDomElement> FilterNodeListByType(XmlNodeList nodeList, IModelInstance modelInstance, Type type)
 {
     return(FilterNodeList(nodeList, new ElementByTypeListFilter(type, modelInstance)));
 }
Exemplo n.º 28
0
        private void OnRenderWindowMouseDown(object sender, MouseEventArgs mouseEventArgs)
        {
            var pos          = mWindow.PointToClient(Cursor.Position);
            var intersection = new IntersectionParams(ActiveCamera.ViewInverse, ActiveCamera.ProjectionInverse,
                                                      new Vector2(pos.X, pos.Y));

            MapManager.Intersect(intersection);
            M2Manager.Intersect(intersection);
            WmoManager.Intersect(intersection);

            if (mouseEventArgs.Button == MouseButtons.Left)
            {
                IModelInstance selected = null;
                if (intersection.M2Hit)
                {
                    selected = intersection.M2Instance;
                }
                else if (intersection.WmoHit)
                {
                    selected = intersection.WmoInstance;
                }

                if (selected != mSelectedInstance)
                {
                    if (mSelectedBoundingBox != null)
                    {
                        BoundingBoxDrawManager.RemoveDrawableBox(mSelectedBoundingBox);
                    }

                    mSelectedBoundingBox = null;

                    if (mSelectedInstance != null)
                    {
                        mSelectedInstance.DestroyModelNameplate();
                    }

                    if (ModelEditManager.Instance.IsCopying && selected != ModelEditManager.Instance.SelectedModel)
                    {
                        selected             = ModelEditManager.Instance.SelectedModel;
                        mSelectedBoundingBox = BoundingBoxDrawManager.AddDrawableBox(selected.InstanceCorners);
                    }
                    else if (selected != null && selected.IsSpecial == false)
                    {
                        selected.CreateModelNameplate();
                        mSelectedBoundingBox = BoundingBoxDrawManager.AddDrawableBox(selected.InstanceCorners);
                        ModelEditManager.Instance.SelectedModel = selected;
                    }
                    else if (selected == null)
                    {
                        ModelEditManager.Instance.SelectedModel = null;
                    }

                    if (EditManager.Instance.CurrentMode != EditMode.Chunk)
                    {
                        mSelectedInstance = selected;
                        ModelSpawnManager.Instance.ClickedInstance = selected as M2RenderInstance;
                    }
                }
            }

            if (OnWorldClicked != null)
            {
                OnWorldClicked(intersection, mouseEventArgs);
            }
        }
 public override void Submit(IModelInstance instance)
 {
     SaveSubmitFacade.SaveSubmit(instance, IncludeAttachments);
 }
Exemplo n.º 30
0
        /// <summary>
        /// 从view中获取所有ModelElement实例
        /// Get a collection of all model element instances in a view
        /// </summary>
        /// <param name="view"> the collection of DOM elements to find the model element instances for </param>
        /// <param name="model"> the model of the elements </param>
        /// <returns> the collection of model element instances of the view </returns>
        public static IList <T> GetModelElementCollection <T>(IList <IDomElement> view, IModelInstance model) where T : IModelElementInstance
        {
            IList <T> resultList = new List <T>();

            foreach (IDomElement element in view)
            {
                //var t = getModelElement(element, model);
                //TODO 4.20 类型转换异常
                resultList.Add((T)GetModelElement(element, model));
            }
            return(resultList);
        }