/// <summary> /// Creates a new tags index with a given strings table. /// </summary> public TagsTableCollectionIndex(bool reverseIndex) { _tagsTable = new ObjectTable<Tag>(true); _tagsCollectionTable = new ObjectTable<OsmTags>(reverseIndex); this.Add(new TagsCollection()); }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> /// <param name="tagsTable"></param> public TagsTableCollectionIndex(ObjectTable<Tag> tagsTable) { _tagsTable = tagsTable; _tagsCollectionTable = new ObjectTable<OsmTags>(true); this.Add(new TagsCollection()); }
/// <summary> /// Creates a new OsmGeo object with a string table. /// </summary> /// <param name="string_table"></param> /// <param name="id"></param> internal CompleteOsmGeo(ObjectTable<string> string_table, long id) : base(string_table, id) { this.Visible = true; this.UserId = null; this.User = null; }
/// <param name="model">A copy of the original model the runtime model was generated from.</param> /// <param name="buffer">The buffer the model was deserialized from.</param> /// <param name="objectTable">The table of objects referenced by the model.</param> /// <param name="formulas">The formulas that are checked on the model.</param> internal SerializedRuntimeModel(ModelBase model, byte[] buffer, ObjectTable objectTable, Formula[] formulas) { Model = model; Buffer = buffer; ObjectTable = objectTable; Formulas = formulas; }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> /// <param name="checkDuplicates">Flag to prevent this index from checking for duplicates, used when sure all tag collections are unique.</param> public TagsTableCollectionIndex(bool checkDuplicates) { _tagsTable = new ObjectTable<Tag>(true); _tagsCollectionTable = new ObjectTable<OsmTags>(false, ObjectTable<Tag>.INITIAL_CAPACITY, !checkDuplicates); this.Add(new TagsCollection()); }
/// <summary> /// Creates a new tags collection initialized with the given existing tags. /// </summary> /// <param name="tagsTable"></param> /// <param name="tags"></param> public TagsTableCollection(ObjectTable<Tag> tagsTable, IEnumerable<Tag> tags) { _tagsTable = tagsTable; _tags = new List<uint>(); foreach(Tag tag in tags) { _tags.Add(_tagsTable.Add(tag)); } }
public Script(ScriptEngine engine, SecurityPolicy policy) { _engine = engine; _tokens = new List<List<List<Token>>>(); _functions = new List<Function>(); _securityPolicy = policy; _globals = new ObjectTable(); IsDirty = true; DefaultScope = new Scope(); UseEngineGlobals = true; }
protected void GenerateCode(SerializationMode mode, params object[] objects) { objects = SerializationRegistry.Default.GetReferencedObjects(objects, mode).ToArray(); var model = TestModel.InitializeModel(new DummyComponent(objects)); _objectTable = new ObjectTable(objects); StateVectorLayout = SerializationRegistry.Default.GetStateVectorLayout(model, _objectTable, mode); _serializer = StateVectorLayout.CreateSerializer(_objectTable); _deserializer = StateVectorLayout.CreateDeserializer(_objectTable); _rangeRestrictor = StateVectorLayout.CreateRangeRestrictor(_objectTable); StateSlotCount = StateVectorLayout.SizeInBytes / 4; StateVectorSize = StateVectorLayout.SizeInBytes; _buffer = new MemoryBuffer(); _buffer.Resize(StateVectorSize, zeroMemory: true); SerializedState = _buffer.Pointer; Output.Log("{0}", StateVectorLayout); }
public void TestStringTable_AddStrings() { ObjectTable<string> table = new ObjectTable<string>(false); uint zero = table.Add("zero"); uint one = table.Add("one"); uint two = table.Add("two"); uint three = table.Add("three"); uint four = table.Add("four"); uint five = table.Add("five"); uint six = table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); table = new ObjectTable<string>(true); zero = table.Add("zero"); one = table.Add("one"); two = table.Add("two"); three = table.Add("three"); four = table.Add("four"); five = table.Add("five"); six = table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); }
public override void SyncNewPlayer(Player newPlayer) { base.SyncNewPlayer(newPlayer); // Sync the objects that are not associated with any player. ObjectTable serverTable = base.ObjectTables.GetPlayerTable(base.NetworkControl.ThisPlayer); ICollection <GameObject> serverObjects = serverTable.GetAllObjects(); Debug.Log("Number of server objects: " + serverObjects.Count); foreach (GameObject obj in serverObjects) { ObjectSync objSync = obj.GetComponent <ObjectSync>(); switch (objSync.Type) { case ObjectSyncType.Mothership: ObjectRPC.CreateMothership(newPlayer.NetworkPlayerInfo, objSync.Owner, objSync.GlobalID, obj.layer); // Temporary mothership positions. if (obj.layer == (int)Layers.Team1Mothership) { ObjectRPC.ObjectPosition(objSync.Owner, objSync.GlobalID, new Vector3(1000, 0, 0), Vector3.zero); } else { ObjectRPC.ObjectPosition(objSync.Owner, objSync.GlobalID, new Vector3(-1000, 0, 0), Vector3.zero); } break; case ObjectSyncType.Drone: ObjectRPC.CreateDrone(newPlayer.NetworkPlayerInfo, objSync.Owner, objSync.GlobalID, obj.transform.position, obj.layer); break; case ObjectSyncType.Asteroid: ObjectRPC.CreateAsteroid(newPlayer.NetworkPlayerInfo, objSync.Owner, objSync.GlobalID, obj.transform.position, obj.transform.localScale, obj.name); break; } } // Sync the objects that belong to other players. foreach (Player p in base.Players.Values) { // Skip all objects for the server player (already synced) and the new player (empty). if (!(p.ID == base.NetworkControl.LocalViewID || p.ID == newPlayer.ID)) { // Sync player ships and player spawnpoints PlayerObjects playerObjects = base.ObjectTables.PlayerObjects[p]; GameObject spawnPoint = base.GetObject(p, playerObjects.PlayerSpawnPointID); ObjectRPC.CreatePlayerSpawnpoint( newPlayer.NetworkPlayerInfo , p , playerObjects.PlayerSpawnPointID , spawnPoint.transform.position); GameObject playerShip = base.GetObject(p, playerObjects.PlayerShipID); PlayerShipRPC.CreatePlayerShip(newPlayer.NetworkPlayerInfo, p, playerObjects.PlayerShipID); //ObjectRPC.SetObjectLayer(newPlayer.NetworkPlayerInfo, p, playerObjects.PlayerShipID, (Layers)playerShip.layer); } } // Create the objects for the new player. int spawnPointID = base.GUIDGenerator.GenerateID(); int playerShipID = base.GUIDGenerator.GenerateID(); GameObject mothership = base.GetMothership(newPlayer.Team); Vector3 spawnPointPos = mothership.transform.position + new Vector3(0, 500, 0); // The order in which the following RPCs are sent is critical! ObjectRPC.CreatePlayerSpawnpoint(newPlayer, spawnPointID, spawnPointPos); PlayerShipRPC.CreatePlayerShip(newPlayer, playerShipID); PlayerShipRPC.SpawnPlayerShip(newPlayer, spawnPointID, playerShipID); }
/// <summary> /// Creates a new node using a string table. /// </summary> /// <param name="id"></param> /// <param name="stringTable"></param> internal protected CompleteNode(ObjectTable <string> stringTable, long id) : base(stringTable, id) { }
/// <summary> /// Update user relationship /// </summary> /// <param name="storageConsistencyMode">Consistency mode</param> /// <param name="relationshipHandle">Relationship handle</param> /// <param name="userHandle">User handle</param> /// <param name="relationshipUserHandle">Relationship user handle</param> /// <param name="appHandle">App handle</param> /// <param name="userRelationshipStatus">Relationship status</param> /// <param name="lastUpdatedTime">Last updated time</param> /// <param name="readUserRelationshipLookupEntity">Read user relationship lookup entity</param> /// <param name="store">store object</param> /// <param name="lookupTable">lookup table</param> /// <param name="feedTable">feed table</param> /// <param name="countTable">count table</param> /// <returns>Update follower relationship task</returns> private async Task UpdateUserRelationship( StorageConsistencyMode storageConsistencyMode, string relationshipHandle, string userHandle, string relationshipUserHandle, string appHandle, UserRelationshipStatus userRelationshipStatus, DateTime lastUpdatedTime, IUserRelationshipLookupEntity readUserRelationshipLookupEntity, CTStore store, ObjectTable lookupTable, FeedTable feedTable, CountTable countTable) { string objectKey = this.GetObjectKey(appHandle, relationshipUserHandle); string feedKey = this.GetFeedKey(appHandle, userRelationshipStatus); string countKey = this.GetCountKey(appHandle, userRelationshipStatus); Transaction transaction = new Transaction(); UserRelationshipFeedEntity relationshipFeedEntity = new UserRelationshipFeedEntity() { RelationshipHandle = relationshipHandle, UserHandle = relationshipUserHandle }; if (readUserRelationshipLookupEntity == null) { UserRelationshipLookupEntity newRelationshipLookupEntity = new UserRelationshipLookupEntity() { RelationshipHandle = relationshipHandle, LastUpdatedTime = lastUpdatedTime, UserRelationshipStatus = userRelationshipStatus, }; transaction.Add(Operation.Insert(lookupTable, userHandle, objectKey, newRelationshipLookupEntity)); if (userRelationshipStatus != UserRelationshipStatus.None) { transaction.Add(Operation.Insert(feedTable, userHandle, feedKey, relationshipHandle, relationshipFeedEntity)); transaction.Add(Operation.InsertOrIncrement(countTable, userHandle, countKey)); } } else { UserRelationshipStatus oldUserRelationshipStatus = readUserRelationshipLookupEntity.UserRelationshipStatus; string oldRelationshipHandle = readUserRelationshipLookupEntity.RelationshipHandle; readUserRelationshipLookupEntity.RelationshipHandle = relationshipHandle; readUserRelationshipLookupEntity.UserRelationshipStatus = userRelationshipStatus; readUserRelationshipLookupEntity.LastUpdatedTime = lastUpdatedTime; string oldFeedKey = this.GetFeedKey(appHandle, oldUserRelationshipStatus); string oldCountKey = this.GetCountKey(appHandle, oldUserRelationshipStatus); transaction.Add(Operation.Replace(lookupTable, userHandle, objectKey, readUserRelationshipLookupEntity as UserRelationshipLookupEntity)); if (userRelationshipStatus == oldUserRelationshipStatus) { if (userRelationshipStatus != UserRelationshipStatus.None && relationshipHandle != oldRelationshipHandle) { transaction.Add(Operation.Delete(feedTable, userHandle, oldFeedKey, oldRelationshipHandle)); transaction.Add(Operation.Insert(feedTable, userHandle, feedKey, relationshipHandle, relationshipFeedEntity)); } } else { if (userRelationshipStatus != UserRelationshipStatus.None) { transaction.Add(Operation.Insert(feedTable, userHandle, feedKey, relationshipHandle, relationshipFeedEntity)); transaction.Add(Operation.InsertOrIncrement(countTable, userHandle, countKey)); } if (oldUserRelationshipStatus != UserRelationshipStatus.None) { transaction.Add(Operation.Delete(feedTable, userHandle, oldFeedKey, oldRelationshipHandle)); transaction.Add(Operation.Increment(countTable, userHandle, oldCountKey, -1.0)); } } } await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode()); }
public LiteValue Visit(SyntaxAssignmentExpressionNode Node, LiteEnv Env) { var LeftNode = Node.GetLeft(); if (LeftNode.GetType() == SyntaxNodeType.Identifier) { var Ident = (LeftNode as SyntaxIdentifierNode).GetValue(); var Val = Node.GetRight().Accept(this, Env); Env.Set(Ident, Val); return(Val); } if (LeftNode.GetType() == SyntaxNodeType.DotClassExpression) { var DotNode = LeftNode as SyntaxDotClassExpressionNode; var Mem = DotNode.GetCallIdentNode() as SyntaxIdentifierNode; var LiteObjVal = DotNode.GetClassIdentNode().Accept(this, Env); if (LiteObjVal.Type != LiteValueType.Object) { Logger.DError($"bad object access : {LiteObjVal}"); return(LiteValue.Error); } var LiteObj = ObjectTable.GetObject((int)LiteObjVal.Numeric); if (LiteObj == null) { Logger.DError($"bad object access : {LiteObjVal}"); return(LiteValue.Error); } var ExpVal = Node.GetRight().Accept(this, Env); if (ExpVal == LiteValue.Error) { return(ExpVal); } return(LiteObj.Write(Mem.GetValue(), ExpVal)); } if (LeftNode.GetType() == SyntaxNodeType.IndexElementsExpression) { var IdxNode = LeftNode as SyntaxIndexElementsExpressionNode; var Val = IdxNode.GetElementIdentNode().Accept(this, Env); if (Val.Type == LiteValueType.Elements) { var EleObj = ElementsTable.GetElements((int)Val.Numeric); if (EleObj == null) { Logger.DError($"bad elements access : {Val}"); return(LiteValue.Error); } var Idx = IdxNode.GetIndexNode().Accept(this, Env); if (Idx.Type != LiteValueType.Numeric) { Logger.DError($"elements index must be number"); return(LiteValue.Error); } var ExpVal = Node.GetRight().Accept(this, Env); if (ExpVal == LiteValue.Error) { return(ExpVal); } return(EleObj.Set((int)Idx.Numeric, ExpVal)); } else { Logger.DError($"unknown elements type : {Val}"); } } Logger.DError($"unexpected '=' near {Node.GetLeft()}"); return(LiteValue.Error); }
//Make ObjectTable of type Entity, passing my entities and the desired parameters private void loadCombatTable() { combatTable = new ObjectTable <Entity>(encounter.Entities, new string[] { "Name", "Initiative", "CurrentHP", "MaxHP", "ArmorClass" }); CombatTablePlaceHolder.Controls.Add(combatTable); }
/// <summary> /// Generates the <see cref="StateVectorLayout" /> for the <paramref name="objects" />. /// </summary> /// <param name="model">The model the state vector should be layouted for.</param> /// <param name="objects">The objects consisting of state values the state vector layout should be generated for.</param> /// <param name="mode">The serialization mode that should be used to generate the state vector layout.</param> internal StateVectorLayout GetStateVectorLayout(ModelBase model, ObjectTable objects, SerializationMode mode) { Requires.NotNull(model, nameof(model)); Requires.NotNull(objects, nameof(objects)); Requires.InRange(mode, nameof(mode)); var layout = new StateVectorLayout(); foreach (var slot in objects.SelectMany(obj => GetSerializer(obj).GetStateSlotMetadata(obj, objects.GetObjectIdentifier(obj), mode))) layout.Add(slot); layout.Compact(model, mode); return layout; }
/// <summary> /// Creates a new way. /// </summary> /// <returns></returns> public static CompleteWay CreateFrom(ObjectTable<string> table, Way simpleWay, IDictionary<long, Node> nodes) { if (table == null) throw new ArgumentNullException("table"); if (simpleWay == null) throw new ArgumentNullException("simpleWay"); if (nodes == null) throw new ArgumentNullException("nodes"); if (simpleWay.Id == null) throw new Exception("simpleWay.id is null"); var way = Create(table, simpleWay.Id.Value); way.ChangeSetId = simpleWay.ChangeSetId; foreach (var pair in simpleWay.Tags) { way.Tags.Add(pair); } for (int idx = 0; idx < simpleWay.Nodes.Count; idx++) { var nodeId = simpleWay.Nodes[idx]; Node node = null; if (nodes.TryGetValue(nodeId, out node)) { way.Nodes.Add(node); } else { return null; } } way.TimeStamp = simpleWay.TimeStamp; way.User = simpleWay.UserName; way.UserId = simpleWay.UserId; way.Version = simpleWay.Version.HasValue ? (long)simpleWay.Version.Value : (long?)null; way.Visible = simpleWay.Visible.HasValue && simpleWay.Visible.Value; return way; }
public void NullKeyIsNotAllowed() { ObjectTable.Add(0, new MockMaterial(), null); }
/// <summary> /// Load graphics content for the game. /// </summary> public override void LoadContent() { if ( Content == null ) Content = new ContentManager( ScreenManager.Game.Services, "Content" ); Game game = ScreenManager.Game; // initialize physics PhysicsSpace = new PhysicsSpace(); PhysicsSpace.Gravity = new Vector2( 0f, -8f ); // render targets GraphicsDevice device = ScreenManager.GraphicsDevice; PostProcessor.Initialize( device, ScreenManager.SpriteBatch, Content ); PresentationParameters pars = device.PresentationParameters; basicSceneRenderTarget = new RenderTarget2D( device, pars.BackBufferWidth, pars.BackBufferHeight, 1, pars.BackBufferFormat ); maskRenderTarget = new RenderTarget2D( device, pars.BackBufferWidth, pars.BackBufferHeight, 1, SurfaceFormat.Bgr32 ); screenRectangle = new Rectangle( 0, 0, pars.BackBufferWidth, pars.BackBufferHeight ); // this prevents the game from pausing after the player presses start to exit the loading screen firstFrame = true; // load fonts gameFont = Content.Load<SpriteFont>( "Fonts/gamefont" ); Content.Load<SpriteFont>( "Fonts/HUDNameFont" ); // load screens ahead of time scoreboardMenuScreen = new ScoreboardMenuScreen( ScreenManager, initSlotInfo ); pauseScreen = new PauseMenuScreen( ScreenManager ); // model explosion particles ParticleManager = new ParticleManager( game, Content ); ParticleManager.Initialize(); components.Add( ParticleManager ); // other particles PixieParticleSystem = new PixieParticleSystem( game, Content ); SparkParticleSystem = new SparkParticleSystem( game, Content ); PinkPixieParticleSystem = new PinkPixieParticleSystem( game, Content ); components.Add( PixieParticleSystem ); components.Add( SparkParticleSystem ); components.Add( PinkPixieParticleSystem ); foreach ( DrawableGameComponent component in components ) component.Initialize(); // pre-load LaserBeam.Initialize(); Content.Load<CustomAvatarAnimationData>( "Animations/Walk" ); Content.Load<CustomAvatarAnimationData>( "Animations/Run" ); backgroundTexture = Content.Load<Texture2D>( "Textures/gameBackground" ); int left = -( backgroundTexture.Width - ScreenManager.GraphicsDevice.Viewport.Width ) / 2; Viewport viewport = ScreenManager.GraphicsDevice.Viewport; if ( left > 0 ) backgroundRect = new Rectangle( 0, 0, viewport.Width, viewport.Height ); else backgroundRect = new Rectangle( left, 0, backgroundTexture.Width, viewport.Height ); // init game stuff ObjectTable = new ObjectTable<GameObject>(); // ready, go! ObjectTable.Add( new ReadyGo( this, new Vector2( viewport.Width / 2, viewport.Height / 2 ) ) ); float fov = MathHelper.ToRadians( 30f ); float aspect = ScreenManager.GraphicsDevice.DisplayMode.AspectRatio; Camera = new Camera( fov, aspect, 1f, 100f, new Vector3( 0f, 0f, cameraDistance ), Vector3.Zero ); winnerSpring = new SpringInterpolater( 1, 10, SpringInterpolater.GetCriticalDamping( 10 ) ); winnerSpring.SetSource( 1 ); winnerSpring.SetDest( 0 ); FloorBlock.Initialize( this ); Powerup.Initialize( this ); lastRowY = rowSpacing - Player.Size * 1.5f; InitSafeRectangle(); InitStage(); CountdownTime = 0f; CountdownEnd = 3f; lastCamY = Camera.Position.Y; SpawnRows(); // spawn additional rows before loading screen is over gameClock = new GameTimer( TimeSpan.FromMinutes( 2 ) ); ObjectTable.Add( gameClock ); ScreenManager.Game.ResetElapsedTime(); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="serializedData">The serialized data describing the model.</param> /// <param name="stateHeaderBytes"> /// The number of bytes that should be reserved at the beginning of each state vector for the model checker tool. /// </param> internal RuntimeModel(SerializedRuntimeModel serializedData, int stateHeaderBytes = 0) { Requires.That(serializedData.Model != null, "Expected a valid model instance."); var buffer = serializedData.Buffer; var rootComponents = serializedData.Model.Roots; var objectTable = serializedData.ObjectTable; var formulas = serializedData.Formulas; Requires.NotNull(buffer, nameof(buffer)); Requires.NotNull(rootComponents, nameof(rootComponents)); Requires.NotNull(objectTable, nameof(objectTable)); Requires.NotNull(formulas, nameof(formulas)); Requires.That(stateHeaderBytes % 4 == 0, nameof(stateHeaderBytes), "Expected a multiple of 4."); Model = serializedData.Model; SerializedModel = buffer; RootComponents = rootComponents.Cast<Component>().ToArray(); StateFormulas = objectTable.OfType<StateFormula>().ToArray(); Formulas = formulas; // Create a local object table just for the objects referenced by the model; only these objects // have to be serialized and deserialized. The local object table does not contain, for instance, // the closure types of the state formulas. _faults = objectTable.OfType<Fault>().Where(fault => fault.IsUsed).ToArray(); _serializedObjects = new ObjectTable(Model.ReferencedObjects); Objects = objectTable; StateVectorLayout = SerializationRegistry.Default.GetStateVectorLayout(Model, _serializedObjects, SerializationMode.Optimized); UpdateFaultSets(); _deserialize = StateVectorLayout.CreateDeserializer(_serializedObjects); _serialize = StateVectorLayout.CreateSerializer(_serializedObjects); _restrictRanges = StateVectorLayout.CreateRangeRestrictor(_serializedObjects); _stateHeaderBytes = stateHeaderBytes; PortBinding.BindAll(objectTable); ConstructionState = new byte[StateVectorSize]; fixed (byte* state = ConstructionState) { Serialize(state); _restrictRanges(); } FaultSet.CheckFaultCount(_faults.Length); StateFormulaSet.CheckFormulaCount(StateFormulas.Length); }
public void TestStringTable_AddStringsTwice() { ObjectTable<string> table = new ObjectTable<string>(false); table.Add("zero"); table.Add("one"); table.Add("two"); table.Add("three"); table.Add("four"); table.Add("five"); table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); Assert.AreEqual((uint)0, table.Add("zero")); Assert.AreEqual((uint)1, table.Add("one")); Assert.AreEqual((uint)2, table.Add("two")); Assert.AreEqual((uint)3, table.Add("three")); Assert.AreEqual((uint)4, table.Add("four")); Assert.AreEqual((uint)5, table.Add("five")); Assert.AreEqual((uint)6, table.Add("six")); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); table = new ObjectTable<string>(true); table.Add("zero"); table.Add("one"); table.Add("two"); table.Add("three"); table.Add("four"); table.Add("five"); table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); Assert.AreEqual((uint)0, table.Add("zero")); Assert.AreEqual((uint)1, table.Add("one")); Assert.AreEqual((uint)2, table.Add("two")); Assert.AreEqual((uint)3, table.Add("three")); Assert.AreEqual((uint)4, table.Add("four")); Assert.AreEqual((uint)5, table.Add("five")); Assert.AreEqual((uint)6, table.Add("six")); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); }
/// <summary> /// Serializes the <paramref name="objectTable" /> using the <paramref name="writer" />. /// </summary> /// <param name="objectTable">The object table that should be serialized.</param> /// <param name="writer">The writer the serialized information should be written to.</param> private static void SerializeObjectTable(ObjectTable objectTable, BinaryWriter writer) { Requires.NotNull(objectTable, nameof(objectTable)); Requires.NotNull(writer, nameof(writer)); // Serialize the objects contained in the table writer.Write(objectTable.Count); foreach (var obj in objectTable) { var serializerIndex = SerializationRegistry.Default.GetSerializerIndex(obj); writer.Write(serializerIndex); SerializationRegistry.Default.GetSerializer(serializerIndex).SerializeType(obj, writer); } }
//Loads the party to the partyTable private void loadPartyTable() { partyTable = new ObjectTable <PartyMember>(party.PartyMembers, new string[] { "Name", "Race", "Perception", "CurrentHP", "MaxHP", "Size" }); PartyTablePlaceHolder.Controls.Add(partyTable); }
/// <summary> /// Creates a new dictionary. /// </summary> /// <param name="stringTable"></param> public StringTableTagsCollection(ObjectTable<string> stringTable) { _stringTable = stringTable; _tagsList = new List<TagEncoded>(); }
protected override void SolveInstance(IGH_DataAccess da) { //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) if ((base.m_attributes as AttButt).Reset) { _history.ForEach(delegate(Guid i) { _doc.get_Objects().Select(i); }); return; } List <Guid> list = new List <Guid>(); List <IGH_GeometricGoo> list2 = new List <IGH_GeometricGoo>(); da.GetDataList <Guid>(0, list); da.GetDataList <IGH_GeometricGoo>(1, list2); if (!ButtonActivate()) { return; } _history = list.ToList(); ObjectTable objects = RhinoDoc.get_ActiveDoc().get_Objects(); int count = list2.Count; Point3d val11 = default(Point3d); Circle val10 = default(Circle); Arc val9 = default(Arc); Rectangle3d val8 = default(Rectangle3d); Line val7 = default(Line); Curve val6 = default(Curve); Mesh val5 = default(Mesh); Surface val4 = default(Surface); Brep val3 = default(Brep); for (int j = 0; j < list.Count; j++) { IGH_GeometricGoo val = list2[j % count]; Guid guid = list[j]; ObjRef val2 = (ObjRef)(object)new ObjRef(guid); switch (((IGH_Goo)val).get_TypeName()) { case "Plane": case "Point": ((IGH_Goo)val).CastTo <Point3d>(ref val11); objects.Replace(guid, val11); break; case "Circle": ((IGH_Goo)val).CastTo <Circle>(ref val10); objects.Replace(guid, val10); break; case "Arc": ((IGH_Goo)val).CastTo <Arc>(ref val9); objects.Replace(guid, val9); break; case "Line": ((IGH_Goo)val).CastTo <Line>(ref val7); objects.Replace(guid, val7); break; case "Curve": ((IGH_Goo)val).CastTo <Curve>(ref val6); objects.Replace(guid, val6); break; case "Mesh": ((IGH_Goo)val).CastTo <Mesh>(ref val5); objects.Replace(guid, val5); break; case "Surface": ((IGH_Goo)val).CastTo <Surface>(ref val4); objects.Replace(guid, val4); break; case "Twisted Box": case "Box": case "Brep": ((IGH_Goo)val).CastTo <Brep>(ref val3); objects.Replace(guid, val3); break; } ObjectAttributes attributes = val2.Object().get_Attributes(); attributes.set_ObjectId(guid); objects.ModifyAttributes(_doc.get_Objects().MostRecentObject().get_Id(), attributes, true); } }
public void LoadVBInfo(VBInfo info) { treeView1.Nodes.Clear(); TreeNodeCollection rootNodes = treeView1.Nodes; TreeNodeCollection nodes = rootNodes; TreeNode node = null; VBHeader vbheader = info.HeaderInfo; node = rootNodes.Add(typeof(VBHeader).Name); node.Tag = vbheader; node = rootNodes.Add(typeof(ProjectInfo).Name); node.Tag = vbheader.ProjectInfo2; if (vbheader.ProjectInfo2.ObjectTable2 != null) { node = rootNodes.Add(typeof(ObjectTable).Name); ObjectTable entity = vbheader.ProjectInfo2.ObjectTable2; node.Tag = entity; if (entity.ProjectInfo22 != null) { node = rootNodes.Add(typeof(ProjectInfo2).Name); node.Tag = entity.ProjectInfo22; } if (entity.Objects != null && entity.Objects.Length > 0) { node = rootNodes.Add("对象"); nodes = node.Nodes; foreach (PublicObjectDescriptor item in entity.Objects) { node = nodes.Add(item.Name); node.Tag = item; TreeNode node2 = null; if (item.ObjectInfo2 != null) { node2 = node.Nodes.Add(typeof(ObjectInfo).Name); node2.Tag = item.ObjectInfo2; } if (item.OptionalObjectInfo != null) { node2 = node.Nodes.Add(typeof(OptionalObjectInfo).Name); node2.Tag = item.OptionalObjectInfo; TreeNode node3 = null; if (item.OptionalObjectInfo.EventLinks != null && item.OptionalObjectInfo.EventLinks.Length > 0) { node2 = node.Nodes.Add("事件"); Int32 i = 1; foreach (EventLink2 elm in item.OptionalObjectInfo.EventLinks) { String name = String.Empty; if (item.ProcNames != null && item.ProcNames.Length > i - 1) { name = item.Name + "_" + item.ProcNames[i - 1].FriendName; } if (String.IsNullOrEmpty(name)) { name = item.Name + "_" + i.ToString("X2"); } i++; node3 = node2.Nodes.Add(name); node3.Tag = elm; } } if (item.OptionalObjectInfo.Controls != null && item.OptionalObjectInfo.Controls.Length > 0) { node2 = node.Nodes.Add("控件"); foreach (VBControl elm in item.OptionalObjectInfo.Controls) { node3 = node2.Nodes.Add(elm.Name2); node3.Tag = elm; } } } //if (item.ProcNames != null && item.ProcNames.Length > 0) //{ // foreach (ProcName elm in item.ProcNames) // { // node2 = node.Nodes.Add(elm.Name); // node2.Tag = elm; // } //} } } } if (vbheader.ComRegisterData2 != null) { node = rootNodes.Add(typeof(ComRegData).Name); ComRegData entity = vbheader.ComRegisterData2; node.Tag = entity; if (entity.RegInfo2 != null && entity.RegInfo2.Length > 0) { node = rootNodes.Add("COM注册"); nodes = node.Nodes; foreach (ComRegInfo item in entity.RegInfo2) { node = nodes.Add(item.Name); node.Tag = item; } } } if (vbheader.ExternalComponentTables != null && vbheader.ExternalComponentTables.Length > 0) { node = rootNodes.Add("引用组件"); nodes = node.Nodes; foreach (ExternalComponentTable item in vbheader.ExternalComponentTables) { node = nodes.Add(item.Name2); node.Tag = item; } } if (vbheader.GUITables != null && vbheader.GUITables.Length > 0) { node = rootNodes.Add("窗体"); nodes = node.Nodes; foreach (GUITable item in vbheader.GUITables) { node = nodes.Add(typeof(GUITable).Name); node.Tag = item; } } }
/// <summary> /// Serializes all the tags in the given index. This serialization preserves the id's of each tag collection. /// </summary> /// <param name="stream">The target stream.</param> /// <param name="tagsIndex">The tags index to serialize.</param> public static void Serialize(Stream stream, ITagsCollectionIndex tagsIndex) { int begin = (int)stream.Position; // build a string index. ObjectTable<string> stringTable = new ObjectTable<string>(false); // convert tag collections to simpler objects. List<KeyValuePair<uint, List<KeyValuePair<uint, uint>>>> tagsIndexList = new List<KeyValuePair<uint,List<KeyValuePair<uint,uint>>>>(); for (uint tagId = 0; tagId < tagsIndex.Max; tagId++) { TagsCollectionBase tagsCollection = tagsIndex.Get(tagId); if (tagsCollection != null) { // convert the tags collection to a list and add to the tag index. List<KeyValuePair<uint, uint>> tagsList = new List<KeyValuePair<uint, uint>>(); foreach (Tag tag in tagsCollection) { uint keyId = stringTable.Add(tag.Key); uint valueId = stringTable.Add(tag.Value); tagsList.Add(new KeyValuePair<uint, uint>( keyId, valueId)); } tagsIndexList.Add(new KeyValuePair<uint, List<KeyValuePair<uint, uint>>>(tagId, tagsList)); } } // do the serialization. TagIndexSerializer.Serialize(begin, stream, tagsIndexList, stringTable); // clear everything. tagsIndexList.Clear(); }
public ObjectTable(ObjectTable table) { table.CopyTo(this); }
/// <summary> /// Does the actual serialization of the given data structures. /// </summary> private static void Serialize(int begin, Stream stream, List<KeyValuePair<uint, List<KeyValuePair<uint, uint>>>> tagIndex, ObjectTable<string> stringTable) { RuntimeTypeModel typeModel = TagIndexSerializer.CreateTypeModel(); // move until after the index (index contains two int's, startoftagindex, endoffile). stream.Seek(begin + 8, SeekOrigin.Begin); // serialize string table. List<string> strings = new List<string>(); for (uint id = 0; id < stringTable.Count; id++) { strings.Add(stringTable.Get(id)); } stringTable.Clear(); stringTable = null; typeModel.Serialize(stream, strings); long startOfTagsIndex = stream.Position - begin; // serialize tagindex. typeModel.Serialize(stream, tagIndex); long endOfFile = stream.Position - begin; // write index. stream.Seek(begin, SeekOrigin.Begin); stream.Write(BitConverter.GetBytes((int)startOfTagsIndex), 0, 4); // write start position of tagindex. stream.Write(BitConverter.GetBytes((int)endOfFile), 0, 4); // write size of complete file. stream.Seek(begin + endOfFile, SeekOrigin.Begin); }
/// <summary> /// Creates a new relation using a string table. /// </summary> /// <param name="id"></param> /// <param name="stringTable"></param> internal protected CompleteRelation(ObjectTable <string> stringTable, long id) : base(stringTable, id) { _members = new List <CompleteRelationMember>(); }
/// <summary> /// Provision azure table storage with tables /// </summary> /// <param name="tableStoreManager">table store manager</param> /// <param name="azureConnectionString">Azure connection string</param> /// <returns>provision task</returns> private static async Task ProvisionAzureStorageTables(CTStoreManager tableStoreManager, string azureConnectionString) { // Creates Social Plus containers/tables defined in ContainerIdentifier.cs/TableIdentifier.cs // Containers map to tables in Azure table storage (container names map to table names) // We create them (if not exists) through the CTStore interface Console.WriteLine("Creating all tables in Azure Table Store..."); // Get azure table storage with the give connection string AzureTableStorage azureTableStorage = new AzureTableStorage(azureConnectionString); // Get CTStore using the azure table storage CTStore store = new CTStore(azureTableStorage, null); // Enumerate all the containers defined foreach (ContainerIdentifier containerIdentifier in Enum.GetValues(typeof(ContainerIdentifier))) { if (!ContainerTableDescriptorProvider.Containers.ContainsKey(containerIdentifier)) { Console.WriteLine(" " + containerIdentifier.ToString() + " - Descriptor not found"); continue; } // in Azure, table deletion can potentially take a long time. // this may lead to conflict exceptions if you delete a table and then attempt to // recreate it. Below, we retry once every 30 seconds for up to 5 minutes if needed. // wait up to 5 minutes before giving up on table creation int attempts = 0; int maxAttempts = 10; while (true) { try { attempts++; // create the container await store.CreateContainerAsync(containerIdentifier.ToString()); // if we reach here, the create was successful break; } catch (ConflictException e) { if (attempts < maxAttempts) { // sleep for 30 seconds before trying await Task.Delay(30 * 1000); } else { // give up after reaching maxAttempts throw e; } } } Console.WriteLine(" " + containerIdentifier.ToString() + " - Table Container Provisioned"); } // insert the store version number into table storage var versionEntity = new StoreVersionEntity { Version = tableStoreManager.StoreVersionString }; // the StoreVersion container has no descriptor, so we need to create it await store.CreateContainerAsync(ContainerIdentifier.ServiceConfig.ToString()); Console.WriteLine(" " + ContainerIdentifier.ServiceConfig.ToString() + " - Table Container Provisioned"); ObjectTable versionTable = Table.GetObjectTable( ContainerIdentifier.ServiceConfig.ToString(), tableStoreManager.ServiceConfigContainerInitials, tableStoreManager.StoreVersionTableName, tableStoreManager.StoreVersionTableInitials, StorageMode.PersistentOnly); var operation = Operation.Insert(versionTable, tableStoreManager.StoreVersionKey, tableStoreManager.StoreVersionKey, versionEntity); // perform the insert on Azure table storage await store.ExecuteOperationAsync(operation, ConsistencyMode.Strong); Console.WriteLine(" SocialPlusStoreVersion number provisioned"); }
internal async Task SaveObjectTableAsync(SqoTypeInfo actualTypeinfo, SqoTypeInfo oldSqoTypeInfo, ObjectTable table, RawdataSerializer rawSerializer) { Dictionary <FieldSqoInfo, FieldSqoInfo> joinedFields = JoinFieldsSqoInfo(actualTypeinfo, oldSqoTypeInfo); foreach (ObjectRow row in table.Rows) { int oid = (int)row["OID"]; if (oid < 0)//deleted { await this.MarkObjectAsDeleteAsync(-oid, actualTypeinfo).ConfigureAwait(false); continue; } byte[] oidBuff = ByteConverter.IntToByteArray(oid); byte[] buffer = new byte[actualTypeinfo.Header.lengthOfRecord]; int curentIndex = 0; Array.Copy(oidBuff, 0, buffer, curentIndex, oidBuff.Length); curentIndex += oidBuff.Length; foreach (FieldSqoInfo ai in actualTypeinfo.Fields) { byte[] by = null; object fieldVal = null; bool existed = false; if (table.Columns.ContainsKey(ai.Name)) { fieldVal = row[ai.Name]; existed = true; } else { if (ai.AttributeTypeId == MetaExtractor.complexID || ai.AttributeTypeId == MetaExtractor.documentID) { fieldVal = null; } else if (typeof(string) == ai.AttributeType) { fieldVal = string.Empty; } else if (ai.AttributeType.IsArray) { fieldVal = Array.CreateInstance(ai.AttributeType.GetElementType(), 0); } else { fieldVal = Activator.CreateInstance(ai.AttributeType); } } if (joinedFields[ai] != null) //existed in old Type { if (ai.AttributeTypeId != joinedFields[ai].AttributeTypeId) { if (typeof(IList).IsAssignableFrom(ai.AttributeType) || ai.AttributeTypeId == MetaExtractor.dictionaryID || joinedFields[ai].AttributeTypeId == MetaExtractor.dictionaryID) { throw new TypeChangedException("Change array or dictionary type it is not supported"); } else { fieldVal = Convertor.ChangeType(fieldVal, ai.AttributeType); } } } if (ai.AttributeTypeId == MetaExtractor.complexID || ai.AttributeTypeId == MetaExtractor.documentID) { if (existed) { by = (byte[])fieldVal; } else { by = await this.GetComplexObjectBytesAsync(fieldVal).ConfigureAwait(false); } } else if (typeof(IList).IsAssignableFrom(ai.AttributeType))//array { if (existed) { by = (byte[])fieldVal; } else { by = await rawSerializer.SerializeArrayAsync(fieldVal, ai.AttributeType, ai.Header.Length, ai.Header.RealLength, actualTypeinfo.Header.version, null, this, ai.IsText).ConfigureAwait(false); } } else if (ai.IsText) { if (existed) { FieldSqoInfo oldAi = joinedFields[ai]; if (oldAi != null && oldAi.IsText) { by = (byte[])fieldVal; } else { by = await rawSerializer.SerializeArrayAsync(fieldVal, ai.AttributeType, ai.Header.Length, ai.Header.RealLength, actualTypeinfo.Header.version, null, this, ai.IsText).ConfigureAwait(false); } } else { by = await rawSerializer.SerializeArrayAsync(fieldVal, ai.AttributeType, ai.Header.Length, ai.Header.RealLength, actualTypeinfo.Header.version, null, this, ai.IsText).ConfigureAwait(false); } } else if (ai.AttributeTypeId == MetaExtractor.dictionaryID) { if (existed) { by = (byte[])fieldVal; } else { IByteTransformer byteTransformer = ByteTransformerFactory.GetByteTransformer(this, rawSerializer, ai, actualTypeinfo, 0); by = await byteTransformer.GetBytesAsync(fieldVal).ConfigureAwait(false); } } else { by = ByteConverter.SerializeValueType(fieldVal, ai.AttributeType, ai.Header.Length, ai.Header.RealLength, actualTypeinfo.Header.version); } Array.Copy(by, 0, buffer, ai.Header.PositionInRecord, ai.Header.Length); //curentIndex += by.Length; } long position = MetaHelper.GetSeekPosition(actualTypeinfo, oid); await file.WriteAsync(position, buffer).ConfigureAwait(false); } }
/// <summary> /// Insert app /// </summary> /// <param name="storageConsistencyMode">Storage consistency mode</param> /// <param name="appHandle">App handle</param> /// <param name="developerId">Developer id</param> /// <param name="name">App name</param> /// <param name="iconHandle">Icon handle</param> /// <param name="platformType">Platform type</param> /// <param name="deepLink">Deep link</param> /// <param name="storeLink">Store link</param> /// <param name="createdTime">Created time</param> /// <param name="disableHandleValidation">whether to disable validation of app-provided handles</param> /// <returns>Create app task</returns> public async Task InsertApp( StorageConsistencyMode storageConsistencyMode, string appHandle, string developerId, string name, string iconHandle, PlatformType platformType, string deepLink, string storeLink, DateTime createdTime, bool disableHandleValidation) { AppProfileEntity appProfileEntity = new AppProfileEntity() { DeveloperId = developerId, Name = name, IconHandle = iconHandle, PlatformType = platformType, DeepLink = deepLink, StoreLink = storeLink, CreatedTime = createdTime, LastUpdatedTime = createdTime, AppStatus = AppStatus.Active, DisableHandleValidation = disableHandleValidation, }; IdentityProviderCredentialsEntity facebookCredentialsEntity = new IdentityProviderCredentialsEntity(); IdentityProviderCredentialsEntity microsoftCredentialsEntity = new IdentityProviderCredentialsEntity(); IdentityProviderCredentialsEntity googleCredentialsEntity = new IdentityProviderCredentialsEntity(); IdentityProviderCredentialsEntity twitterCredentialsEntity = new IdentityProviderCredentialsEntity(); IdentityProviderCredentialsEntity aadCredentialsEntity = new IdentityProviderCredentialsEntity(); ValidationConfigurationEntity validationConfigurationEntity = new ValidationConfigurationEntity() { Enabled = false }; PushNotificationsConfigurationEntity windowsPushNotificationsConfigurationEntity = new PushNotificationsConfigurationEntity() { Enabled = false }; PushNotificationsConfigurationEntity androidPushNotificationsConfigurationEntity = new PushNotificationsConfigurationEntity() { Enabled = false }; PushNotificationsConfigurationEntity iosPushNotificationsConfigurationEntity = new PushNotificationsConfigurationEntity() { Enabled = false }; CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.Apps); ObjectTable profilesTable = this.tableStoreManager.GetTable(ContainerIdentifier.Apps, TableIdentifier.AppProfilesObject) as ObjectTable; ObjectTable credentialsTable = this.tableStoreManager.GetTable(ContainerIdentifier.Apps, TableIdentifier.AppIdentityProviderCredentialsObject) as ObjectTable; ObjectTable validationConfigsTable = this.tableStoreManager.GetTable(ContainerIdentifier.Apps, TableIdentifier.AppValidationConfigurationsObject) as ObjectTable; ObjectTable pushConfigsTable = this.tableStoreManager.GetTable(ContainerIdentifier.Apps, TableIdentifier.AppPushNotificationsConfigurationsObject) as ObjectTable; Transaction transaction = new Transaction(); transaction.Add(Operation.Insert(profilesTable, appHandle, appHandle, appProfileEntity)); transaction.Add(Operation.Insert(credentialsTable, appHandle, IdentityProviderType.Facebook.ToString(), facebookCredentialsEntity)); transaction.Add(Operation.Insert(credentialsTable, appHandle, IdentityProviderType.Microsoft.ToString(), microsoftCredentialsEntity)); transaction.Add(Operation.Insert(credentialsTable, appHandle, IdentityProviderType.Google.ToString(), googleCredentialsEntity)); transaction.Add(Operation.Insert(credentialsTable, appHandle, IdentityProviderType.Twitter.ToString(), twitterCredentialsEntity)); transaction.Add(Operation.Insert(credentialsTable, appHandle, IdentityProviderType.AADS2S.ToString(), aadCredentialsEntity)); transaction.Add(Operation.Insert(validationConfigsTable, appHandle, appHandle, validationConfigurationEntity)); transaction.Add(Operation.Insert(pushConfigsTable, appHandle, PlatformType.Windows.ToString(), windowsPushNotificationsConfigurationEntity)); transaction.Add(Operation.Insert(pushConfigsTable, appHandle, PlatformType.Android.ToString(), androidPushNotificationsConfigurationEntity)); transaction.Add(Operation.Insert(pushConfigsTable, appHandle, PlatformType.IOS.ToString(), iosPushNotificationsConfigurationEntity)); await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode()); }
public StringTableTagsCollection(ObjectTable <string> stringTable) { this._stringTable = stringTable; this._tagsList = new List <StringTableTagsCollection.TagEncoded>(); }
public void CopyTo(ObjectTable table) => Fields.CopyTo(table.Fields);
/// <summary> /// Creates a new tags collection. /// </summary> /// <param name="tagsTable"></param> public TagsTableCollection(ObjectTable<Tag> tagsTable) { _tags = new List<uint>(); }
public static int _SelectedCount(this ObjectTable objects) { var count = objects.ObjectCount(_SelectedFilter); return(count); }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> /// <param name="reverseIndex">The reverse index is enable if true.</param> /// <param name="initCapacity">The inital capacity.</param> /// <param name="checkDuplicates">Flag preventing this object table for checking for duplicates. Use this when sure almost all objects will be unique.</param> public TagsTableCollectionIndex(bool reverseIndex, int initCapacity, bool checkDuplicates) { _tagsTable = new ObjectTable<Tag>(true); _tagsCollectionTable = new ObjectTable<OsmTags>(reverseIndex, initCapacity, !checkDuplicates); this.Add(new TagsCollection()); }
/// <summary> /// Creates a new dictionary. /// </summary> /// <param name="stringTable"></param> public StringTableTagsCollection(ObjectTable <string> stringTable) { _stringTable = stringTable; _tagsList = new List <TagEncoded>(); }
/// <summary> /// Creates a new relation. /// </summary> /// <returns></returns> public static CompleteRelation Create(ObjectTable<string> table, long id) { return new CompleteRelation(table, id); }
/// <summary> /// Creates a new node using a given string table with the given id. /// </summary> /// <param name="table"></param> /// <param name="id"></param> /// <returns></returns> public static CompleteNode Create(ObjectTable <string> table, long id) { return(new CompleteNode(table, id)); }
public void TestStringTable_AddStringsTwice() { ObjectTable <string> table = new ObjectTable <string>(false); table.Add("zero"); table.Add("one"); table.Add("two"); table.Add("three"); table.Add("four"); table.Add("five"); table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); Assert.AreEqual((uint)0, table.Add("zero")); Assert.AreEqual((uint)1, table.Add("one")); Assert.AreEqual((uint)2, table.Add("two")); Assert.AreEqual((uint)3, table.Add("three")); Assert.AreEqual((uint)4, table.Add("four")); Assert.AreEqual((uint)5, table.Add("five")); Assert.AreEqual((uint)6, table.Add("six")); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); table = new ObjectTable <string>(true); table.Add("zero"); table.Add("one"); table.Add("two"); table.Add("three"); table.Add("four"); table.Add("five"); table.Add("six"); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); Assert.AreEqual((uint)0, table.Add("zero")); Assert.AreEqual((uint)1, table.Add("one")); Assert.AreEqual((uint)2, table.Add("two")); Assert.AreEqual((uint)3, table.Add("three")); Assert.AreEqual((uint)4, table.Add("four")); Assert.AreEqual((uint)5, table.Add("five")); Assert.AreEqual((uint)6, table.Add("six")); Assert.AreEqual("zero", table.Get(0)); Assert.AreEqual("one", table.Get(1)); Assert.AreEqual("two", table.Get(2)); Assert.AreEqual("three", table.Get(3)); Assert.AreEqual("four", table.Get(4)); Assert.AreEqual("five", table.Get(5)); Assert.AreEqual("six", table.Get(6)); }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> public SimpleTagsIndex() { _tagsTable = new ObjectTable <OsmTags>(true); this.Add(new SimpleTagsCollection()); }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> public OsmTagsIndex(ObjectTable<OsmTags> tags) { //_string_table = string_table; _tags = tags; }
/// <summary> /// Creates a new relation from a SimpleRelation. /// </summary> /// <returns></returns> public static CompleteRelation CreateFrom(ObjectTable<string> table, Relation simpleRelation, IDictionary<long, Node> nodes, IDictionary<long, CompleteWay> ways, IDictionary<long, CompleteRelation> relations) { if (simpleRelation == null) throw new ArgumentNullException("simpleRelation"); if (nodes == null) throw new ArgumentNullException("nodes"); if (ways == null) throw new ArgumentNullException("ways"); if (relations == null) throw new ArgumentNullException("relations"); if (simpleRelation.Id == null) throw new Exception("simpleRelation.Id is null"); var relation = Create(table, simpleRelation.Id.Value); relation.ChangeSetId = simpleRelation.ChangeSetId; foreach (var pair in simpleRelation.Tags) { relation.Tags.Add(pair); } for (var idx = 0; idx < simpleRelation.Members.Count; idx++) { var memberId = simpleRelation.Members[idx].MemberId.Value; var role = simpleRelation.Members[idx].MemberRole; var member = new CompleteRelationMember(); member.Role = role; switch (simpleRelation.Members[idx].MemberType.Value) { case OsmGeoType.Node: Node node = null; if (nodes.TryGetValue(memberId, out node)) { member.Member = node; } else { return null; } break; case OsmGeoType.Way: CompleteWay way = null; if (ways.TryGetValue(memberId, out way)) { member.Member = way; } else { return null; } break; case OsmGeoType.Relation: CompleteRelation relationMember = null; if (relations.TryGetValue(memberId, out relationMember)) { member.Member = relationMember; } else { return null; } break; } relation.Members.Add(member); } relation.TimeStamp = simpleRelation.TimeStamp; relation.User = simpleRelation.UserName; relation.UserId = simpleRelation.UserId; relation.Version = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null; relation.Visible = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value; return relation; }
public void ApplyObjTb(ObjectTable a_refTb) { m_nPow = a_refTb.m_nPow; m_nDef = a_refTb.m_nDef; m_nHP = a_refTb.m_nHP; }
/// <summary> /// Creates a new tags index with a given strings table. /// </summary> public OsmTagsIndex() { //_string_table = string_table; _tags = new ObjectTable<OsmTags>(true); }
/// <summary> /// Creates a new relation using a string table. /// </summary> /// <param name="id"></param> /// <param name="stringTable"></param> protected internal CompleteRelation(ObjectTable<string> stringTable, long id) : base(stringTable, id) { _members = new List<CompleteRelationMember>(); }
/// <summary> /// Creates a new way. /// </summary> /// <returns></returns> public static CompleteWay Create(ObjectTable<string> table, long id) { return new CompleteWay(table, id); }
/// <summary> /// Compiles the dynamic method, returning a delegate that can be used to invoke it. /// </summary> /// <param name="objects">The known objects that can be serialized and deserialized.</param> internal Action Compile(ObjectTable objects = null) { _il.Emit(OpCodes.Ret); return (Action)_method.CreateDelegate(typeof(Action), objects); }
/// <summary> /// Creates a new way using a string table. /// </summary> protected internal CompleteWay(ObjectTable<string> stringTable, long id) : base(stringTable, id) { _nodes = new List<Node>(); }
/// <summary> /// Creates a new relation. /// </summary> /// <param name="table"></param> /// <param name="id"></param> /// <returns></returns> public static CompleteRelation Create(ObjectTable <string> table, long id) { return(new CompleteRelation(table, id)); }
public void GetObjectHandlesNull() { RigidActor actor = ObjectTable.GetObject <RigidActor>(0); Assert.IsNull(actor); }
/// <summary> /// Creates a new way using a string table. /// </summary> internal protected CompleteWay(ObjectTable <string> stringTable, long id) : base(stringTable, id) { _nodes = new List <Node>(); }
/// <summary> /// Creates a new tags collection. /// </summary> /// <param name="tagsTable"></param> public TagsTableCollection(ObjectTable <Tag> tagsTable) { _tags = new List <uint>(); }
/// <summary> /// Creates a new relation from a SimpleRelation. /// </summary> /// <param name="table"></param> /// <param name="simpleRelation"></param> /// <param name="nodes"></param> /// <param name="ways"></param> /// <param name="relations"></param> /// <returns></returns> public static CompleteRelation CreateFrom(ObjectTable <string> table, Relation simpleRelation, IDictionary <long, Node> nodes, IDictionary <long, CompleteWay> ways, IDictionary <long, CompleteRelation> relations) { if (simpleRelation == null) { throw new ArgumentNullException("simpleRelation"); } if (nodes == null) { throw new ArgumentNullException("nodes"); } if (ways == null) { throw new ArgumentNullException("ways"); } if (relations == null) { throw new ArgumentNullException("relations"); } if (simpleRelation.Id == null) { throw new Exception("simpleRelation.Id is null"); } CompleteRelation relation = Create(table, simpleRelation.Id.Value); relation.ChangeSetId = simpleRelation.ChangeSetId; foreach (Tag pair in simpleRelation.Tags) { relation.Tags.Add(pair); } for (int idx = 0; idx < simpleRelation.Members.Count; idx++) { long memberId = simpleRelation.Members[idx].MemberId.Value; string role = simpleRelation.Members[idx].MemberRole; var member = new CompleteRelationMember(); member.Role = role; switch (simpleRelation.Members[idx].MemberType.Value) { case OsmGeoType.Node: Node node = null; if (nodes.TryGetValue(memberId, out node)) { member.Member = node; } else { return(null); } break; case OsmGeoType.Way: CompleteWay way = null; if (ways.TryGetValue(memberId, out way)) { member.Member = way; } else { return(null); } break; case OsmGeoType.Relation: CompleteRelation relationMember = null; if (relations.TryGetValue(memberId, out relationMember)) { member.Member = relationMember; } else { return(null); } break; } relation.Members.Add(member); } relation.TimeStamp = simpleRelation.TimeStamp; relation.User = simpleRelation.UserName; relation.UserId = simpleRelation.UserId; relation.Version = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null; relation.Visible = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value; return(relation); }
/// <summary> /// Update like /// </summary> /// <param name="storageConsistencyMode">Consistency mode</param> /// <param name="likeHandle">Like handle</param> /// <param name="contentHandle">Content handle</param> /// <param name="userHandle">User handle</param> /// <param name="liked">Like status</param> /// <param name="lastUpdatedTime">Last updated time</param> /// <param name="readLikeLookupEntity">Read like lookup entity</param> /// <returns>Update like task</returns> public async Task UpdateLike( StorageConsistencyMode storageConsistencyMode, string likeHandle, string contentHandle, string userHandle, bool liked, DateTime lastUpdatedTime, ILikeLookupEntity readLikeLookupEntity) { CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.Likes); ObjectTable lookupTable = this.tableStoreManager.GetTable(ContainerIdentifier.Likes, TableIdentifier.LikesLookup) as ObjectTable; FeedTable feedTable = this.tableStoreManager.GetTable(ContainerIdentifier.Likes, TableIdentifier.LikesFeed) as FeedTable; CountTable countTable = this.tableStoreManager.GetTable(ContainerIdentifier.Likes, TableIdentifier.LikesCount) as CountTable; Transaction transaction = new Transaction(); LikeFeedEntity likeFeedEntity = new LikeFeedEntity() { LikeHandle = likeHandle, UserHandle = userHandle }; if (readLikeLookupEntity == null) { LikeLookupEntity newLikeLookupEntity = new LikeLookupEntity() { LikeHandle = likeHandle, LastUpdatedTime = lastUpdatedTime, Liked = liked }; transaction.Add(Operation.Insert(lookupTable, contentHandle, userHandle, newLikeLookupEntity)); if (liked) { transaction.Add(Operation.Insert(feedTable, contentHandle, this.tableStoreManager.DefaultFeedKey, likeHandle, likeFeedEntity)); transaction.Add(Operation.InsertOrIncrement(countTable, contentHandle, this.tableStoreManager.DefaultCountKey)); } } else { bool oldLiked = readLikeLookupEntity.Liked; string oldLikeHandle = readLikeLookupEntity.LikeHandle; readLikeLookupEntity.LikeHandle = likeHandle; readLikeLookupEntity.Liked = liked; readLikeLookupEntity.LastUpdatedTime = lastUpdatedTime; transaction.Add(Operation.Replace(lookupTable, contentHandle, userHandle, readLikeLookupEntity as LikeLookupEntity)); if (liked == oldLiked) { if (liked && likeHandle != oldLikeHandle) { transaction.Add(Operation.Delete(feedTable, contentHandle, this.tableStoreManager.DefaultFeedKey, oldLikeHandle)); transaction.Add(Operation.Insert(feedTable, contentHandle, this.tableStoreManager.DefaultFeedKey, likeHandle, likeFeedEntity)); } } else { if (liked) { transaction.Add(Operation.Insert(feedTable, contentHandle, this.tableStoreManager.DefaultFeedKey, likeHandle, likeFeedEntity)); transaction.Add(Operation.Increment(countTable, contentHandle, this.tableStoreManager.DefaultCountKey, 1)); } else { transaction.Add(Operation.Delete(feedTable, contentHandle, this.tableStoreManager.DefaultFeedKey, oldLikeHandle)); transaction.Add(Operation.Increment(countTable, contentHandle, this.tableStoreManager.DefaultCountKey, -1.0)); } } } await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode()); }
public List <PageItem> Process(int Flags, byte[] RecordData) { MemoryStream _ms = null; BinaryReader _br = null; MemoryStream _fs = null; BinaryReader _fr = null; try { _fs = new MemoryStream(BitConverter.GetBytes(Flags)); _fr = new BinaryReader(_fs); //Byte 1 will be ObjectID - a font in the object table byte ObjectID = _fr.ReadByte(); //Byte 2 is the real flags byte RealFlags = _fr.ReadByte(); // 0 1 2 3 4 5 6 7 // X X X X X X X S // if S = type of brush - if S then ARGB, else a brush object in object table _ms = new MemoryStream(RecordData); _br = new BinaryReader(_ms); bool BrushIsARGB = ((RealFlags & (int)Math.Pow(2, 7)) == (int)Math.Pow(2, 7)); Brush b; if (BrushIsARGB) { byte A, R, G, B; B = _br.ReadByte(); G = _br.ReadByte(); R = _br.ReadByte(); A = _br.ReadByte(); b = new SolidBrush(Color.FromArgb(A, R, G, B)); } else { UInt32 BrushID = _br.ReadUInt32(); EMFBrush EMFb = (EMFBrush)ObjectTable[(byte)BrushID]; b = EMFb.myBrush; } UInt32 FormatID = _br.ReadUInt32(); // Index of Optional stringFormatobject in Object Table... UInt32 StringLength = _br.ReadUInt32(); //bounding of string... Single recX = _br.ReadSingle(); Single recY = _br.ReadSingle(); Single recWidth = _br.ReadSingle(); Single recHeight = _br.ReadSingle(); //Array of Chars... char[] StringData = new char[StringLength]; System.Text.UnicodeEncoding d = new System.Text.UnicodeEncoding(); d.GetChars(_br.ReadBytes((int)StringLength * 2), 0, (int)StringLength * 2, StringData, 0); EMFFont EF = (EMFFont)ObjectTable[(byte)ObjectID]; Font f = EF.myFont; StringFormat sf; if (ObjectTable.Contains((byte)FormatID)) { EMFStringFormat ESF = (EMFStringFormat)ObjectTable[(byte)FormatID]; sf = ESF.myStringFormat; } else { sf = new StringFormat(); } DoInstructions(f, sf, b, recX, recY, recWidth, recHeight, new String(StringData)); return(items); } finally { if (_br != null) { _br.Close(); } if (_ms != null) { _ms.Dispose(); } if (_fr != null) { _fr.Close(); } if (_fs != null) { _fs.Dispose(); } } }
/// <summary> /// Insert a new user-generated report of content into the store /// </summary> /// <param name="storageConsistencyMode">consistency to use</param> /// <param name="reportHandle">uniquely identifies this report</param> /// <param name="contentType">the type of content being reported</param> /// <param name="contentHandle">uniquely identifies the content</param> /// <param name="contentUserHandle">uniquely identifies the user who authored the content</param> /// <param name="reportingUserHandle">uniquely identifies the user doing the reporting</param> /// <param name="appHandle">uniquely identifies the app that the content came from</param> /// <param name="reason">the complaint against the content</param> /// <param name="createdTime">when the report was received</param> /// <param name="hasComplainedBefore">has the reporting user complained about this content before?</param> /// <returns>a task that inserts the report into the store</returns> public async Task InsertContentReport( StorageConsistencyMode storageConsistencyMode, string reportHandle, ContentType contentType, string contentHandle, string contentUserHandle, string reportingUserHandle, string appHandle, ReportReason reason, DateTime createdTime, bool hasComplainedBefore) { // get all the table interfaces CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.ContentReports); ObjectTable lookupTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsLookup) as ObjectTable; ObjectTable lookupUniquenessTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsLookupUniquenessByReportingUser) as ObjectTable; FeedTable feedByAppTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsRecentFeedByApp) as FeedTable; FeedTable feedByContentTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsRecentFeedByContent) as FeedTable; FeedTable feedByContentUserTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsRecentFeedByContentUser) as FeedTable; FeedTable feedByReportingUserTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsRecentFeedByReportingUser) as FeedTable; CountTable countByContentTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsCountByContent) as CountTable; CountTable countByContentUserTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsCountByContentUser) as CountTable; CountTable countByReportingUserTable = this.tableStoreManager.GetTable(ContainerIdentifier.ContentReports, TableIdentifier.ContentReportsCountByReportingUser) as CountTable; // create the two entities that will be inserted into the tables ContentReportEntity contentReportEntity = new ContentReportEntity() { ContentType = contentType, ContentHandle = contentHandle, ContentUserHandle = contentUserHandle, ReportingUserHandle = reportingUserHandle, AppHandle = appHandle, Reason = reason, CreatedTime = createdTime }; ContentReportFeedEntity contentReportFeedEntity = new ContentReportFeedEntity() { ReportHandle = reportHandle, ContentType = contentType, ContentHandle = contentHandle, ContentUserHandle = contentUserHandle, ReportingUserHandle = reportingUserHandle, AppHandle = appHandle }; // do the inserts and increments as a transaction Transaction transaction = new Transaction(); // the partition key is app handle for all tables so that a transaction can be achieved transaction.Add(Operation.Insert(lookupTable, appHandle, reportHandle, contentReportEntity)); transaction.Add(Operation.Insert(feedByAppTable, appHandle, appHandle, reportHandle, contentReportFeedEntity)); transaction.Add(Operation.Insert(feedByContentTable, appHandle, contentHandle, reportHandle, contentReportFeedEntity)); // only add to the feedByContentUserTable if this is user-generated content if (!string.IsNullOrWhiteSpace(contentUserHandle)) { transaction.Add(Operation.Insert(feedByContentUserTable, appHandle, contentUserHandle, reportHandle, contentReportFeedEntity)); } transaction.Add(Operation.Insert(feedByReportingUserTable, appHandle, reportingUserHandle, reportHandle, contentReportFeedEntity)); // if the reporting user has not previously reported this content, then increment counts if (!hasComplainedBefore) { string uniquenessKey = UniquenessObjectKey(contentHandle, reportingUserHandle); transaction.Add(Operation.Insert(lookupUniquenessTable, appHandle, uniquenessKey, new ObjectEntity())); transaction.Add(Operation.InsertOrIncrement(countByContentTable, appHandle, contentHandle)); // only increment the countByContentUserTable if this is user-generated content if (!string.IsNullOrWhiteSpace(contentUserHandle)) { transaction.Add(Operation.InsertOrIncrement(countByContentUserTable, appHandle, contentUserHandle)); } transaction.Add(Operation.InsertOrIncrement(countByReportingUserTable, appHandle, reportingUserHandle)); } // execute the transaction await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode()); }