예제 #1
0
파일: RIDTests.cs 프로젝트: SaberMK/BiBi
        public void CanCreateRID()
        {
            RID rid = new RID(1, 2);;

            Assert.AreEqual(1, rid.BlockNumber);
            Assert.AreEqual(2, rid.Id);
        }
예제 #2
0
    private void AddMesh()
    {
        Vector3[] vertices = new Vector3[] {
            new Vector3(-5f, 0f, -5f),
            new Vector3(5f, 0f, -5f),
            new Vector3(5f, 0f, 5f),
            new Vector3(-5f, 0f, 5f)
        };
        Vector3[] normals = new Vector3[] {
            Vector3.Up,
            Vector3.Up,
            Vector3.Up,
            Vector3.Up
        };
        int[] indices = new int[] { 0, 1, 2, 0, 2, 3 };

        Godot.Collections.Array meshData = new Godot.Collections.Array();
        meshData.Resize((int)Mesh.ArrayType.Max);
        meshData[(int)Mesh.ArrayType.Vertex] = vertices;
        meshData[(int)Mesh.ArrayType.Normal] = normals;
        meshData[(int)Mesh.ArrayType.Index]  = indices;

        _mesh = VisualServer.MeshCreate();
        VisualServer.MeshAddSurfaceFromArrays(_mesh, VisualServer.PrimitiveType.Triangles, meshData);

        _instance = VisualServer.InstanceCreate();
        VisualServer.InstanceSetBase(_instance, _mesh);

        RID scenario = GetWorld().Scenario;

        VisualServer.InstanceSetScenario(_instance, scenario);
    }
예제 #3
0
        /// <summary>
        /// Uses the VisualServer to draw each of an entity's split sprites, by:
        ///     1. Obtaining the Node2D that is designated to play host to a given split sprite
        ///     2. Changing the Node2D's (TileMap) parent if required
        ///     3. Creating an RID for the canvas item (the sprite drawing) and storing it so it can be freed later
        /// </summary>
        /// <param name="tileMaps"></param>
        /// <param name="tileMapZIndex"></param>
        /// <param name="entityPos"></param>
        /// <param name="entityDrawPos">Offsets the sprite upwards. Used for drawing entities falling/jumping.</param>
        public void DrawSplitSprites(TileMapList tileMaps, int tileMapZIndex, Vector2 entityPos, float entityDrawPos /*State goes here*/)
        {
            List <SplitSpriteSheetValue> splitSprites = this._splitSpriteSheet.GetSplitSpriteInfoForAnim("idle", 0); //TODO match to entity anim state

            foreach (SplitSpriteSheetValue splitSprite in splitSprites)
            {
                Node2D  splitNode2D = this._idToSplitNodes[splitSprite.splitIndex];
                TileMap tileMap     = tileMaps[tileMapZIndex + splitSprite.zIndex];
                if (splitNode2D.GetParent() != tileMap)
                {
                    if (splitNode2D.GetParent() != null)
                    {
                        splitNode2D.GetParent().RemoveChild(splitNode2D);
                    }
                    tileMap.AddChild(splitNode2D);
                }

                RID splitSpriteRID = VisualServer.CanvasItemCreate();
                this._drawnSprites.Add(splitSpriteRID);
                VisualServer.CanvasItemSetParent(splitSpriteRID, splitNode2D.GetCanvasItem());

                VisualServer.CanvasItemAddTextureRectRegion(splitSpriteRID,
                                                            new Rect2(Vector2.Zero, splitSprite.size),
                                                            this._splitSpriteSheet.GetSpriteSheetRID(),
                                                            new Rect2(splitSprite.sheetPos, splitSprite.size),
                                                            new Color(1, 1, 1, 1),
                                                            false,
                                                            this._splitSpriteSheet.GetSpriteSheetRID());

                VisualServer.CanvasItemSetTransform(splitSpriteRID, new Transform2D(0, this._relativePos - new Vector2(Globals.TileWidth / 2, Globals.TileHeight / 2) + new Vector2(0, entityDrawPos)));

                splitNode2D.Position = entityPos + splitSprite.splitPos + new Vector2(Globals.TileWidth / 2, Globals.TileHeight / 2);
            }
        }
