public void Init(MyModel model, Matrix matrix, float rescaleModel = 1.0f) { Model = model; model.Rescale(rescaleModel); InstanceData.LocalMatrix = matrix; model.LoadData(); }
public ActionResult Login(LoginRegister l) { if (ModelState.IsValid) { using (MyModel db = new MyModel()) { var v = db.Users.Where(a => a.Email.Equals(l.login.Email) && a.Password.Equals(l.login.Password)).FirstOrDefault(); if (v != null) { Session["LogedUserID"] = v.UserID.ToString(); Session["LoggedUserFullname"] = v.FirstName.ToString(); return RedirectToRoute("SurveyPage"); } else { ModelState.AddModelError("Email", "Email or password is not correct"); return View(l); } } } return View(new LoginRegister { login = new Login(), users = new Users() }); }
public void ShouldRoundtripTypeWithEvent() { var model = RuntimeTypeModel.Create(); model.AutoCompile = false; model.DynamicTypeFormatting += new TypeFormatEventHandler(model_DynamicTypeFormatting); var orig = new MyModel { Type = typeof(SqlCommand) }; var clone = (MyModel)model.DeepClone(orig); Assert.AreSame(typeof(SqlCommand), clone.Type); string s = "abc"; byte[] expected = new byte[Encoding.UTF8.GetByteCount(s) + 2]; Encoding.UTF8.GetBytes(s, 0, s.Length, expected, 2); expected[0] = 0x0A; // field-header expected[1] = 0x03; // length Program.CheckBytes(orig, model, expected); model.CompileInPlace(); clone = (MyModel)model.DeepClone(orig); Assert.AreSame(typeof(SqlCommand), clone.Type); Program.CheckBytes(orig, model, expected); var compiled = model.Compile(); compiled.DynamicTypeFormatting += new TypeFormatEventHandler(model_DynamicTypeFormatting); clone = (MyModel)compiled.DeepClone(orig); Assert.AreSame(typeof(SqlCommand), clone.Type); Program.CheckBytes(orig, compiled, expected); }
public async Task TryUpdateModel_ReturnsFalse_IfBinderReturnsNull() { // Arrange var metadataProvider = new EmptyModelMetadataProvider(); var binder = new Mock<IModelBinder>(); binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>())) .Returns(Task.FromResult<ModelBindingResult>(null)); var model = new MyModel(); // Act var result = await ModelBindingHelper.TryUpdateModelAsync( model, null, Mock.Of<HttpContext>(), new ModelStateDictionary(), metadataProvider, GetCompositeBinder(binder.Object), Mock.Of<IValueProvider>(), new List<IInputFormatter>(), new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], metadataProvider), Mock.Of<IModelValidatorProvider>()); // Assert Assert.False(result); Assert.Null(model.MyProperty); }
public async Task TryUpdateModel_ReturnsFalse_IfBinderReturnsFalse() { // Arrange var metadataProvider = new Mock<IModelMetadataProvider>(); metadataProvider.Setup(m => m.GetMetadataForType(null, It.IsAny<Type>())) .Returns(new ModelMetadata(metadataProvider.Object, null, null, typeof(MyModel), null)) .Verifiable(); var binder = new Mock<IModelBinder>(); binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>())) .Returns(Task.FromResult(false)); var model = new MyModel(); // Act var result = await ModelBindingHelper.TryUpdateModelAsync( model, null, Mock.Of<HttpContext>(), new ModelStateDictionary(), metadataProvider.Object, GetCompositeBinder(binder.Object), Mock.Of<IValueProvider>(), Enumerable.Empty<IModelValidatorProvider>()); // Assert Assert.False(result); Assert.Null(model.MyProperty); metadataProvider.Verify(); }
public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails() { // Arrange var binders = new IModelBinder[] { new TypeConverterModelBinder(), new ComplexModelDtoModelBinder(), new MutableObjectModelBinder() }; var validator = new DataAnnotationsModelValidatorProvider(); var model = new MyModel(); var modelStateDictionary = new ModelStateDictionary(); var values = new Dictionary<string, object> { { "", null } }; var valueProvider = new DictionaryBasedValueProvider(values); // Act var result = await ModelBindingHelper.TryUpdateModelAsync( model, "", Mock.Of<HttpContext>(), modelStateDictionary, new DataAnnotationsModelMetadataProvider(), GetCompositeBinder(binders), valueProvider, new[] { validator }); // Assert Assert.False(result); Assert.Equal("The MyProperty field is required.", modelStateDictionary["MyProperty"].Errors[0].ErrorMessage); }
public void Start(MyModel model, MyLine line, IntersectionFlags flags = IntersectionFlags.DIRECT_TRIANGLES) { result = null; m_model = model; m_line = line; m_flags = flags; }
protected void SetModelLOD0(MyModel model) { m_ModelLOD0 = model; Flags |= MyElementFlag.EF_AABB_DIRTY; //if (GetRigidBody() != null) // MyPhysics.physicsSystem.GetRigidBodyModule().AddActiveRigid(GetRigidBody()); }
public MainViewModel() { Competition = new CompetitionVM(); MyModel myModel = new MyModel(); Competition comp = myModel.Competitions.First(); //Competition = new CompetitionVM(comp); }
public void TestCase () { var model = new MyModel (){ AnInt = 1, AString = "A", ABool = true }; var aFileName = BinaryFormatterExample.Serialize (model); var outModel = BinaryFormatterExample.Deserialize<MyModel> (aFileName); Assert.AreEqual (model, outModel); }
public void TestSetup() { backingEntity = new MockModelATableEntity(); model = new MockModelA(backingEntity); propertyManager = model.Property; // -- myBackingEntity = new MyTableEntity(); myModel = new MyModel(myBackingEntity); }
internal static void LoadModelInDrawInBackground(MyModel model) { if (MyFakes.LOAD_MODELS_IMMEDIATELY) { model.LoadInDraw(Managers.LoadingMode.Immediate); } else { m_loadingQueue.Enqueue(model); m_loadModelEvent.Set(); } }
public ParticleRenderObject(MyModel __model, bool __ShadowCaster, bool __ShadowReceiver, bool __Transparent, bool __SelfIlmn) { _model = __model; isshadowcaster = __ShadowCaster; isshadowreceiver = __ShadowReceiver; isTransparent = __Transparent; isSelfIllumination = __SelfIlmn; }
// Difference between GetIntersectionWithLine and GetIntersectionWithLineRecursive is that the later doesn't calculate // final result, but is better suited for recursive nature of octree. Don't call GetIntersectionWithLineRecursive() from // the outisde of this class, it's private method. public MyIntersectionResultLineTriangleEx? GetIntersectionWithLine(MyEntity physObject, MyModel model, ref MyLine line, float? minDistanceUntilNow, IntersectionFlags flags) { MyIntersectionResultLineTriangle? foundTriangle = GetIntersectionWithLineRecursive(model, ref line, minDistanceUntilNow); if (foundTriangle != null) { return new MyIntersectionResultLineTriangleEx(foundTriangle.Value, physObject, ref line); } else { return null; } }
public Test() { var sw = new Stopwatch(); sw.Start(); XamlReader.Load(this); sw.Stop(); Log.Write(this, "loaded in {0} seconds", sw.Elapsed.TotalSeconds); MyCheckBox.Checked = true; MyTextArea.Text = "This form was created via xaml!"; DataContext = new MyModel { SomeText = "Text from data model" }; }
public async Task StorageHelperSaveTest(StorageSerializer serializerType) { var myObject = new MyModel() { Name = "Michiel", Age = 29 }; IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local, serializerType: serializerType); await sh.SaveAsync(myObject, "myfile"); var loadedObject = await sh.LoadAsync("myfile"); Assert.AreEqual(myObject.Name, loadedObject.Name); Assert.AreEqual(myObject.Age, loadedObject.Age); await sh.DeleteAsync("myfile"); }
public async Task StorageHelperDeleteTest() { var myObject = new MyModel() { Name = "Michiel", Age = 29 }; StorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local); await sh.SaveAsync(myObject, "myfile"); //Delete saved object await sh.DeleteAsync("myfile"); var loadedObject = await sh.LoadAsync("myfile"); Assert.IsNull(loadedObject); }
protected override void InitPrefab(string displayName, Vector3 relativePosition, Matrix localOrientation, MyMwcObjectBuilder_PrefabBase objectBuilder, MyPrefabConfiguration prefabConfig) { MyMwcObjectBuilder_PrefabAlarm objectBuilderAlarm = objectBuilder as MyMwcObjectBuilder_PrefabAlarm; MyPrefabConfigurationAlarm alarmConfig = prefabConfig as MyPrefabConfigurationAlarm; m_modelLod0On = MyModels.GetModelOnlyData(alarmConfig.ModelLod0EnumOn); if (alarmConfig.ModelLod1EnumOn != null) { m_modelLod1On = MyModels.GetModelOnlyData(alarmConfig.ModelLod1EnumOn.Value); } m_modelLod0Off = m_modelLod0; m_modelLod1Off = m_modelLod1; Flags |= EntityFlags.EditableInEditor; InitLight(); }
public async Task StorageHelperDifferentSerializerTest() { var myObject = new MyModel() { Name = "Michiel", Age = 29 }; IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local); await sh.SaveAsync(myObject, "myfile"); IStorageHelper<MyModel> shXml = new StorageHelper<MyModel>(StorageType.Local, serializerType: StorageSerializer.XML); var loadedObject = await shXml.LoadAsync("myfile"); Assert.IsNull(loadedObject); await sh.DeleteAsync("myfile"); }
public ActionResult Registration(LoginRegister U) { if (ModelState.IsValid) { using (MyModel db = new MyModel()) { db.Users.Add(U.users); db.SaveChanges(); ModelState.Clear(); U = null; ViewBag.Message = "Successfully Registration Done"; return RedirectToRoute("Home"); } } return View(); }
private static List<Vector3> m_verticesBuffer = new List<Vector3>(2000); //max capacity of rendered lines public static void LoadContent() { MyMwcLog.WriteLine("MySimpleObjectDraw.LoadContent() - START"); MyMwcLog.IncreaseIndent(); m_modelBoxHiRes = MyModels.GetModelForDraw(MyModelsEnum.BoxHiRes); m_modelBoxLowRes = MyModels.GetModelForDraw(MyModelsEnum.BoxLowRes); m_modelSphere = MyModels.GetModelForDraw(MyModelsEnum.Sphere); m_modelLightSphere = MyModels.GetModelForDraw(MyModelsEnum.Sphere_low); m_modelCone = MyModels.GetModelForDraw(MyModelsEnum.Cone); m_modelHemisphere = MyModels.GetModelForDraw(MyModelsEnum.Hemisphere); m_modelHemisphereLowRes = MyModels.GetModelForDraw(MyModelsEnum.Hemisphere_low); m_modelCapsule = MyModels.GetModelForDraw(MyModelsEnum.Capsule); MyMwcLog.DecreaseIndent(); MyMwcLog.WriteLine("MySimpleObjectDraw.LoadContent() - END"); }
public void SubirArchivoAsync(MyModel model, HttpPostedFileBase inputFileId) { AsyncManager.OutstandingOperations.Increment(); AsyncManager.Sync(() => { try { if (ModelState.IsValid) { // ¡¡¡ Código para procesar archivo !!! AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = true, Message = "mensaje ok" } }; } else { AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = false, Message = this.GetHtmlModelStateErrors() } }; } } catch (Exception exception) { AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = false, Message = (exception is PortalLoadFileFailedException) ? exception.Message : "otro mensaje", CodeError = codError } }; } finally { AsyncManager.OutstandingOperations.Decrement(); } }); }
public async Task StorageHelperSaveOverwriteTest() { var myObject = new MyModel() { Name = "Michiel", Age = 29 }; StorageHelper<MyModel> sh = new StorageHelper<MyModel>(StorageType.Local); await sh.SaveAsync(myObject, "myfile"); var newObject = new MyModel() { Name = "Simon", Age = 0 }; //Save new object await sh.SaveAsync(newObject, "myfile"); var loadedObject = await sh.LoadAsync("myfile"); Assert.AreEqual(newObject.Name, loadedObject.Name); Assert.AreEqual(newObject.Age, loadedObject.Age); await sh.DeleteAsync("myfile"); }
public async Task StorageHelperSaveOverwriteTest(StorageSerializer serializerType) { var myObject = new MyModel() { Name = "Michiel", Age = 29 }; IStorageHelper<MyModel> sh = new StorageHelper<MyModel>(Windows.Storage.ApplicationData.Current.LocalFolder, serializerType: serializerType); await sh.SaveAsync(myObject, "myfile"); var newObject = new MyModel() { Name = "Simon", Age = 0 }; //Save new object await sh.SaveAsync(newObject, "myfile"); var loadedObject = await sh.LoadAsync("myfile"); Assert.AreEqual(newObject.Name, loadedObject.Name); Assert.AreEqual(newObject.Age, loadedObject.Age); await sh.DeleteAsync("myfile"); }
public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails() { // Arrange var expectedMessage = TestPlatformHelper.IsMono ? "The field MyProperty is invalid." : "The MyProperty field is required."; var binders = new IModelBinder[] { new TypeConverterModelBinder(), new ComplexModelDtoModelBinder(), new MutableObjectModelBinder() }; var validator = new DataAnnotationsModelValidatorProvider(); var model = new MyModel(); var modelStateDictionary = new ModelStateDictionary(); var values = new Dictionary<string, object> { { "", null } }; var valueProvider = new TestValueProvider(values); var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); // Act var result = await ModelBindingHelper.TryUpdateModelAsync( model, "", Mock.Of<HttpContext>(), modelStateDictionary, modelMetadataProvider, GetCompositeBinder(binders), valueProvider, new List<IInputFormatter>(), new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], modelMetadataProvider), validator); // Assert Assert.False(result); var error = Assert.Single(modelStateDictionary["MyProperty"].Errors); Assert.Equal(expectedMessage, error.ErrorMessage); }
public void BindComplexElementalModelReturnsIfOnModelUpdatingReturnsFalse() { // Arrange ControllerContext controllerContext = new Mock<ControllerContext>().Object; MyModel model = new MyModel() { ReadWriteProperty = 3 }; ModelBindingContext bindingContext = new ModelBindingContext() { ModelType = typeof(MyModel) }; Mock<DefaultModelBinderHelper> mockHelper = new Mock<DefaultModelBinderHelper>() { CallBase = true }; mockHelper.Expect(b => b.PublicOnModelUpdating(controllerContext, It.IsAny<ModelBindingContext>())).Returns(false); mockHelper.Expect(b => b.PublicGetModelProperties(controllerContext, It.IsAny<ModelBindingContext>())).Never(); mockHelper.Expect(b => b.PublicBindProperty(controllerContext, It.IsAny<ModelBindingContext>(), It.IsAny<PropertyDescriptor>())).Never(); DefaultModelBinderHelper helper = mockHelper.Object; // Act helper.BindComplexElementalModel(controllerContext, bindingContext, model); // Assert Assert.AreEqual(3, model.ReadWriteProperty, "Model should not have been updated."); mockHelper.Verify(); }
// Use this constructor to build the octree public MyModelOctree(MyModel model) { // we can't use performance timer, because octree now loaded in parallel tasks //MyPerformanceTimer.OctreeBuilding.Start(); m_model = model; // Bounding box for the root node - get it from model (we need to trust the model that it will be good) m_rootNode = new MyModelOctreeNode(model.BoundingBox); // Add model triangles into octree for (int i = 0; i < m_model.Triangles.Length; i++) { // Add triangleVertexes to octree m_rootNode.AddTriangle(model, i, 0); } // This method will look if node has all its childs null, and if yes, destroy childs array (saving memory + making traversal faster, because we don't need to traverse whole array) m_rootNode.OptimizeChilds(); // we can't use performance timer, because octree now loaded in parallel tasks //MyPerformanceTimer.OctreeBuilding.End(); }
public IActionResult NumOfClicks() { var model = new MyModel() {ClickCount = 0 }; var previousClickCount = Session[clickCountSessionKey]; if (previousClickCount != null) }
public void CustomCollectionTest() { var originalCollection = new CustomCollection <MyModel>(true) { new MyModel(), new MyModel(), new MyModel() }; var synchronizingCollection = new SynchronizingCollectionCore <MyDataModel, MyModel>( originalCollection, m => new MyDataModel(m)); AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model)); // Check add operation with collection changed event. bool handlerCalled = false; NotifyCollectionChangedEventHandler handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); Assert.AreEqual(3, e.NewStartingIndex); Assert.AreEqual(originalCollection.Last(), e.NewItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Add(new MyModel()); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Compare the collections AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model)); // Check remove operation with collection changed event. MyModel itemToRemove = originalCollection[2]; handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action); Assert.AreEqual(2, e.OldStartingIndex); Assert.AreEqual(itemToRemove, e.OldItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Remove(itemToRemove); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Check replace operation with collection changed event. MyModel itemToReplace = originalCollection[1]; int handlerCalledCount = 0; handler = (sender, e) => { Assert.AreEqual(synchronizingCollection, sender); if (handlerCalledCount == 0) { Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action); Assert.AreEqual(itemToReplace, e.OldItems.Cast <MyDataModel>().Single().Model); } else { Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); Assert.AreEqual(originalCollection[1], e.NewItems.Cast <MyDataModel>().Single().Model); } handlerCalledCount++; }; synchronizingCollection.CollectionChanged += handler; originalCollection[1] = new MyModel(); synchronizingCollection.CollectionChanged -= handler; Assert.AreEqual(2, handlerCalledCount); // Check reset operation with collection changed event. var newItems = new List <MyModel>() { new MyModel(), new MyModel() }; handlerCalledCount = 0; handler = (sender, e) => { Assert.AreEqual(synchronizingCollection, sender); if (handlerCalledCount == 0) { Assert.AreEqual(NotifyCollectionChangedAction.Reset, e.Action); } else { Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); } handlerCalledCount++; }; synchronizingCollection.CollectionChanged += handler; originalCollection.Reset(newItems); synchronizingCollection.CollectionChanged -= handler; Assert.AreEqual(3, handlerCalledCount); AssertHelper.SequenceEqual(newItems, synchronizingCollection.Select(dm => dm.Model)); }
private readonly MyModel _mm; // Implements IDisposable, so we need to clean it up when done public HomeController() { _mm = new MyModel(); }
public ActionResult GridViewPartial() { var model = MyModel.GetModelList(); return(PartialView("_GridViewPartial", model)); }
public ActionResult MyView() { var myModel = new MyModel(true); return(View(myModel)); }
public static List <MyCubeBlockDefinition.MountPoint> AutogenerateMountpoints(MyModel model, float gridSize) { var shapes = model.HavokCollisionShapes; if (shapes == null) { if (model.HavokBreakableShapes == null) { return(new List <MyCubeBlockDefinition.MountPoint>()); } shapes = new HkShape[] { model.HavokBreakableShapes[0].GetShape() }; } return(AutogenerateMountpoints(shapes, gridSize)); }
public override void RecreateControls(bool constructor) { base.RecreateControls(constructor); m_currentPosition = -m_size.Value / 2.0f + new Vector2(0.02f, 0.10f); m_currentPosition.Y += 0.01f; m_scale = 0.7f; AddCaption("Render Model FX", Color.Yellow.ToVector4()); AddShareFocusHint(); //if (MySession.Static.ControlledObject == null) //return; AddButton(new StringBuilder("Reload textures"), delegate { VRageRender.MyRenderProxy.ReloadTextures(); }); //Line line = new Line(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 10); //var res = MyEntities.GetIntersectionWithLine(ref line, null, null); //if (!res.HasValue) // return; ////MyModel model = MySession.Static.ControlledObject.ModelLod0; //m_model = res.Value.Entity.ModelLod0; m_modelsCombo = AddCombo(); var modelList = VRage.Game.Models.MyModels.GetLoadedModels(); if (modelList.Count == 0) { return; } for (int i = 0; i < modelList.Count; i++) { var model = modelList[i]; m_modelsCombo.AddItem((int)i, new StringBuilder(System.IO.Path.GetFileNameWithoutExtension(model.AssetName))); } m_modelsCombo.SelectItemByIndex(m_currentModelSelectedItem); m_modelsCombo.ItemSelected += new MyGuiControlCombobox.ItemSelectedDelegate(modelsCombo_OnSelect); m_model = modelList[m_currentModelSelectedItem]; if (m_model == null) { return; } m_meshesCombo = AddCombo(); for (int i = 0; i < m_model.GetMeshList().Count; i++) { var mesh = m_model.GetMeshList()[i]; m_meshesCombo.AddItem((int)i, new StringBuilder(mesh.Material.Name)); } m_meshesCombo.SelectItemByIndex(m_currentSelectedMeshItem); m_meshesCombo.ItemSelected += new MyGuiControlCombobox.ItemSelectedDelegate(meshesCombo_OnSelect); if (MySector.MainCamera != null) { m_voxelsCombo = AddCombo(); m_voxelsCombo.AddItem(-1, new StringBuilder("None")); int i = 0; foreach (var voxelMaterial in MyDefinitionManager.Static.GetVoxelMaterialDefinitions()) { m_voxelsCombo.AddItem(i++, new StringBuilder(voxelMaterial.Id.SubtypeName)); } m_voxelsCombo.SelectItemByIndex(m_currentSelectedVoxelItem + 1); m_voxelsCombo.ItemSelected += new MyGuiControlCombobox.ItemSelectedDelegate(voxelsCombo_OnSelect); } if (m_model.GetMeshList().Count <= m_currentSelectedMeshItem) { return; } var selectedMesh = m_model.GetMeshList()[m_currentSelectedMeshItem]; var selectedMaterial = selectedMesh.Material; m_diffuseColor = AddColor(new StringBuilder("Diffuse"), selectedMaterial, MemberHelper.GetMember(() => selectedMaterial.DiffuseColor)); m_specularIntensity = AddSlider("Specular intensity", selectedMaterial.SpecularIntensity, 0, 32, null); m_specularPower = AddSlider("Specular power", selectedMaterial.SpecularPower, 0, 128, null); }
/// <summary> /// Returns true if the given small block connects to large one. One of the given AABB's is inflated with 0.05 to reduce inaccuracies. /// </summary> /// <param name="smallBlock">small block</param> /// <param name="smallBlockWorldAabb">small block world AABB</param> /// <param name="largeBlock">large block</param> /// <param name="largeBlockWorldAabb">large block wotld AABB</param> /// <returns>true when connected</returns> private bool SmallBlockConnectsToLarge(MySlimBlock smallBlock, ref BoundingBoxD smallBlockWorldAabb, MySlimBlock largeBlock, ref BoundingBoxD largeBlockWorldAabb) { Debug.Assert(GetCubeSize(smallBlock) == MyCubeSize.Small); Debug.Assert(GetCubeSize(largeBlock) == MyCubeSize.Large); Debug.Assert(!(smallBlock.FatBlock is MyCompoundCubeBlock)); Debug.Assert(!(largeBlock.FatBlock is MyCompoundCubeBlock)); BoundingBoxD smallBlockWorldAabbReduced = smallBlockWorldAabb; smallBlockWorldAabbReduced.Inflate(-smallBlock.CubeGrid.GridSize / 4); // Small block aabb penetrates large block aabb (large timbers). bool penetratesAabbs = largeBlockWorldAabb.Intersects(smallBlockWorldAabbReduced); if (!penetratesAabbs) { Vector3I addDir = GetSmallBlockAddDirection(ref smallBlockWorldAabb, ref smallBlockWorldAabbReduced, ref largeBlockWorldAabb); // Check small grid mount points Quaternion smallBlockRotation; smallBlock.Orientation.GetQuaternion(out smallBlockRotation); smallBlockRotation = Quaternion.CreateFromRotationMatrix(smallBlock.CubeGrid.WorldMatrix) * smallBlockRotation; if (!MyCubeGrid.CheckConnectivitySmallBlockToLargeGrid(largeBlock.CubeGrid, smallBlock.BlockDefinition, ref smallBlockRotation, ref addDir)) { return(false); } } BoundingBoxD smallBlockWorldAabbInflated = smallBlockWorldAabb; smallBlockWorldAabbInflated.Inflate(2 * smallBlock.CubeGrid.GridSize / 3); // Trim small block aabb with large block aabb. BoundingBoxD intersectedBox = smallBlockWorldAabbInflated.Intersect(largeBlockWorldAabb); Vector3D intersectedBoxCenter = intersectedBox.Center; HkShape shape = new HkBoxShape((Vector3)intersectedBox.HalfExtents); Quaternion largeRotation; largeBlock.Orientation.GetQuaternion(out largeRotation); largeRotation = Quaternion.CreateFromRotationMatrix(largeBlock.CubeGrid.WorldMatrix) * largeRotation; Vector3D largeTranslation; largeBlock.ComputeWorldCenter(out largeTranslation); bool result = false; try { if (largeBlock.FatBlock != null) { MyModel model = largeBlock.FatBlock.Model; if (model != null) { HkShape[] shapes = model.HavokCollisionShapes; if (shapes == null || shapes.Length == 0) { return(false); } for (int i = 0; i < shapes.Length; ++i) { result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapes[i], ref largeTranslation, ref largeRotation); if (result) { break; } } } else { HkShape shapeLarge = new HkBoxShape(largeBlock.BlockDefinition.Size * largeBlock.CubeGrid.GridSize / 2); result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapeLarge, ref largeTranslation, ref largeRotation); shapeLarge.RemoveReference(); } } else { HkShape shapeLarge = new HkBoxShape(largeBlock.BlockDefinition.Size * largeBlock.CubeGrid.GridSize / 2); result = MyPhysics.IsPenetratingShapeShape(shape, ref intersectedBoxCenter, ref Quaternion.Identity, shapeLarge, ref largeTranslation, ref largeRotation); shapeLarge.RemoveReference(); } } finally { shape.RemoveReference(); } return(result); }
public ActionResult Create(MyModel model) { // do something }
public RemoveItemsProductController(MyModel <Product> products) { _products = products; }
void LoadModel(MyModel model, Matrix modelWorld, float modelScale) { Matrix world = modelWorld * Matrix.CreateScale(modelScale); m_minCoord = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); m_maxCoord = new Vector3(float.MinValue, float.MinValue, float.MinValue); MyTriangleVertexIndices[] triangles = model.Triangles; m_triangles = new List<MyImportTriangle>(triangles.Length); for (int i = 0; i < triangles.Length; i++) { Vector3 vertex0 = Vector3.Transform(model.GetVertex(triangles[i].I0), world); Vector3 vertex1 = Vector3.Transform(model.GetVertex(triangles[i].I1), world); Vector3 vertex2 = Vector3.Transform(model.GetVertex(triangles[i].I2), world); MyImportTriangle triangle = new MyImportTriangle(vertex0, vertex1, vertex2); // Ignore triangles that lie in XZ plane if (triangle.Normal.Y != 0) { m_triangles.Add(triangle); CheckMinMaxCoords(vertex0); CheckMinMaxCoords(vertex1); CheckMinMaxCoords(vertex2); } } }
/// <summary> /// Adds environment item to internal collections. Creates render and physics data. /// </summary> /// <returns>True if successfully added, otherwise false.</returns> private bool AddItem(MyEnvironmentItemDefinition itemDefinition, ref MatrixD worldMatrix, ref BoundingBoxD aabbWorld, HkStaticCompoundShape sectorRootShape, Dictionary <MyStringId, HkShape> subtypeIdToShape) { if (!MyFakes.ENABLE_ENVIRONMENT_ITEMS) { return(true); } Debug.Assert(m_definition.ContainsItemDefinition(itemDefinition), String.Format("Environment item with definition '{0}' not found in class '{1}'", itemDefinition.Id, m_definition.Id)); if (!m_definition.ContainsItemDefinition(itemDefinition)) { return(false); } //MyDefinitionId defId = new MyDefinitionId(envItemObjectBuilderType, subtypeId.ToString()); MyModel model = MyModels.GetModelOnlyData(itemDefinition.Model); if (model == null) { //Debug.Fail(String.Format("Environment item model of '{0}' not found, skipping the item...", itemDefinition.Id)); return(false); } int localId = worldMatrix.Translation.GetHashCode(); MyEnvironmentItemData data = new MyEnvironmentItemData() { Id = localId, SubtypeId = itemDefinition.Id.SubtypeId, Transform = new MyTransformD(ref worldMatrix), Enabled = true, SectorInstanceId = -1 }; //Preload split planes //VRageRender.MyRenderProxy.PreloadMaterials(model.AssetName); aabbWorld.Include(model.BoundingBox.Transform(worldMatrix)); CheckModelConsistency(itemDefinition); MatrixD transform = data.Transform.TransformMatrix; Vector3I sectorId = MyEnvironmentSector.GetSectorId(transform.Translation, m_definition.SectorSize); MyEnvironmentSector sector; if (!m_sectors.TryGetValue(sectorId, out sector)) { sector = new MyEnvironmentSector(sectorId); m_sectors.Add(sectorId, sector); } // Adds instance of the given model. Local matrix specified might be changed internally in renderer. Matrix transformL = (Matrix)transform; data.SectorInstanceId = sector.AddInstance(itemDefinition.Id.SubtypeId, ref transformL, model.BoundingBox, m_instanceFlags, m_definition.MaxViewDistance); int physicsShapeInstanceId; if (AddPhysicsShape(data.SubtypeId, model, ref transform, sectorId, sectorRootShape, subtypeIdToShape, out physicsShapeInstanceId)) { // Map to data index - note that itemData is added after this to its list! m_physicsShapeInstanceIdToLocalId[physicsShapeInstanceId] = localId; m_localIdToPhysicsShapeInstanceId[localId] = physicsShapeInstanceId; } data.Transform = new MyTransformD(transform); if (m_itemsData.ContainsKey(localId)) { Debug.Fail("More items on same place! " + transform.Translation.ToString()); } else { m_itemsData.Add(localId, data); } return(true); }
public MyModelViewModel() { model = new MyModel(); Start = InnerStart; CurrentOperationLabel = model.CurrentOperation; }
public IActionResult Person([Bind("Age,Name")] MyModel model) { return(new JsonResult(model)); }
public void ObservableCollectionTest() { var originalCollection = new ObservableCollection <MyModel>() { new MyModel(), new MyModel(), new MyModel() }; var synchronizingCollection = new SynchronizingCollectionCore <MyDataModel, MyModel>(originalCollection, m => new MyDataModel(m)); AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model)); // Check add operation with collection changed event. bool handlerCalled = false; NotifyCollectionChangedEventHandler handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); Assert.AreEqual(3, e.NewStartingIndex); Assert.AreEqual(originalCollection.Last(), e.NewItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Add(new MyModel()); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Check insert at index 0 operation with collection changed event. handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action); Assert.AreEqual(0, e.NewStartingIndex); Assert.AreEqual(originalCollection.First(), e.NewItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Insert(0, new MyModel()); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Compare the collections AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model)); // Check remove operation with collection changed event. MyModel itemToRemove = originalCollection[2]; handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action); Assert.AreEqual(2, e.OldStartingIndex); Assert.AreEqual(itemToRemove, e.OldItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Remove(itemToRemove); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Check replace operation with collection changed event. MyModel itemToReplace = originalCollection[1]; handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Replace, e.Action); Assert.AreEqual(1, e.NewStartingIndex); Assert.AreEqual(1, e.OldStartingIndex); Assert.AreEqual(originalCollection[1], e.NewItems.Cast <MyDataModel>().Single().Model); Assert.AreEqual(itemToReplace, e.OldItems.Cast <MyDataModel>().Single().Model); }; synchronizingCollection.CollectionChanged += handler; originalCollection[1] = new MyModel(); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Check move operation with collection changed event. handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Move, e.Action); Assert.AreEqual(0, e.OldStartingIndex); Assert.AreEqual(2, e.NewStartingIndex); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Move(0, 2); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); // Check clear operation with collection changed event. handlerCalled = false; handler = (sender, e) => { handlerCalled = true; Assert.AreEqual(synchronizingCollection, sender); Assert.AreEqual(NotifyCollectionChangedAction.Reset, e.Action); }; synchronizingCollection.CollectionChanged += handler; originalCollection.Clear(); synchronizingCollection.CollectionChanged -= handler; Assert.IsTrue(handlerCalled); Assert.IsFalse(synchronizingCollection.Any()); }
public ActionResult Index() { return(View(MyModel.getModels())); }
public MyDataModel(MyModel model) { Model = model; }
private async void LoadButton(object sender, RoutedEventArgs e) { _model = await _repo.GetByIdAsync(_model.GetId()); InfoTextBlock.Text = "Inhalt: " + JsonConvert.SerializeObject(_model); }
public ActionResult VersionControl(string VersionControl, string Oper, string Version, string ChartData) { if (VersionControl == "DownloadVersion") { var UploadExcelFile = (from uef in db.UploadFiles where uef.CompanyName == UserData.CompanyName && uef.UserId == UserData.UserName select uef).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); string ServerMapPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Upload/" + UploadExcelFile.JSONFileName); var filePath = new FileInfo(ServerMapPath); using (ExcelPackage workbook = new ExcelPackage(filePath)) { // Generate a new unique identifier against which the file can be stored string handle = Guid.NewGuid().ToString(); using (MemoryStream memoryStream = new MemoryStream()) { workbook.SaveAs(memoryStream); memoryStream.Position = 0; TempData[handle] = memoryStream.ToArray(); } // Note we are returning a filename as well as the handle return(new JsonResult() { Data = new { FileGuid = handle, FileName = "TestReportOutput.xlsx" } }); } } else if (VersionControl == "SaveVersion") { var UploadExcelFile = (from uef in db.UploadFiles where uef.CompanyName == UserData.CompanyName select uef).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); string ServerMapPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Download/" + UploadExcelFile.JSONFileName); using (StreamReader reader = new StreamReader(ServerMapPath)) { string jsonData = reader.ReadToEnd(); dynamic lstDynamic = JsonConvert.DeserializeObject(jsonData); foreach (var item in lstDynamic.data) { } } } MyLastAction myla = GetUserCurrentAction(); var viewModel = new MyModel { UseDate = DateTime.Now, ShowLevel = myla.ShowLevel, Levels = myla.Levels, Version = myla.Version, Oper = myla.Oper, View = myla.View, Country = myla.Country, ChartData = GetOrgChartData(myla.Role, myla.Country, myla.ShowLevel, myla.Levels, myla.Oper, myla.Version), Role = myla.Role }; return(View("Index", viewModel)); }
public ActionResult MyView(MyModel myModel) { myModel.RefreshReport(); return(View(myModel)); }
public void Init(MyModel model, Matrix matrix) { Model = model; InstanceData.LocalMatrix = matrix; model.LoadData(); }
protected static void AddFastBuildModelWithSubparts(ref MatrixD matrix, List <MatrixD> matrices, List <string> models, MyCubeBlockDefinition blockDefinition) { if (string.IsNullOrEmpty(blockDefinition.Model)) { return; } matrices.Add(matrix); models.Add(blockDefinition.Model); var data = new MyEntitySubpart.Data(); MyCubeBlockDefinition subBlockDefinition; MatrixD subBlockMatrix; Vector3 dummyPosition; MyModel modelData = VRage.Game.Models.MyModels.GetModelOnlyData(blockDefinition.Model); foreach (var dummy in modelData.Dummies) { if (MyEntitySubpart.GetSubpartFromDummy(blockDefinition.Model, dummy.Key, dummy.Value, ref data)) { MatrixD mCopy = MatrixD.Multiply(data.InitialTransform, matrix); matrices.Add(mCopy); models.Add(data.File); } else if (MyFakes.ENABLE_SUBBLOCKS && MyCubeBlock.GetSubBlockDataFromDummy(blockDefinition, dummy.Key, dummy.Value, false, out subBlockDefinition, out subBlockMatrix, out dummyPosition)) { if (!string.IsNullOrEmpty(subBlockDefinition.Model)) { // Repair subblock matrix to have int axes (because preview renderer does not allow such non integer rotation). Vector3I forward = Vector3I.Round(Vector3.DominantAxisProjection(subBlockMatrix.Forward)); Vector3I invForward = Vector3I.One - Vector3I.Abs(forward); Vector3I right = Vector3I.Round(Vector3.DominantAxisProjection((Vector3)subBlockMatrix.Right * invForward)); Vector3I up; Vector3I.Cross(ref right, ref forward, out up); subBlockMatrix.Forward = forward; subBlockMatrix.Right = right; subBlockMatrix.Up = up; MatrixD mCopy = MatrixD.Multiply(subBlockMatrix, matrix); matrices.Add(mCopy); models.Add(subBlockDefinition.Model); } } } // Precache models for generated blocks if (MyFakes.ENABLE_GENERATED_BLOCKS && !blockDefinition.IsGeneratedBlock && blockDefinition.GeneratedBlockDefinitions != null) { foreach (var generatedBlockDefId in blockDefinition.GeneratedBlockDefinitions) { MyCubeBlockDefinition generatedBlockDef; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(generatedBlockDefId, out generatedBlockDef)) { VRage.Game.Models.MyModels.GetModelOnlyData(generatedBlockDef.Model); } } } }
public ActionResult MakeOrder([ModelBinder(typeof(MyEditorsBinder))] MyModel order) { ViewData["Message"] = String.Format("Your order is ready, {0}: {1}.", order.Name, order.Meal); return(View("Index", order)); }
protected override bool Interact(bool staticCollision) { try { if (!staticCollision) { TestsCount++; MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("BoxTriangleIntersection"); } if (RBElement1.GetElementType() != MyRBElementType.ET_BOX) { SwapElements(); } var boxElement = (MyRBBoxElement)RBElement1; var triangleMeshElem = (MyRBTriangleMeshElement)RBElement2; MyModel model = ((boxElement.Flags & MyElementFlag.EF_MODEL_PREFER_LOD0) > 0 ? triangleMeshElem.ModelLOD0 : triangleMeshElem.Model); Matrix boxMatrix = boxElement.GetGlobalTransformation(); Matrix triangleMeshMatrix = triangleMeshElem.GetGlobalTransformation(); Matrix newMatrix = boxMatrix; if (!staticCollision) { // MyPhysics.physicsSystem.GetRigidBodyModule().CurrentTimeStep newMatrix.Translation = newMatrix.Translation + boxElement.GetRigidBody().LinearVelocity *MyPhysics.physicsSystem.GetRigidBodyModule().CurrentTimeStep; } MyBox oldBox = m_tempBox1; MyBox newBox = m_tempBox2; oldBox.Transform.Orientation = boxMatrix; oldBox.Transform.Orientation.Translation = Vector3.Zero; oldBox.Transform.Position = boxMatrix.Translation - Vector3.TransformNormal(boxElement.Size * 0.5f, boxMatrix); newBox.Transform.Orientation = newMatrix; newBox.Transform.Orientation.Translation = Vector3.Zero; newBox.Transform.Position = newMatrix.Translation - Vector3.TransformNormal(boxElement.Size * 0.5f, newMatrix); oldBox.SideLengths = boxElement.Size; newBox.SideLengths = boxElement.Size; float boxRadius = newBox.GetBoundingRadiusAroundCentre(); #region REFERENCE: Vector3 boxCentre = newBox.GetCentre(); Vector3 boxCentre; newBox.GetCentre(out boxCentre); // Deano need to trasnform the box center into mesh space Matrix invTransformMatrix = Matrix.Invert(triangleMeshMatrix); Vector3.Transform(ref boxCentre, ref invTransformMatrix, out boxCentre); #endregion BoundingBox bb = boxElement.GetWorldSpaceAABB(); if (staticCollision) { Vector3 bbMin = Vector3.Transform(bb.Min, invTransformMatrix); Vector3 bbMax = Vector3.Transform(bb.Max, invTransformMatrix); BoundingSphere bs = new BoundingSphere((bbMax + bbMin) / 2, Vector3.Distance(bbMin, bbMax)); List <MyTriangle_Vertex_Normal> triangles = MyPhysics.physicsSystem.GetContactConstraintModule().GetTriangleCache().GetFreeTriangleList(this); model.GetTrianglePruningStructure().GetTrianglesIntersectingSphere(ref bs, triangles, triangles.Capacity); for (int iTriangle = 0; iTriangle < triangles.Count; iTriangle++) { MyTriangle_Vertex_Normal triangle = triangles[iTriangle]; MyPlane plane = new MyPlane(ref triangle.Vertexes); // quick early test is done in mesh space float dist = MyUtils.GetDistanceFromPointToPlane(ref boxCentre, ref plane); if (dist > boxRadius || dist < -boxRadius) { continue; } Vector3 oldPos = boxMatrix.Translation; Vector3 newPos = newMatrix.Translation; float collisionEpsilon = 0;//pz to test not sure about value if (DoOverlapBoxTriangleStaticTest( oldBox, newBox, triangle, plane, collisionEpsilon, ref triangleMeshMatrix, ref oldPos, ref newPos)) { return(true); } } return(false); } else { bb.Min += boxElement.GetRigidBody().LinearVelocity *MyPhysics.physicsSystem.GetRigidBodyModule().CurrentTimeStep; bb.Max += boxElement.GetRigidBody().LinearVelocity *MyPhysics.physicsSystem.GetRigidBodyModule().CurrentTimeStep; var boxCenter = bb.GetCenter(); // aabox is done in mesh space and handles the mesh transform correctly //int numTriangles = mesh.GetTrianglesIntersectingtAABox(potentialTriangles, MaxLocalStackTris, ref bb); //boxElement.GetRigidBody().Position = Vector3.Zero; //triangleMeshElem.GetRigidBody().Position = Vector3.Zero; //BoundingSphere bs = new BoundingSphere((bbMax + bbMin) / 2, Vector3.Distance(bbMin, bbMax)); var halfSize = bb.Size() / 2; BoundingBox bb2 = new BoundingBox(boxCentre - halfSize, boxCentre + halfSize); List <MyTriangle_Vertex_Normal> triangles = MyPhysics.physicsSystem.GetContactConstraintModule().GetTriangleCache().GetFreeTriangleList(this); MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("PruningStructure"); model.GetTrianglePruningStructure().GetTrianglesIntersectingAABB(ref bb2, triangles, triangles.Capacity); //model.GetTrianglePruningStructure().GetTrianglesIntersectingSphere(ref bs, triangles, triangles.Capacity); MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().ProfileCustomValue("Tests count ", TestsCount); MySmallCollPointInfo[] collPtArray = MyContactInfoCache.SCPIStackAlloc(); int refPointer = 0; m_collPoints.Clear(); MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Triangles"); for (int iTriangle = 0; iTriangle < triangles.Count; iTriangle++) { MyTriangle_Vertex_Normal triangle = triangles[iTriangle]; //IndexedTriangle meshTriangle = mesh.GetTriangle(potentialTriangles[iTriangle]); MyPlane plane = new MyPlane(ref triangle.Vertexes); // quick early test is done in mesh space //float dist = meshTriangle.Plane.DotCoordinate(boxCentre); float dist = MyUtils.GetDistanceFromPointToPlane(ref boxCentre, ref plane); if (dist > boxRadius || dist < -boxRadius) { continue; } Vector3 oldPos = boxMatrix.Translation; Vector3 newPos = newMatrix.Translation; DoOverlapBoxTriangleTest( oldBox, newBox, triangle, plane, MyPhysics.physicsSystem.GetRigidBodyModule().CollisionEpsilon, ref triangleMeshMatrix, ref oldPos, ref newPos, m_collPoints); } MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); TrianglesTested += triangles.Count; MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().ProfileCustomValue("Triangles tested ", TrianglesTested); m_collPoints.Sort(m_colPointComparer); refPointer = 0; foreach (MyCollisionPointStruct collPoint in m_collPoints) { collPtArray[refPointer] = collPoint.CollPointInfo; refPointer++; if (refPointer >= MyPhysicsConfig.MaxContactPoints) { break; } } if (refPointer > 0) { MyPhysics.physicsSystem.GetContactConstraintModule().AddContactConstraint(this, collPtArray, refPointer); } MyContactInfoCache.FreeStackAlloc(collPtArray); MyPhysics.physicsSystem.GetContactConstraintModule().GetTriangleCache().PushBackTriangleList(triangles); } } catch { throw; } finally { if (!staticCollision) { MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); } } return(false); }
public void BindModel() { // Arrange ControllerContext controllerContext = new ControllerContext(); MyModel model = new MyModel(); ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType( () => model, typeof(MyModel) ); ComplexModelDto dto = new ComplexModelDto(modelMetadata, modelMetadata.Properties); Mock <IExtensibleModelBinder> mockStringBinder = new Mock <IExtensibleModelBinder>(); mockStringBinder .Setup( b => b.BindModel(controllerContext, It.IsAny <ExtensibleModelBindingContext>()) ) .Returns( delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) { Assert.Equal(typeof(string), mbc.ModelType); Assert.Equal("theModel.StringProperty", mbc.ModelName); mbc.ValidationNode = new ModelValidationNode( mbc.ModelMetadata, "theModel.StringProperty" ); mbc.Model = "someStringValue"; return(true); } ); Mock <IExtensibleModelBinder> mockIntBinder = new Mock <IExtensibleModelBinder>(); mockIntBinder .Setup( b => b.BindModel(controllerContext, It.IsAny <ExtensibleModelBindingContext>()) ) .Returns( delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) { Assert.Equal(typeof(int), mbc.ModelType); Assert.Equal("theModel.IntProperty", mbc.ModelName); mbc.ValidationNode = new ModelValidationNode( mbc.ModelMetadata, "theModel.IntProperty" ); mbc.Model = 42; return(true); } ); Mock <IExtensibleModelBinder> mockDateTimeBinder = new Mock <IExtensibleModelBinder>(); mockDateTimeBinder .Setup( b => b.BindModel(controllerContext, It.IsAny <ExtensibleModelBindingContext>()) ) .Returns( delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) { Assert.Equal(typeof(DateTime), mbc.ModelType); Assert.Equal("theModel.DateTimeProperty", mbc.ModelName); return(false); } ); ModelBinderProviderCollection binders = new ModelBinderProviderCollection(); binders.RegisterBinderForType( typeof(string), mockStringBinder.Object, true /* suppressPrefixCheck */ ); binders.RegisterBinderForType( typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */ ); binders.RegisterBinderForType( typeof(DateTime), mockDateTimeBinder.Object, true /* suppressPrefixCheck */ ); ExtensibleModelBindingContext parentBindingContext = new ExtensibleModelBindingContext { ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType( () => dto, typeof(ComplexModelDto) ), ModelName = "theModel", ModelBinderProviders = binders }; ComplexModelDtoModelBinder binder = new ComplexModelDtoModelBinder(); // Act bool retVal = binder.BindModel(controllerContext, parentBindingContext); // Assert Assert.True(retVal); Assert.Equal(dto, parentBindingContext.Model); ComplexModelDtoResult stringDtoResult = dto.Results[ dto.PropertyMetadata.Where(m => m.ModelType == typeof(string)).First() ]; Assert.Equal("someStringValue", stringDtoResult.Model); Assert.Equal("theModel.StringProperty", stringDtoResult.ValidationNode.ModelStateKey); ComplexModelDtoResult intDtoResult = dto.Results[ dto.PropertyMetadata.Where(m => m.ModelType == typeof(int)).First() ]; Assert.Equal(42, intDtoResult.Model); Assert.Equal("theModel.IntProperty", intDtoResult.ValidationNode.ModelStateKey); ComplexModelDtoResult dateTimeDtoResult = dto.Results[ dto.PropertyMetadata.Where(m => m.ModelType == typeof(DateTime)).First() ]; Assert.Null(dateTimeDtoResult); }
public ActionResult UpdateTable() { int iShowCount = 0, iNullCount = 0, iKey = 0; List <string> lstParentName = new List <string>(); List <dynamic> lstDynamic = new List <dynamic>(); var UploadExcelFile = (from uef in db.UploadFiles where uef.CompanyName == UserData.CompanyName select uef).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); string ServerMapPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Uploads/" + UploadExcelFile.JSONFileName); using (StreamReader reader = new StreamReader(ServerMapPath)) { string SUP_DISPLAY_NAME = UploadExcelFile.ParentField; string RNUM = UploadExcelFile.FirstPositionField; string SNUM = ""; string jsonData = reader.ReadToEnd(); dynamic array = JsonConvert.DeserializeObject(jsonData); foreach (var item in array.data) { if (item[SUP_DISPLAY_NAME] != null) { iShowCount++; } if (item[SUP_DISPLAY_NAME] == null) { iNullCount++; } if (UploadExcelFile.SerialNoFlag == "Y") { SNUM = (100000 + Convert.ToInt32(item[RNUM])).ToString(); } else { SNUM = (100000 + iKey++).ToString(); } if (item[SUP_DISPLAY_NAME] != null) { if (lstParentName.Count() >= 1) { var match = lstParentName.FirstOrDefault(stringToCheck => stringToCheck.Contains(item[SUP_DISPLAY_NAME].ToString().Trim())); if (match == null) { lstParentName.Add(item[SUP_DISPLAY_NAME].ToString().Trim()); } } else { lstParentName.Add(item[SUP_DISPLAY_NAME].ToString().Trim()); } } // Employee Details if (UploadExcelFile.UseFields != "") { string FULL_NAME = ""; if (UploadExcelFile.FullNameFields != "") { string[] FN = UploadExcelFile.FullNameFields.Split(','); foreach (string strFN in FN) { FULL_NAME += " " + item[strFN]; } } dynamic DyObj = new ExpandoObject(); string[] UF = UploadExcelFile.UseFields.Split(','); foreach (string strUF in UF) { string strField = strUF.Trim().ToUpper().Replace(" ", "_"); if (strField == "LEVEL_ID") { AddProperty(DyObj, strField, SNUM); } else if (strField == "PARENT_LEVEL_ID") { AddProperty(DyObj, strField, "999999"); } else if (strField == "VERSION") { AddProperty(DyObj, strField, "1"); } else if (strField == "FULL_NAME") { AddProperty(DyObj, strField, (FULL_NAME == "") ? "" : FULL_NAME.Substring(1)); } else if (strField == "DATE_UPDATED") { AddProperty(DyObj, strField, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")); } else if (strField == "USER_ID") { AddProperty(DyObj, strField, UserData.CompanyName); } else { AddProperty(DyObj, strField, ((item[strUF] == null)?"":item[strUF])); } } lstDynamic.Add(DyObj); } } // Gets the Parent name int Index = 0; foreach (string pn in lstParentName) { ExpandoObject ObjId = lstDynamic.Where(Obj => Obj.FULL_NAME == pn).FirstOrDefault(); if (ObjId != null) { var expandoLEVEL_ID = (IDictionary <string, object>)ObjId; Index++; var Objects = lstDynamic.Where(Obj => Obj.SUP_DISPLAY_NAME == pn).ToList(); foreach (ExpandoObject md in Objects) { var expandoPARENT_ID = (IDictionary <string, object>)md; expandoPARENT_ID["PARENT_LEVEL_ID"] = expandoLEVEL_ID["LEVEL_ID"].ToString(); } } } } // Insert the data into SQL table InsertDynamicDataToDB(lstDynamic); MyLastAction myla = GetUserCurrentAction(); var viewModel = new MyModel { UseDate = DateTime.Now, ShowLevel = myla.ShowLevel, Levels = myla.Levels, Version = myla.Version, Oper = myla.Oper, View = myla.View, Country = myla.Country, ChartData = GetOrgChartData(myla.Role, myla.Country, myla.ShowLevel, myla.Levels, myla.Oper, myla.Version), Role = myla.Role }; return(View("Index", viewModel)); }
/// <summary> /// A method for removing a certain amount of an item from an item already in stock. /// </summary> /// <param name="products"></param> /// <param name="countItemsOfWarehouse"></param> #region Remove items product public void RemoveItems(MyModel <Product> products, ref int countItemsOfWarehouse) { // The logic of this method is the same as for the method // of adding the quantity of goods to the warehouse. if (products.Products.Count > 0) { Console.WriteLine("Enter a product name to reduce the number of items in warehouse: "); string nameItemAdd = Console.ReadLine(); int countAdd = 0; bool flag = false; for (int index = 0; index < products.Products.Count; index++) { if (nameItemAdd == products.Products[index].Name) { while (true) { Console.WriteLine("Enter the number of items to remove: "); countAdd = EnterCountRemove(); if ((products.Products[index].Count - countAdd) < 0) { Console.Clear(); Console.WriteLine($"There can be no {products.Products[index].Name} less than zero in the warehouse.\nEnter a number from 1 to {products.Products[index].Count}: "); continue; } // If, when deleting, the quantity of an item with this name is equal to zero, // then such item is completely removed from the warehouse. if ((products.Products[index].Count - countAdd) == 0) { products.Delete(index); countItemsOfWarehouse--; break; } else { products.Products[index].Count -= countAdd; break; } } flag = true; break; } } if (!flag) { Console.WriteLine("No product found with this name!"); Console.ReadKey(); } } else { return; } }
public MyController() { model = new MyModel(); areas = model.getListOfAreas(); currentUserEmail = ""; }
public ActionResult GetAction(MyModel myModel) { ViewBag.Message = unallocateAllClassRoomManager.UnallocateAllClassRoom(); return(View()); }
MyVoxelImport(MyVoxelMap voxelMap, MyModel model, MyvoxelImportAction importAction, Matrix modelWorld, float modelScale, MyMwcVoxelMaterialsEnum? voxelMaterial, ref bool changed) { // Load model, get triangles transformed to model's world matrix LoadModel(model, modelWorld, modelScale); RescaleModel(voxelMap, MyVoxelImportOptions.KeepScale); // Fill lookup array with triangles located at specified voxel positions. Array is 2D. FillTrianglesLookup(voxelMap); // Performs action //PerformAction(voxelMap, importAction, voxelMaterial, ref changed); Import(voxelMap); }
public myForm(MyModel data) { data.StopRefereshLoading += (o, e) => this.CustomControl.StopPullToRefreshLoading(true); // ... etc }
void LoadModel(MyModel model) { model.LoadData(); m_minCoord = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); m_maxCoord = new Vector3(float.MinValue, float.MinValue, float.MinValue); MyTriangleVertexIndices[] triangles = model.Triangles; m_triangles = new List<MyImportTriangle>(triangles.Length); for (int i = 0; i < triangles.Length; i++) { Vector3 vertex0 = model.GetVertex(triangles[i].I0); Vector3 vertex1 = model.GetVertex(triangles[i].I1); Vector3 vertex2 = model.GetVertex(triangles[i].I2); MyImportTriangle triangle = new MyImportTriangle(vertex0, vertex1, vertex2); // Ignore triangles that lie in XZ plane if (triangle.Normal.Y != 0) { m_triangles.Add(triangle); CheckMinMaxCoords(vertex0); CheckMinMaxCoords(vertex1); CheckMinMaxCoords(vertex2); } } }
public static string ListEntry(this MyModel model) { return($" # {model.Id}: {model.SomeEntry}/{model.OtherEntry}"); }