예제 #4
0
        private void StartRun(object sender, RoutedEventArgs e)
        {
            int urlType = 5;

            if ((Boolean)lengthFive.IsChecked)
            {
                urlType = 5;
            }
            if ((Boolean)lengthSix.IsChecked)
            {
                urlType = 6;
            }
            if ((Boolean)lengthSeven.IsChecked)
            {
                urlType = 7;
            }
            int parsedResult;

            int.TryParse(this.runLength.Text, out parsedResult);
            if (parsedResult == 0)
            {
                MessageBox.Show("Length is not a number or is zero!", "Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            if (selectedDirectory.Text == "")
            {
                MessageBox.Show("Please select a directory!", "Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            RID.KickOff(selectedDirectory.Text, urlType, parsedResult);
        }
예제 #5
0
파일: MyRM.cs 프로젝트: vlung/Citicenter
        public bool Delete(Transaction context, RID rId, int count)
        {
            // enlist with TM
            this.Enlist(context);

            // read in the resource
            Resource data    = null;
            bool     removed = this.dataStore.Read(context, rId, out data);

            if (!removed ||
                null == data)
            {
                // silently discard
                return(false);
            }

            // update the resource
            if (data.getCount() > count)
            {
                data.decrCount(count);
            }
            else
            {
                data.setCount(0);
            }

            // write the resource back
            return(this.dataStore.Write(context, rId, data));
        }
예제 #6
0
        //加载窗口
        private void A_returnBook_Load(object sender, EventArgs e)
        {
            SqlConnection conn = SQLbase.getConn();

            try
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Open();
                SqlCommand    selectCmd = new SqlCommand("select * from returntable", conn);
                SqlDataReader datareader = selectCmd.ExecuteReader();
                string        RID, BID, Bname;
                int           rowindex = 0;
                this.datagridview.Rows.Clear();
                while (datareader.Read())
                {
                    RID   = datareader["RID"].ToString();
                    Bname = datareader["Bname"].ToString();
                    BID   = datareader["BID"].ToString();

                    rowindex = this.datagridview.Rows.Add();
                    //trim函数同于去除字符串两头的空格
                    this.datagridview.Rows[rowindex].Cells[0].Value = RID.Trim();
                    this.datagridview.Rows[rowindex].Cells[1].Value = BID.Trim();
                    this.datagridview.Rows[rowindex].Cells[2].Value = Bname.Trim();
                }
            }
            catch
            {
                MessageBox.Show("操作错误!");
            }
        }
예제 #7
0
        /// <summary>
        /// Deletes certain amount of resource.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="rid"></param>
        /// <param name="count"></param>
        /// <returns>true the given resources exists. False if not</returns>
        public bool Delete(Transaction context, RID rid, int count)
        {
            WaitForReady();
            Enlist(context);

            _lockManager.LockForWrite(context, rid);
            Resource resource = _transactionStorage.Read(context, rid);

            if (resource == null)
            {
                // silently discard
                return(false);
            }
            if (resource.getCount() > count)
            {
                resource.decrCount(count);
            }
            else
            {
                resource.setCount(0);
            }

            _transactionStorage.Write(context, rid, resource);
            return(true);
        }
예제 #8
0
        /// <summary>
        /// Reserve a list of resources for a customer
        /// Decrease all reserved resources by 1.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="c"></param>
        /// <param name="i"></param>
        /// <returns>true if reservation is successful</returns>
        public bool Reserve(Transaction context, Customer c, RID i)
        {
            WaitForReady();
            Enlist(context);

            _lockManager.LockForWrite(context, c);
            _lockManager.LockForWrite(context, i);
            Resource resource = _transactionStorage.Read(context, i);

            if (resource == null)
            {
                throw new InvalidOperationException(i + " does not exist!");
            }
            if (resource.getCount() == 0)
            {
                return(false);
            }

            HashSet <RID> r = _transactionStorage.Read(context, c) ?? new HashSet <RID>();

            r.Add(resource.getID());

            Console.WriteLine("Reserving flight: Stops={0}", r.Count);
            _transactionStorage.Write(context, c, r);

            resource.decrCount();
            _transactionStorage.Write(context, i, resource);
            return(true);
        }
예제 #9
0
        /// <param name="c">Customer</param>
        /// <param name="flights">array of flight names</param>
        /// <param name="location">room location if room is true</param>
        /// <param name="car">true if request is for a car</param>
        /// <param name="room">true if request is for a room</param>
        /// <returns>price of reservation</returns>
        public bool ReserveItinerary(TP.Customer c, string[] flights, string location, bool car, bool room)
        {
            TP.Transaction tid = TransactionManager.Start();

            try
            {
                if (car)
                {
                    Cars.Reserve(tid, c, RID.forCar(location));
                }

                if (room)
                {
                    Rooms.Reserve(tid, c, RID.forRoom(location));
                }

                foreach (string flight in flights)
                {
                    Flights.Reserve(tid, c, RID.forFlight(flight));
                }

                TransactionManager.Commit(tid);
            }
            catch (Exception e)
            {
                TransactionManager.Abort(tid);
                throw;
            }
            return(true);
        }
예제 #10
0
        private void UnLockResource(Transaction context, MyLM.LockMode mode, RID rId)
        {
            LockableID id = new LockableID(
                ResourceLockPrefix, new LockableID(rId.ToString()));

            this.UnLock(context, mode, id);
        }
예제 #11
0
 public Area2DMonitor(RID areaRID, int zIndex, List <ConvexPolygonShape2D> areaShapes, TinyMessengerHub toEntityHub)
 {
     this._areaRID     = areaRID;
     this._zIndex      = zIndex;
     this._areaShapes  = areaShapes;
     this._toEntityHub = toEntityHub;
 }
예제 #12
0
        public void LockConversionTest3()
        {
            MyLM target = new MyLM();

            target.setDeadlockTimeout(1000);
            Transaction context  = new Transaction();
            Transaction context2 = new Transaction();
            Lockable    resource = new RID(RID.Type.CAR, "test");

            target.LockForUpdate(context, resource);
            target.LockForRead(context2, resource);
            ManualResetEvent e = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem((obj) =>
            {
                Thread.Sleep(200);
                target.UnlockRead(context2, resource);
                e.Set();
            });
            target.LockForWrite(context, resource);
            if (!e.WaitOne(2000))
            {
                Assert.Fail("Failed");
            }
        }
예제 #13
0
 /// <summary>
 /// Creates and returns a dictionary that maps a TileMap's StaticBody2D's RID to said TileMap's walls or ledges.
 /// </summary>
 /// <param name="tileMaps">List of TileMaps.</param>
 /// <param name="tileMapToSB2Ds">Map of TileMap to its SB2D, whether its origin was a wall or ledge.</param>
 /// <param name="perimData">Data of all perimeters of all TileMaps.</param>
 /// <param name="ledgeData">Data of all ledges of all TileMaps.</param>
 /// <param name="option">Whether this function is being used to construct segments for walls or ledges.</param>
 /// <returns>A dictionary that maps a TileMap's SB2D RID to said TileMap's walls.</returns>
 public static Dictionary<RID, List<SegmentShape2D>> ConstructSB2DSegments(this TileMapList tileMaps,
                                                                           Dictionary<TileMap, RID> tileMapToSB2Ds,
                                                                           PerimeterData perimData,
                                                                           LedgeData ledgeData,
                                                                           StaticBodyOrigin option)
 {
     if (tileMaps is null) throw new ArgumentNullException(nameof(tileMaps));
     if (tileMapToSB2Ds is null) throw new ArgumentNullException(nameof(tileMapToSB2Ds));
     if (perimData is null) throw new ArgumentNullException(nameof(perimData));
     if (ledgeData is null) throw new ArgumentNullException(nameof(ledgeData));
     
     var sb2dToSegments = new Dictionary<RID, List<SegmentShape2D>>();
     foreach (TileMap tileMap in tileMaps.Values)
     {
         RID wall = tileMapToSB2Ds[tileMap];
         List<SegmentShape2D> segments = (option == StaticBodyOrigin.Wall) ?
                                               _GetWallSegments(tileMaps, tileMap, perimData) :
                                               _GetLedgeSegments(tileMaps, tileMap, ledgeData);
         sb2dToSegments.Add(wall, segments);
         foreach (SegmentShape2D segment in segments)
         {
             Physics2DServer.BodyAddShape(wall, segment.GetRid());
         }
     }
     return sb2dToSegments;
 }
예제 #14
0
        /// <summary>
        /// Set all walls and ledges that are not on the same z index as some entity to ignore it.
        /// Passed from entity MessageHub subscription and is fired when EntityTracker detects that an entity has changed z index.
        /// </summary>
        /// <param name="msg"></param>
        private void _HandleEntityChangedZIndex(EntityChangedZIndexMessage msg)
        {
            RID entityRID = msg.GetEntityRID();
            int zIndex    = msg.GetZIndex();

            GD.PrintS("requested that entity with id: " + entityRID.GetId() + " be moved to collide with segments on z index: " + zIndex);

            foreach (TileMap tileMap in this._tileMapToWallSB2Ds.Keys)
            {
                if (tileMap.ZIndex == zIndex)
                {
                    Physics2DServer.BodyRemoveCollisionException(this._tileMapToWallSB2Ds[tileMap], entityRID);
                }
                else
                {
                    Physics2DServer.BodyAddCollisionException(this._tileMapToWallSB2Ds[tileMap], entityRID);
                }
            }
            foreach (TileMap tileMap in this._tileMapToLedgeSB2Ds.Keys)
            {
                if (tileMap.ZIndex == zIndex)
                {
                    Physics2DServer.BodyRemoveCollisionException(this._tileMapToLedgeSB2Ds[tileMap], entityRID);
                    GD.PrintS("removed collision with sb2d with id: " + this._tileMapToLedgeSB2Ds[tileMap].GetId());
                }
                else
                {
                    Physics2DServer.BodyAddCollisionException(this._tileMapToLedgeSB2Ds[tileMap], entityRID);
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Write the resource to the shadow
        /// It supports multiple transactions
        /// </summary>
        /// <param name="context">Design for supporting multiple transactions</param>
        /// <param name="key"> </param>
        /// <param name="resource"> </param>
        /// <returns>success</returns>
        public void Write(Transaction context, RID key, Resource resource)
        {
            this.NumberWrites++;
            SelfDestructing();
            var row = SerializationHelper.ConvertResourceToRow(resource);

            _simpleDatabase.UpsertRecord(context, Constants.ResourcesTableName, key.ToString(), row);
        }
예제 #16
0
 public void insert(Constant val, RID rid)
 {//向TableScan相应桶中插入一条新纪录
     beforeFirst(val);
     ts.insert();
     ts.setInt("block", rid.blockNumber());
     ts.setInt("id", rid.Id());
     ts.setVal("dataval", val);
 }
 internal Physics2DSpaceQueryResult(Dictionary dict)
 {
     CollidingObject = (CollisionObject2D)dict["collider"];
     ColliderId      = (int)dict["collider_id"];
     Metadata        = dict["metadata"];
     IntersectingRid = (RID)dict["rid"];
     ShapeIndex      = (int)dict["shape"];
 }
예제 #18
0
 public Reservation(Customer rID, RID[] resources)
 {
     this.Id = rID;
     this.Resources = new List<RID>();
     if (null != resources)
     {
         this.Resources.AddRange(resources);
     }
 }
예제 #19
0
        public void MoveToRID(RID rid)
        {
            var updateScan = _scan as IUpdateScan;

            if (updateScan != null)
            {
                updateScan.MoveToRID(rid);
            }
        }
예제 #20
0
 public void LockConversionTest1()
 {
     MyLM target = new MyLM();
     target.setDeadlockTimeout(1000);
     Transaction context = new Transaction();
     Lockable resource = new RID(RID.Type.CAR, "test");
     target.LockForUpdate(context, resource);
     target.LockForWrite(context, resource);
 }
예제 #21
0
        public void LM_DowngradeWriteLockToReadLock()
        {
            MyLM lm   = new MyLM();
            RID  res1 = new RID();

            Transaction t1 = new Transaction();

            lm.LockForWrite(t1, res1);
            lm.LockForRead(t1, res1);
        }
예제 #22
0
        public void LM_DowngradeWriteLockToReadLock()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();

            lm.LockForWrite(t1, res1);
            lm.LockForRead(t1, res1);
        }
예제 #23
0
        public void UnlockWriteTest()
        {
            MyLM        target   = new MyLM();
            Transaction context  = new Transaction();
            Transaction context2 = new Transaction();
            Lockable    resource = new RID(RID.Type.CAR, "test");

            target.LockForWrite(context, resource);
            target.UnlockWrite(context, resource);
            target.LockForWrite(context2, resource);
        }
예제 #24
0
        public void LockConversionTest1()
        {
            MyLM target = new MyLM();

            target.setDeadlockTimeout(1000);
            Transaction context  = new Transaction();
            Lockable    resource = new RID(RID.Type.CAR, "test");

            target.LockForUpdate(context, resource);
            target.LockForWrite(context, resource);
        }
예제 #25
0
        public void LM_GetReadLockForManyTransactions()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.LockForRead(t1, res1);
            lm.LockForRead(t2, res1);
        }
예제 #26
0
        public void LM_UpgradeReadLockToWriteLock5()
        {
            MyLM lm   = new MyLM();
            RID  res1 = new RID();

            Transaction t1 = new Transaction();

            lm.LockForRead(t1, res1);
            lm.LockForWrite(t1, res1);
            lm.LockForWrite(t1, res1); // This should be a noop since the transaction already has a write lock on the resource.
        }
예제 #27
0
        public void LM_GetReadLockForManyTransactions()
        {
            MyLM lm   = new MyLM();
            RID  res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.LockForRead(t1, res1);
            lm.LockForRead(t2, res1);
        }
예제 #28
0
 public void AddTest()
 {
     MyRM.MyRM_Accessor rm = MockRM("AddTest");
     Transaction context = new Transaction();
     RID i = new RID(RID.Type.ROOM, "test1");
     int count = 1;
     int price = 3;
     rm.Add(context, i, count, price);
     rm.Prepare(context);
     rm.Commit(context);
     Assert.AreEqual(price, rm.QueryPrice(context, i));
 }
예제 #29
0
        public void LockForReadTest()
        {
            MyLM target = new MyLM();

            target.setDeadlockTimeout(1000);
            Transaction context  = new Transaction();
            Transaction context2 = new Transaction();
            Lockable    resource = new RID(RID.Type.CAR, "test");

            target.LockForRead(context, resource);
            target.LockForRead(context2, resource);
        }
예제 #30
0
        public void LM_UpgradeReadLockToWriteLock4()
        {
            MyLM lm   = new MyLM();
            RID  res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.setDeadlockTimeout(500); // Shorten deadlock timeout to speed up unit test
            lm.LockForWrite(t2, res1);
            lm.LockForWrite(t1, res1);
        }
예제 #31
0
 /// <summary>
 /// Reads the requested resource from the storage
 /// </summary>
 /// <param name="context">Design for supporting multiple transactions</param>
 /// <param name="key"></param>
 /// <returns></returns>
 public Resource Read(Transaction context, RID key)
 {
     try
     {
         var record = _simpleDatabase.ReadRecord(context, Constants.ResourcesTableName, key.ToString());
         return(SerializationHelper.ConvertRowToResource(record));
     }
     catch (RecordNotFoundException)
     {
         return(null);
     }
 }
예제 #32
0
 public void delete(Constant val, RID rid)
 {//删除 TableScan 中相应桶中指定的记录
     beforeFirst(val);
     while (next())
     {
         if (getDataRid().Equals(rid))
         {
             ts.delete();
             return;
         }
     }
 }
예제 #33
0
        public void LM_GetWritelockOnResLockedWithWriteLock()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.setDeadlockTimeout(500); // Shorten deadlock timeout to speed up unit test
            lm.LockForWrite(t1, res1);
            lm.LockForWrite(t2, res1);
        }
예제 #34
0
        public void LM_GetWritelockOnResLockedWithReadLock()
        {
            MyLM lm   = new MyLM();
            RID  res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.setDeadlockTimeout(500); // Shorten deadlock timeout to speed up unit test
            lm.LockForRead(t1, res1);
            lm.LockForWrite(t2, res1);
        }
예제 #35
0
파일: MyRM.cs 프로젝트: vlung/Citicenter
        public bool Reserve(Transaction context, Customer customer, RID resource)
        {
            // enlist with TM
            this.Enlist(context);

            // get the resource info
            Resource item   = null;
            bool     result = this.dataStore.Read(context, resource, out item);

            if (!result)
            {
                throw new InvalidOperationException(resource + " does not exist!");
            }
            if (item.getCount() <= 0)
            {
                return(false);
            }

            // get the reservation record
            Reservation data = null;

            result = this.dataStore.Read(context, customer, out data);
            if (!result)
            {
                data = new Reservation(customer);
            }

            // only allow one reservation per item
            if (data.Resources.Contains(resource))
            {
                return(false);
            }

            // update the data
            data.Resources.Add(resource);
            item.decrCount();

            // write back the records
            result = this.dataStore.Write(context, customer, data);
            if (!result)
            {
                return(result);
            }

            result = this.dataStore.Write(context, resource, item);
            if (!result)
            {
                return(result);
            }

            return(true);
        }
 public void AbortTest()
 {
     Transaction context = new Transaction();
     RID rid = new RID(RID.Type.FLIGHT, "test");
     var db = CreateDatabase();
     TransactionStorage tr = new TransactionStorage(db);
     tr.Write(context, rid, new Resource(rid, 10, 11));
     //Resource res = tr.Read(context, rid);
     //Assert.AreEqual(11, res.getPrice());
     tr.Abort(context);
     var res = tr.Read(context, rid);
     Assert.IsNull(res, "Transaction aborted, but record still there");
 }
        public void WriteDeleteBeforeCommit()
        {
            Transaction        context = new Transaction();
            RID                rid     = new RID(RID.Type.FLIGHT, "test");
            var                db      = CreateDatabase();
            TransactionStorage tr      = new TransactionStorage(db);

            tr.Write(context, rid, new Resource(rid, 10, 11));
            tr.Delete(context, rid);
            Resource res = tr.Read(context, rid);

            Assert.IsNull(res);
        }
예제 #38
0
 public void LockConversionTest2()
 {
     MyLM target = new MyLM();
     target.setDeadlockTimeout(1000);
     Transaction context = new Transaction();
     Transaction context2 = new Transaction();
     Lockable resource = new RID(RID.Type.CAR, "test");
     target.setDeadlockTimeout(10);
     target.LockForUpdate(context, resource);
     target.LockForRead(context2, resource);
     target.LockForWrite(context, resource);
     Assert.Fail("shall not reach this line");
 }
 public void DeleteTest1()
 {
     Transaction context = new Transaction();
     RID rid = new RID(RID.Type.FLIGHT, "test");
     Customer c = new Customer();
     HashSet<RID> reservations = new HashSet<RID> {rid};
     var db = CreateDatabase();
     TransactionStorage tr = new TransactionStorage(db);
     tr.Write(context, c, reservations);
     tr.Delete(context, c);
     List<Customer> cs = new List<Customer>(tr.GetCustomers(context));
     Assert.AreEqual(0, cs.Count);
 }
 public void CommitTest()
 {
     Transaction context = new Transaction();
     Transaction context1 = new Transaction();
     RID rid = new RID(RID.Type.FLIGHT, Guid.NewGuid().ToString().Substring(0, 24));
     var db = CreateDatabase();
     TransactionStorage tr = new TransactionStorage(db);
     tr.Write(context, rid, new Resource(rid, 10, 11));
     Resource res = tr.Read(context1, rid);
     Assert.IsNull(res);
     tr.Prepare(context);
     tr.Commit(context);
     res = tr.Read(context, rid);
     Assert.AreEqual(11, res.getPrice());
 }
예제 #41
0
        public void AddResource(RID resource)
        {
            if (null == this.resourceList)
            {
                this.resourceList = new List<RID>();
            }

            if (this.resourceList.Contains(resource))
            {
                // already have this resource
                return;
            }

            this.resourceList.Add(resource);
        }
 /// <summary>
 /// Deletes reservations for a customer
 /// </summary>
 /// <param name="context">Design for supporting multiple transactions</param>
 /// <param name="key"></param>
 /// <returns></returns>
 public bool Delete(Transaction context, RID key)
 {
     //TransactionData currentShadow = CreateShadowIfNotExists(context);
     //return currentShadow.Resources.Remove(key);
     this.NumberWrites++;
     SelfDestructing();
     try
     {
         _simpleDatabase.DeleteRecord(context, Constants.ResourcesTableName, key.ToString());
         return true;
     }
     catch(RecordNotFoundException)
     {
         return false;
     }
 }
예제 #43
0
파일: MyRM.cs 프로젝트: vlung/Citicenter
        /// <summary>
        /// Adds a resource to the available ones
        /// </summary>
        /// <param name="context"></param>
        /// <param name="rId"></param>
        /// <param name="count"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        public bool Add(Transaction context, RID rId, int count, int price)
        {
            // enlist with TM
            this.Enlist(context);

            // read the resource
            Resource data = null;
            bool result = this.dataStore.Read(context, rId, out data);
            if (!result)
            {
                data = new Resource(rId);
            }

            // update the item
            data.incrCount(count);
            data.setPrice(price);

            // write the resource
            return this.dataStore.Write(context, rId, data);
        }
예제 #44
0
 public void LockConversionTest3()
 {
     MyLM target = new MyLM();
     target.setDeadlockTimeout(1000);
     Transaction context = new Transaction();
     Transaction context2 = new Transaction();
     Lockable resource = new RID(RID.Type.CAR, "test");
     target.LockForUpdate(context, resource);
     target.LockForRead(context2, resource);
     ManualResetEvent e = new ManualResetEvent(false);
     ThreadPool.QueueUserWorkItem((obj) =>
     {
         Thread.Sleep(200);
         target.UnlockRead(context2, resource);
         e.Set();
     });
     target.LockForWrite(context, resource);
     if (!e.WaitOne(2000))
     {
         Assert.Fail("Failed");
     }
 }
예제 #45
0
        public void LM_UpgradeReadLockToWriteLock4()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();

            lm.setDeadlockTimeout(500); // Shorten deadlock timeout to speed up unit test
            lm.LockForWrite(t2, res1);
            lm.LockForWrite(t1, res1);
        }
예제 #46
0
 public void UnlockWriteTest()
 {
     MyLM target = new MyLM();
     Transaction context = new Transaction();
     Transaction context2 = new Transaction();
     Lockable resource = new RID(RID.Type.CAR, "test");
     target.LockForWrite(context, resource);
     target.UnlockWrite(context, resource);
     target.LockForWrite(context2, resource);
 }
 /// <summary>
 /// Write the resource to the shadow
 /// It supports multiple transactions
 /// </summary>
 /// <param name="context">Design for supporting multiple transactions</param>
 /// <param name="key"> </param>
 /// <param name="resource"> </param>
 /// <returns>success</returns>
 public void Write(Transaction context, RID key, Resource resource)
 {
     this.NumberWrites++;
     SelfDestructing();
     var row = SerializationHelper.ConvertResourceToRow(resource);
     _simpleDatabase.UpsertRecord(context, Constants.ResourcesTableName, key.ToString(), row);
 }
예제 #48
0
        public void LM_UpgradeReadLockToWriteLock2()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();

            LM_Rid_Bundle param = new LM_Rid_Bundle(lm, res1);

            Thread thread = new Thread(AttemptWriteLockOnResource);

            lm.setDeadlockTimeout(3000); // Shorten deadlock timeout to 3 seconds speed up unit test
            lm.LockForRead(t1, res1);
            thread.Start(param);
            Thread.Sleep(1000);
            lm.LockForWrite(t1, res1);
            thread.Join();
            // Make sure that the second thread failed with deadlock exception.
            // This should happen because the first thread is still holding either the read lock or write lock
            // when the second thread trys to acquire a write lock. The second thread won't be able to steal the
            // lock from the first thread because two phase locking was used when the LM upgrades the read lock
            // to a write lock.
            Assert.AreEqual(param.status, 1);
        }
예제 #49
0
 public LM_Rid_Bundle(MyLM lm, RID rid)
 {
     this.lm = lm; this.rid = rid; status = 0; event1 = new AutoResetEvent(false);
 }
예제 #50
0
 public Resource(RID rId, int c, int p)
 {
     this._rId = rId;
     this._count = c;
     this._price = p;
 }
예제 #51
0
 public Resource(RID rId)
 {
     this._rId = rId;
 }
예제 #52
0
 public void DeleteTest()
 {
     string rmName = "DeleteTest" + Guid.NewGuid();
     MyRM.MyRM_Accessor rm = MockRM(rmName);
     Transaction context = new Transaction();
     Customer c = new Customer();
     RID rid = new RID(RID.Type.ROOM, "test1");
     int count = 5;
     int price = 3;
     Assert.IsFalse(rm.Delete(context, rid));
     rm.Add(context, rid, count, price);
     rm.Delete(context, rid, 2);
     Assert.AreEqual(3, rm.Query(context, rid));
     rm.Reserve(context, c, rid);
     rm.Delete(context, rid);
     Assert.AreEqual(0, rm.QueryReservedPrice(context, c));
     Assert.IsTrue(string.IsNullOrEmpty(rm.QueryReserved(context, c)));
     rm.Query(context, rid);
     Assert.Fail("shall not hit this line.");
 }
 /// <summary>
 /// Reads the requested resource from the storage
 /// </summary>
 /// <param name="context">Design for supporting multiple transactions</param>
 /// <param name="key"></param>
 /// <returns></returns>
 public Resource Read(Transaction context, RID key)
 {
     try
     {
         var record = _simpleDatabase.ReadRecord(context, Constants.ResourcesTableName, key.ToString());
         return SerializationHelper.ConvertRowToResource(record);
     }
     catch(RecordNotFoundException)
     {
         return null;
     }
 }
예제 #54
0
 public void UnReserveTest()
 {
     MyRM.MyRM_Accessor rm = MockRM("UnReserveTest");
     Transaction context = new Transaction();
     Customer c = new Customer();
     RID rid = new RID(RID.Type.ROOM, "test1");
     RID rid1 = new RID(RID.Type.CAR, "test1");
     int count = 5;
     int price = 3;
     Assert.IsFalse(rm.Delete(context, rid));
     rm.Add(context, rid, count, price);
     rm.Add(context, rid1, count, price);
     rm.Reserve(context, c, rid);
     Assert.AreEqual(count, rm.Query(context, rid1));
     Assert.AreEqual(count - 1, rm.Query(context, rid));
     rm.UnReserve(context, c);
     Assert.AreEqual(count, rm.Query(context, rid1));
     Assert.AreEqual(count, rm.Query(context, rid));
 }
 public void ReadWriteTest()
 {
     Transaction context = new Transaction();
     RID rid = new RID(RID.Type.FLIGHT, "test");
     Customer c = new Customer();
     HashSet<RID> reservations = new HashSet<RID> {rid};
     var db = CreateDatabase();
     TransactionStorage tr = new TransactionStorage(db);
     tr.Write(context, c, reservations);
     HashSet<RID> actual = tr.Read(context, c);
     Assert.IsTrue(reservations.SetEquals(actual));
 }
예제 #56
0
        public void LM_UpgradeReadLockToWriteLock5()
        {
            MyLM lm = new MyLM();
            RID res1 = new RID();

            Transaction t1 = new Transaction();

            lm.LockForRead(t1, res1);
            lm.LockForWrite(t1, res1);
            lm.LockForWrite(t1, res1); // This should be a noop since the transaction already has a write lock on the resource.
        }
        public void SetResourcesTest()
        {
            var db = CreateDatabase();
            var target = new TransactionStorage(db);
            var resources = new Dictionary<RID, Resource>();
            var rid1 = new RID(TP.RID.Type.ROOM, "Motel6");
            resources.Add(rid1, new Resource(rid1, 1000, 20));
            var rid2 = new RID(TP.RID.Type.FLIGHT, "53");
            resources.Add(rid2, new Resource(rid2, 260, 550));

            // TODO: need to fix this because the class signiture changed
            //target.SetResources(resources);

            //var result = target.GetResources();
            //Assert.IsTrue(result.ContainsKey(rid1));
            //Assert.IsTrue(result.ContainsKey(rid2));

            //Assert.AreEqual(260, result[rid2].getCount());
            //Assert.AreEqual(550, result[rid2].getPrice());
            //Assert.AreEqual("53", result[rid2].getName());
        }
 public void WriteDeleteBeforeCommit()
 {
     Transaction context = new Transaction();
     RID rid = new RID(RID.Type.FLIGHT, "test");
     var db = CreateDatabase();
     TransactionStorage tr = new TransactionStorage(db);
     tr.Write(context, rid, new Resource(rid, 10, 11));
     tr.Delete(context, rid);
     Resource res = tr.Read(context, rid);
     Assert.IsNull(res);
 }
예제 #59
0
 public static uint GetRawInputData(IntPtr rawInput, RID command, IntPtr pData, ref uint pcbSize, int cbSizeHeader)
 {
     return NativeMethods.GetRawInputData(rawInput, (uint)command, pData, ref pcbSize, (uint)cbSizeHeader);
 }
예제 #60
0
 public static extern uint GetRawInputData(IntPtr hRawInput, RID uiCommand, void* pData, ref int pcbSize, int cbSizeHeader);