public void LoadTestRemoveShardFromListShardMap()
        {
            try
            {
                ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                ListShardMap <int> lsm = smm.GetListShardMap <int>(ShardMapManagerLoadTests.s_listShardMapName);
                Assert.IsNotNull(lsm);

                List <Shard> existingShards = lsm.GetShards().ToList();

                if (existingShards.Count == 0)
                {
                    return;
                }

                // If there is already a shard marked as offline, chose that one to delete.
                // This can happend if earlier remove operation was terminated for some reason - ex. killing connections.
                Shard offlineShard = existingShards.Find(e => e.Status == ShardStatus.Offline);

                if (offlineShard == null)
                {
                    offlineShard = existingShards[_r.Next(existingShards.Count)];

                    // First mark shard as offline so that other test threads will not add new mappings to it.
                    offlineShard = lsm.UpdateShard(offlineShard,
                                                   new ShardUpdate
                    {
                        Status = ShardStatus.Offline
                    });
                }

                Debug.WriteLine("Trying to remove shard at location {0}", offlineShard.Location);

                PointMappingUpdate pu = new PointMappingUpdate();
                pu.Status = MappingStatus.Offline;

                // Remove all mappings from this shard for given shard map.
                foreach (PointMapping <int> p in lsm.GetMappings(offlineShard))
                {
                    PointMapping <int> mappingToDelete = lsm.UpdateMapping(p, pu);
                    lsm.DeleteMapping(mappingToDelete);
                }

                // Shard object is changed as mappings are removed, get it again.
                Shard deleteShard = lsm.GetShard(offlineShard.Location);

                // now remove shard.
                lsm.DeleteShard(deleteShard);

                Debug.WriteLine("Removed shard at location {0} from shard map {1}", deleteShard.Location, lsm);
            }
            catch (ShardManagementException sme)
            {
                Debug.WriteLine("Exception caught: {0}", sme.Message);
            }
        }
        public void DateDeletePointMappingDefault()
        {
            CountingCacheStore countingCache = new CountingCacheStore(new CacheStore());

            ShardMapManager smm = new ShardMapManager(
                new SqlShardMapManagerCredentials(Globals.ShardMapManagerConnectionString),
                new SqlStoreConnectionFactory(),
                new StoreOperationFactory(),
                countingCache,
                ShardMapManagerLoadPolicy.Lazy,
                new RetryPolicy(1, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero),
                RetryBehavior.DefaultRetryBehavior);

            ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName);

            Assert.IsNotNull(lsm);

            ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0]);

            Shard s = lsm.CreateShard(sl);

            Assert.IsNotNull(s);

            DateTime val = DateTime.Now;
            PointMapping <DateTime> p1 = lsm.CreatePointMapping(val, s);

            PointMapping <DateTime> p2 = lsm.GetMappingForKey(val);

            Assert.IsNotNull(p2);
            Assert.AreEqual(0, countingCache.LookupMappingHitCount);

            // The mapping must be made offline first before it can be deleted.
            PointMappingUpdate ru = new PointMappingUpdate();

            ru.Status = MappingStatus.Offline;

            PointMapping <DateTime> mappingToDelete = lsm.UpdateMapping(p1, ru);

            lsm.DeleteMapping(mappingToDelete);

            // Try to get from store. Because the mapping is missing from the store, we will try to
            // invalidate the cache, but since it is also missing from cache there will be an cache miss.
            bool lookupFailed = false;

            try
            {
                PointMapping <DateTime> pLookup = lsm.GetMappingForKey(val);
            }
            catch (ShardManagementException sme)
            {
                Assert.AreEqual(ShardManagementErrorCategory.ListShardMap, sme.ErrorCategory);
                Assert.AreEqual(ShardManagementErrorCode.MappingNotFoundForKey, sme.ErrorCode);
                lookupFailed = true;
            }

            Assert.IsTrue(lookupFailed);
            Assert.AreEqual(1, countingCache.LookupMappingMissCount);
        }
Exemplo n.º 3
0
        public void GetPointMapping(ref PointMapping pm)
        {
            UInt64 size   = 0;
            IntPtr buffer = IntPtr.Zero;

            while (true)
            {
                eLeapRS result = LeapC.GetPointMapping(_leapConnection, buffer, ref size);
                if (result == eLeapRS.eLeapRS_InsufficientBuffer)
                {
                    if (buffer != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(buffer);
                    }
                    buffer = Marshal.AllocHGlobal((Int32)size);
                    continue;
                }
                reportAbnormalResults("LeapC get point mapping call was ", result);
                if (result != eLeapRS.eLeapRS_Success)
                {
                    pm.points = null;
                    pm.ids    = null;
                    return;
                }
                break;
            }
            LEAP_POINT_MAPPING pmi;

            StructMarshal <LEAP_POINT_MAPPING> .PtrToStruct(buffer, out pmi);

            Int32 nPoints = (Int32)pmi.nPoints;

            pm.frameId   = pmi.frame_id;
            pm.timestamp = pmi.timestamp;
            pm.points    = new Vector[nPoints];
            pm.ids       = new UInt32[nPoints];

            float[] points = new float[3 * nPoints];
            Int32[] ids    = new Int32[nPoints];
            Marshal.Copy(pmi.points, points, 0, 3 * nPoints);
            Marshal.Copy(pmi.ids, ids, 0, nPoints);

            int j = 0;

            for (int i = 0; i < nPoints; i++)
            {
                pm.points[i].x = points[j++];
                pm.points[i].y = points[j++];
                pm.points[i].z = points[j++];
                pm.ids[i]      = unchecked ((UInt32)ids[i]);
            }
            Marshal.FreeHGlobal(buffer);
        }
        /// <summary>
        /// Helper function to clean list and range shard maps.
        /// </summary>
        private static void CleanShardMapsHelper()
        {
            ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerLoadPolicy.Lazy);

            // Remove all existing mappings from the list shard map.
            ListShardMap <DateTime> lsm;

            if (smm.TryGetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName, out lsm))
            {
                Assert.IsNotNull(lsm);

                foreach (PointMapping <DateTime> pm in lsm.GetMappings())
                {
                    PointMapping <DateTime> pmOffline = lsm.MarkMappingOffline(pm);
                    Assert.IsNotNull(pmOffline);
                    lsm.DeleteMapping(pmOffline);
                }

                // Remove all shards from list shard map
                foreach (Shard s in lsm.GetShards())
                {
                    lsm.DeleteShard(s);
                }
            }

            // Remove all existing mappings from the range shard map.
            RangeShardMap <DateTime> rsm;

            if (smm.TryGetRangeShardMap <DateTime>(DateTimeShardMapperTests.s_rangeShardMapName, out rsm))
            {
                Assert.IsNotNull(rsm);

                foreach (RangeMapping <DateTime> rm in rsm.GetMappings())
                {
                    MappingLockToken mappingLockToken = rsm.GetMappingLockOwner(rm);
                    rsm.UnlockMapping(rm, mappingLockToken);
                    RangeMapping <DateTime> rmOffline = rsm.MarkMappingOffline(rm);
                    Assert.IsNotNull(rmOffline);
                    rsm.DeleteMapping(rmOffline);
                }

                // Remove all shards from range shard map
                foreach (Shard s in rsm.GetShards())
                {
                    rsm.DeleteShard(s);
                }
            }
        }
        public void LoadTestAddPointMapping()
        {
            try
            {
                ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                ListShardMap <int> lsm = smm.GetListShardMap <int>(ShardMapManagerLoadTests.s_listShardMapName);

                Assert.IsNotNull(lsm);
                do
                {
                    // Chose a random shard to add mapping.
                    Shard s = GetRandomOnlineShardFromShardMap((ShardMap)lsm);
                    if (s == null)
                    {
                        continue;
                    }

                    // Create a random integer key for a new mapping and verify that its not already present in this shard map.
                    int key = _r.Next(MinMappingPoint, MaxMappingPoint);
                    PointMapping <int> pExisting = null;

                    // choose different mapping if this one already exists.
                    if (lsm.TryGetMappingForKey(key, out pExisting))
                    {
                        continue;
                    }

                    Debug.WriteLine("Trying to add point mapping for key {0} to shard location {1}", key, s.Location);

                    PointMapping <int> p1 = lsm.CreatePointMapping(key, s);

                    Assert.IsNotNull(p1);

                    // Validate mapping by trying to connect
                    s_retryPolicy.ExecuteAction(
                        () => ValidateImpl(
                            (ShardMap)lsm,
                            key));
                }while (false);
            }
            catch (ShardManagementException sme)
            {
                Debug.WriteLine("Exception caught: {0}", sme.Message);
            }
        }
        public void DateAddPointMappingDuplicate()
        {
            CountingCacheStore countingCache = new CountingCacheStore(new CacheStore());

            ShardMapManager smm = new ShardMapManager(
                new SqlShardMapManagerCredentials(Globals.ShardMapManagerConnectionString),
                new SqlStoreConnectionFactory(),
                new StoreOperationFactory(),
                countingCache,
                ShardMapManagerLoadPolicy.Lazy,
                new RetryPolicy(1, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), RetryBehavior.DefaultRetryBehavior);

            ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName);

            Assert.IsNotNull(lsm);

            ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0]);

            Shard s = lsm.CreateShard(sl);

            Assert.IsNotNull(s);

            DateTime val = DateTime.Now;
            PointMapping <DateTime> p1 = lsm.CreatePointMapping(val, s);

            Assert.IsNotNull(p1);

            bool addFailed = false;

            try
            {
                // add same point mapping again.
                PointMapping <DateTime> pNew = lsm.CreatePointMapping(val, s);
            }
            catch (ShardManagementException sme)
            {
                Assert.AreEqual(ShardManagementErrorCategory.ListShardMap, sme.ErrorCategory);
                Assert.AreEqual(ShardManagementErrorCode.MappingPointAlreadyMapped, sme.ErrorCode);
                addFailed = true;
            }

            Assert.IsTrue(addFailed);

            PointMapping <DateTime> p2 = lsm.GetMappingForKey(val);

            Assert.IsNotNull(p2);
            Assert.AreEqual(0, countingCache.LookupMappingHitCount);
        }
        public void DateDeletePointMappingNonExisting()
        {
            ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerLoadPolicy.Lazy);

            ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName);

            Assert.IsNotNull(lsm);

            ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0]);

            Shard s = lsm.CreateShard(sl);

            Assert.IsNotNull(s);

            DateTime val = DateTime.Now;
            PointMapping <DateTime> p1 = lsm.CreatePointMapping(val, s);

            Assert.IsNotNull(p1);

            PointMappingUpdate ru = new PointMappingUpdate();

            ru.Status = MappingStatus.Offline;

            // The mapping must be made offline before it can be deleted.
            p1 = lsm.UpdateMapping(p1, ru);

            lsm.DeleteMapping(p1);

            bool removeFailed = false;

            try
            {
                lsm.DeleteMapping(p1);
            }
            catch (ShardManagementException sme)
            {
                Assert.AreEqual(ShardManagementErrorCategory.ListShardMap, sme.ErrorCategory);
                Assert.AreEqual(ShardManagementErrorCode.MappingDoesNotExist, sme.ErrorCode);
                removeFailed = true;
            }

            Assert.IsTrue(removeFailed);
        }
Exemplo n.º 8
0
        private PointMapping <T> MarkMappingOfflineAndUpdateShard <T>(ListShardMap <T> map, PointMapping <T> mapping, Shard newShard)
        {
            PointMapping <T> mappingOffline = map.UpdateMapping(
                mapping,
                new PointMappingUpdate
            {
                Status = MappingStatus.Offline
            });

            Assert.IsNotNull(mappingOffline);

            return(map.UpdateMapping(
                       mappingOffline,
                       new PointMappingUpdate
            {
                Shard = newShard
            }));
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            ILog log = new DefaultLog("FreedomServer");

            PointMapping <bool> boolMaping = PointMapping <bool> .GetInstance(log);

            PointMapping <byte> byteMaping = PointMapping <byte> .GetInstance(log);

            PointMapping <ushort> ushortMaping = PointMapping <ushort> .GetInstance(log);

            PointMapping <short> shortMaping = PointMapping <short> .GetInstance(log);

            PointMapping <int> intMaping = PointMapping <int> .GetInstance(log);

            PointMapping <uint> uintMaping = PointMapping <uint> .GetInstance(log);

            PointMapping <float> floatMaping = PointMapping <float> .GetInstance(log);

            for (int i = 0; i < 1000; i++)
            {
                var bpoint = new VirtulPoint <bool>(string.Concat("boolSignal", i), DataServer.ValueType.Bool, new bool[] { true });
                boolMaping.Register(bpoint.Name, bpoint);
                var bypoint = new VirtulPoint <byte>(string.Concat("byteSignal", i), DataServer.ValueType.Byte, new byte[] { 10 });
                byteMaping.Register(bypoint.Name, bypoint);
                var ushortpoint = new VirtulPoint <ushort>(string.Concat("ushortSignal", i), DataServer.ValueType.UInt16, new ushort[] { Convert.ToUInt16(i) });
                ushortMaping.Register(ushortpoint.Name, ushortpoint);
                var shortpoint = new VirtulPoint <short>(string.Concat("shortSignal", i), DataServer.ValueType.Int16, new short[] { Convert.ToInt16(i) });
                shortMaping.Register(shortpoint.Name, shortpoint);
                var intpoint = new VirtulPoint <int>(string.Concat("intSignal", i), DataServer.ValueType.Int32, new int[] { i });
                intMaping.Register(intpoint.Name, intpoint);
                var uintpoint = new VirtulPoint <uint>(string.Concat("uintSignal", i), DataServer.ValueType.UInt32, new uint[] { Convert.ToUInt32(i) });
                uintMaping.Register(uintpoint.Name, uintpoint);
            }

            EthernetSetUp setup   = new EthernetSetUp("127.0.0.1", 9527);
            TimeOut       timeout = new TimeOut("FreedomeServer", 1000, log);

            FreedomDrivers.FreedomServer fs = new FreedomDrivers.FreedomServer(setup, timeout, log);
            if (fs.Init())
            {
                fs.Start();
            }
            Console.ReadKey();
        }
        public bool DeleteShardListMap()
        {
            try
            {
                if (ShardMapManager == null)
                {
                    return(false);
                }
                Shard tempShard = null;
                PointMapping <long> tempMapping = null;

                if (ShardMapManager.TryGetListShardMap(mapManagerName, out lsm))
                {
                    foreach (Shard shard in lsm.GetShards())
                    {
                        // delete all mappings
                        var allMappings = lsm.GetMappings(shard);
                        for (int i = 0; i < allMappings.Count; i++)
                        {
                            lsm.MarkMappingOffline(allMappings[i]);
                            if (lsm.TryGetMappingForKey(allMappings[i].Value, out tempMapping))
                            {
                                lsm.DeleteMapping(tempMapping);
                            }
                        }
                        // delete shard
                        if (lsm.TryGetShard(shard.Location, out tempShard))
                        {
                            lsm.DeleteShard(tempShard);
                        }
                    }
                }
                // clear shard map manager
                if (ShardMapManager.TryGetListShardMap(mapManagerName, out lsm))
                {
                    ShardMapManager.DeleteShardMap(lsm);
                }

                return(true);
            }
            catch { return(false); }
        }
Exemplo n.º 11
0
        public void DateAddPointMappingDefault()
        {
            CountingCacheStore countingCache = new CountingCacheStore(new CacheStore());

            ShardMapManager smm = new ShardMapManager(
                new SqlShardMapManagerCredentials(Globals.ShardMapManagerConnectionString),
                new SqlStoreConnectionFactory(),
                new StoreOperationFactory(),
                countingCache,
                ShardMapManagerLoadPolicy.Lazy,
                new RetryPolicy(1, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), RetryBehavior.DefaultRetryBehavior);

            ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName);

            Assert.IsNotNull(lsm);

            ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0]);

            Shard s = lsm.CreateShard(sl);

            Assert.IsNotNull(s);

            DateTime val = DateTime.Now;
            PointMapping <DateTime> p1 = lsm.CreatePointMapping(val, s);

            Assert.IsNotNull(p1);

            PointMapping <DateTime> p2 = lsm.GetMappingForKey(val);

            Assert.IsNotNull(p2);
            Assert.AreEqual(0, countingCache.LookupMappingCount);
            Assert.AreEqual(0, countingCache.LookupMappingHitCount);

            // Validate mapping by trying to connect
            using (SqlConnection conn = lsm.OpenConnection(
                       p1,
                       Globals.ShardUserConnectionString,
                       ConnectionOptions.Validate))
            {
            }
        }
Exemplo n.º 12
0
        public void AddListMapShard <TKey>(string mapName, TKey key, string serverName, string databaseName)
        {
            var listShardMap = GetListShardMap <TKey>(mapName);

            PointMapping <TKey> mapping = null;
            var isMappingExists         = listShardMap.TryGetMappingForKey(key, out mapping);

            var location = new ShardLocation(serverName, databaseName);

            Shard shard         = null;
            var   isShardExists = listShardMap.TryGetShard(location, out shard);

            var isMappedToDifferentShard = (isMappingExists && !isShardExists) ||
                                           (isMappingExists && !mapping.Shard.Equals(shard));

            if (isMappedToDifferentShard)
            {
                var message = string.Format(
                    "Key {0} in list shard map {1} is already mapped to database {2} on server {3}!",
                    key,
                    mapName,
                    mapping.Shard.Location.Database,
                    mapping.Shard.Location.Server);
                throw new Exception(message);
            }

            if (isMappingExists)
            {
                // mapping already exists and points to the correct shard location
                return;
            }

            if (!isShardExists)
            {
                shard = listShardMap.CreateShard(location);
            }

            listShardMap.CreatePointMapping(key, shard);
        }
Exemplo n.º 13
0
        public void BasicScenarioListShardMaps()
        {
            bool   success      = true;
            string shardMapName = "PerTenantShardMap";

            try
            {
                #region DeployShardMapManager

                // Deploy shard map manager.
                ShardMapManagerFactory.CreateSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerCreateMode.ReplaceExisting);

                #endregion DeployShardMapManager

                #region GetShardMapManager

                // Obtain shard map manager.
                ShardMapManager shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                #endregion GetShardMapManager

                #region CreateListShardMap

                // Create a single user per-tenant shard map.
                ListShardMap <int> perTenantShardMap = shardMapManager.CreateListShardMap <int>(shardMapName);

                #endregion CreateListShardMap

                #region CreateShardAndPointMapping

                for (int i = 0; i < ScenarioTests.s_perTenantDBs.Length; i++)
                {
                    // Create the shard.
                    Shard s = perTenantShardMap.CreateShard(
                        new ShardLocation(
                            Globals.ShardMapManagerTestsDatasourceName,
                            ScenarioTests.s_perTenantDBs[i]));

                    // Create the mapping.
                    PointMapping <int> p = perTenantShardMap.CreatePointMapping(
                        i + 1,
                        s);
                }

                #endregion CreateShardAndPointMapping

                #region UpdatePointMapping

                // Let's add another point 5 and map it to same shard as 1.

                PointMapping <int> mappingForOne = perTenantShardMap.GetMappingForKey(1);

                PointMapping <int> mappingForFive = perTenantShardMap.CreatePointMapping(5, mappingForOne.Shard);

                Assert.IsTrue(mappingForOne.Shard.Location.Equals(mappingForFive.Shard.Location));

                // Move 3 from PerTenantDB3 to PerTenantDB for 5.
                PointMapping <int> mappingToUpdate = perTenantShardMap.GetMappingForKey(3);
                bool updateFailed = false;

                // Try updating that shard in the mapping without taking it offline first.
                try
                {
                    perTenantShardMap.UpdateMapping(
                        mappingToUpdate,
                        new PointMappingUpdate
                    {
                        Shard = mappingForFive.Shard
                    });
                }
                catch (ShardManagementException smme)
                {
                    Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingIsNotOffline);
                    updateFailed = true;
                }

                Assert.IsTrue(updateFailed);

                // Perform the actual update.
                PointMapping <int> newMappingFor3 = MarkMappingOfflineAndUpdateShard <int>(
                    perTenantShardMap, mappingToUpdate, mappingForFive.Shard);

                // Verify that update succeeded.
                Assert.IsTrue(newMappingFor3.Shard.Location.Equals(mappingForFive.Shard.Location));
                Assert.IsTrue(newMappingFor3.Status == MappingStatus.Offline);

                // Update custom field for the updated mapping.
                //PointMapping<int> veryNewMappingFor3 = perTenantShardMap.UpdatePointMapping(
                //    newMappingFor3,
                //    new PointMappingUpdate
                //    {
                //        Custom = new byte[] { 0x12, 0x34 }
                //    });

                #endregion UpdatePointMapping

                #region DeleteMapping

                // Find the shard by location.
                PointMapping <int> mappingToDelete = perTenantShardMap.GetMappingForKey(5);
                bool operationFailed = false;

                // Try to delete mapping while it is online, the delete should fail.
                try
                {
                    perTenantShardMap.DeleteMapping(mappingToDelete);
                }
                catch (ShardManagementException smme)
                {
                    operationFailed = true;
                    Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingIsNotOffline);
                }

                Trace.Assert(operationFailed);

                // The mapping must be taken offline first before it can be deleted.
                mappingToDelete = perTenantShardMap.UpdateMapping(
                    mappingToDelete,
                    new PointMappingUpdate
                {
                    Status = MappingStatus.Offline,
                });

                perTenantShardMap.DeleteMapping(mappingToDelete);

                // Verify that delete succeeded.
                try
                {
                    PointMapping <int> deletedMapping = perTenantShardMap.GetMappingForKey(5);
                }
                catch (ShardManagementException smme)
                {
                    Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingNotFoundForKey);
                }

                #endregion DeleteMapping

                #region OpenConnection without Validation

                using (SqlConnection conn = perTenantShardMap.OpenConnectionForKey(
                           2,
                           Globals.ShardUserConnectionString,
                           ConnectionOptions.None))
                {
                }

                #endregion OpenConnection without Validation

                #region OpenConnection with Validation

                // Use the stale state of "shardToUpdate" shard & see if validation works.
                bool validationFailed = false;
                try
                {
                    using (SqlConnection conn = perTenantShardMap.OpenConnection(
                               mappingToDelete,
                               Globals.ShardUserConnectionString,
                               ConnectionOptions.Validate))
                    {
                    }
                }
                catch (ShardManagementException smme)
                {
                    validationFailed = true;
                    Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingDoesNotExist);
                }

                Assert.AreEqual(validationFailed, true);

                #endregion OpenConnection with Validation

                #region OpenConnection without Validation and Empty Cache

                // Obtain a new ShardMapManager instance
                ShardMapManager newShardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                // Get the ShardMap
                ListShardMap <int> newPerTenantShardMap = newShardMapManager.GetListShardMap <int>(shardMapName);

                using (SqlConnection conn = newPerTenantShardMap.OpenConnectionForKey(
                           2,
                           Globals.ShardUserConnectionString,
                           ConnectionOptions.None))
                {
                }

                #endregion

                #region OpenConnection with Validation and Empty Cache

                // Use the stale state of "shardToUpdate" shard & see if validation works.
                validationFailed = false;

                // Obtain a new ShardMapManager instance
                newShardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                // Get the ShardMap
                newPerTenantShardMap = newShardMapManager.GetListShardMap <int>(shardMapName);

                // Create a new mapping
                PointMapping <int> newMappingToDelete = newPerTenantShardMap.CreatePointMapping(6,
                                                                                                newPerTenantShardMap.GetMappingForKey(1).Shard);

                // Delete the mapping
                newMappingToDelete = newPerTenantShardMap.UpdateMapping(
                    newMappingToDelete,
                    new PointMappingUpdate
                {
                    Status = MappingStatus.Offline,
                });

                newPerTenantShardMap.DeleteMapping(newMappingToDelete);

                try
                {
                    using (SqlConnection conn = newPerTenantShardMap.OpenConnection(
                               newMappingToDelete,
                               Globals.ShardUserConnectionString,
                               ConnectionOptions.Validate))
                    {
                    }
                }
                catch (ShardManagementException smme)
                {
                    validationFailed = true;
                    Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingDoesNotExist);
                }

                Assert.AreEqual(validationFailed, true);

                #endregion

                #region OpenConnectionAsync without Validation

                using (SqlConnection conn = perTenantShardMap.OpenConnectionForKeyAsync(
                           2,
                           Globals.ShardUserConnectionString,
                           ConnectionOptions.None).Result)
                {
                }

                #endregion

                #region OpenConnectionAsync with Validation

                // Use the stale state of "shardToUpdate" shard & see if validation works.
                validationFailed = false;
                try
                {
                    using (SqlConnection conn = perTenantShardMap.OpenConnectionAsync(
                               mappingToDelete,
                               Globals.ShardUserConnectionString,
                               ConnectionOptions.Validate).Result)
                    {
                    }
                }
                catch (AggregateException ex)
                {
                    ShardManagementException smme = ex.InnerException as ShardManagementException;
                    if (smme != null)
                    {
                        validationFailed = true;
                        Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingDoesNotExist);
                    }
                }

                Assert.AreEqual(validationFailed, true);

                #endregion

                #region OpenConnectionAsync without Validation and Empty Cache

                // Obtain a new ShardMapManager instance
                newShardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                // Get the ShardMap
                newPerTenantShardMap = newShardMapManager.GetListShardMap <int>(shardMapName);
                using (SqlConnection conn = newPerTenantShardMap.OpenConnectionForKeyAsync(
                           2,
                           Globals.ShardUserConnectionString,
                           ConnectionOptions.None).Result)
                {
                }

                #endregion

                #region OpenConnectionAsync with Validation and Empty Cache

                // Use the stale state of "shardToUpdate" shard & see if validation works.
                validationFailed = false;

                // Obtain a new ShardMapManager instance
                newShardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                    Globals.ShardMapManagerConnectionString,
                    ShardMapManagerLoadPolicy.Lazy);

                // Get the ShardMap
                newPerTenantShardMap = newShardMapManager.GetListShardMap <int>(shardMapName);

                // Create a new mapping
                newMappingToDelete = newPerTenantShardMap.CreatePointMapping(6,
                                                                             newPerTenantShardMap.GetMappingForKey(1).Shard);

                // Delete the mapping
                newMappingToDelete = newPerTenantShardMap.UpdateMapping(
                    newMappingToDelete,
                    new PointMappingUpdate
                {
                    Status = MappingStatus.Offline,
                });

                newPerTenantShardMap.DeleteMapping(newMappingToDelete);

                try
                {
                    using (SqlConnection conn = newPerTenantShardMap.OpenConnectionAsync(
                               newMappingToDelete,
                               Globals.ShardUserConnectionString,
                               ConnectionOptions.Validate).Result)
                    {
                    }
                }
                catch (AggregateException ex)
                {
                    ShardManagementException smme = ex.InnerException as ShardManagementException;
                    if (smme != null)
                    {
                        validationFailed = true;
                        Assert.AreEqual(smme.ErrorCode, ShardManagementErrorCode.MappingDoesNotExist);
                    }
                }

                Assert.AreEqual(validationFailed, true);

                #endregion

                #region LookupPointMapping

                // Perform tenant lookup. This will populate the cache.
                for (int i = 0; i < ScenarioTests.s_perTenantDBs.Length; i++)
                {
                    PointMapping <int> result = shardMapManager
                                                .GetListShardMap <int>("PerTenantShardMap")
                                                .GetMappingForKey(i + 1);

                    Trace.WriteLine(result.Shard.Location);

                    // Since we moved 3 to database 1 earlier.
                    Assert.IsTrue(result.Shard.Location.Database == ScenarioTests.s_perTenantDBs[i != 2 ? i : 0]);
                }

                // Perform tenant lookup. This will read from the cache.
                for (int i = 0; i < ScenarioTests.s_perTenantDBs.Length; i++)
                {
                    PointMapping <int> result = shardMapManager
                                                .GetListShardMap <int>("PerTenantShardMap")
                                                .GetMappingForKey(i + 1);

                    Trace.WriteLine(result.Shard.Location);

                    // Since we moved 3 to database 1 earlier.
                    Assert.IsTrue(result.Shard.Location.Database == ScenarioTests.s_perTenantDBs[i != 2 ? i : 0]);
                }

                #endregion LookupPointMapping
            }
            catch (ShardManagementException smme)
            {
                success = false;

                Trace.WriteLine(String.Format("Error Category: {0}", smme.ErrorCategory));
                Trace.WriteLine(String.Format("Error Code    : {0}", smme.ErrorCode));
                Trace.WriteLine(String.Format("Error Message : {0}", smme.Message));

                if (smme.InnerException != null)
                {
                    Trace.WriteLine(String.Format("Storage Error Message : {0}", smme.InnerException.Message));

                    if (smme.InnerException.InnerException != null)
                    {
                        Trace.WriteLine(String.Format("SqlClient Error Message : {0}", smme.InnerException.InnerException.Message));
                    }
                }
            }

            Assert.IsTrue(success);
        }
Exemplo n.º 14
0
        /// <summary>
        /// 根据类型不同,反馈不同类型数据
        /// </summary>
        /// <param name="nameGroup"></param>
        /// <returns></returns>
        private List <string> readFeedBack(PointNameGroup nameGroup)
        {
            string        pointName = nameGroup.PointName;
            byte          index     = nameGroup.Index;
            string        type      = nameGroup.Type;
            List <string> result    = new List <string>();

            if (type == DataServer.ValueType.Bool)
            {
                var pointMapping = PointMapping <bool> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.Byte)
            {
                var pointMapping = PointMapping <byte> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.UInt16)
            {
                var pointMapping = PointMapping <ushort> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.Int16)
            {
                var pointMapping = PointMapping <short> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.UInt32)
            {
                var pointMapping = PointMapping <uint> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.Int32)
            {
                var pointMapping = PointMapping <int> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.Float)
            {
                var pointMapping = PointMapping <float> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value.ToString());
                result.Add(quality.ToString());
            }
            else if (type == DataServer.ValueType.String)
            {
                var pointMapping = PointMapping <string> .GetInstance(_log);

                var  value   = pointMapping.GetValue(pointName, index);
                byte quality = pointMapping.GetPoint(pointName).GetQuality(index);
                result.Add(string.Concat(pointName, "[", index, "]"));
                result.Add(type);
                result.Add(value);
                result.Add(quality.ToString());
            }
            return(result);
        }
Exemplo n.º 15
0
        private int writeMapping(PointNameGroup nameGroup, string value)
        {
            string        pointName = nameGroup.PointName;
            byte          index     = nameGroup.Index;
            string        type      = nameGroup.Type;
            List <string> result    = new List <string>();

            if (type == DataServer.ValueType.Bool)
            {
                bool temp;
                if (bool.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <bool> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.Byte)
            {
                byte temp;
                if (byte.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <byte> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.UInt16)
            {
                ushort temp;
                if (ushort.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <ushort> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.Int16)
            {
                short temp;
                if (short.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <short> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.UInt32)
            {
                uint temp;
                if (uint.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <uint> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.Int32)
            {
                int temp;
                if (int.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <int> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            else if (type == DataServer.ValueType.Float)
            {
                float temp;
                if (float.TryParse(value, out temp))
                {
                    var pointMapping = PointMapping <float> .GetInstance(_log);

                    return(pointMapping.SetValue(pointName, temp, index));
                }
                else
                {
                    return(-1);
                }
            }
            return(-1);
        }
Exemplo n.º 16
0
        public bool Add(PointNameGroup nameGroup)
        {
            if (_pointNames.Exists((s) => (s == nameGroup)))
            {
                return(false);
            }
            var type = nameGroup.Type;

            if (!_pointNames.Exists(s => s.PointName == nameGroup.PointName))
            {
                if (type == DataServer.ValueType.Bool)
                {
                    var point = PointMapping <bool> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendBoolData;
                }
                else if (type == DataServer.ValueType.Byte)
                {
                    var point = PointMapping <byte> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendByteData;
                }
                else if (type == DataServer.ValueType.Int16)
                {
                    var point = PointMapping <short> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendShortData;
                }
                else if (type == DataServer.ValueType.UInt16)
                {
                    var point = PointMapping <ushort> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendUshortData;
                }
                else if (type == DataServer.ValueType.Int32)
                {
                    var point = PointMapping <int> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendIntData;
                }
                else if (type == DataServer.ValueType.UInt32)
                {
                    var point = PointMapping <uint> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendUintData;
                }
                else if (type == DataServer.ValueType.Float)
                {
                    var point = PointMapping <float> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendFloatData;
                }
                else if (type == DataServer.ValueType.String)
                {
                    var point = PointMapping <string> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged += sendStringData;
                }
            }
            _pointNames.Add(nameGroup);
            return(true);
        }
Exemplo n.º 17
0
        public bool Remove(PointNameGroup nameGroup)
        {
            bool result = false;

            if (_pointNames.Exists((s) => (s == nameGroup)))
            {
                var type = nameGroup.Type;
                if (type == DataServer.ValueType.Bool)
                {
                    var point = PointMapping <bool> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendBoolData;
                    result = true;
                }
                else if (type == DataServer.ValueType.Byte)
                {
                    var point = PointMapping <byte> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendByteData;
                    result = true;
                }
                else if (type == DataServer.ValueType.Int16)
                {
                    var point = PointMapping <short> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendShortData;
                    result = true;
                }
                else if (type == DataServer.ValueType.UInt16)
                {
                    var point = PointMapping <ushort> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendUshortData;
                    result = true;
                }
                else if (type == DataServer.ValueType.Int32)
                {
                    var point = PointMapping <int> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendIntData;
                    result = true;
                }
                else if (type == DataServer.ValueType.UInt32)
                {
                    var point = PointMapping <uint> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendUintData;
                    result = true;
                }
                else if (type == DataServer.ValueType.Float)
                {
                    var point = PointMapping <float> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendFloatData;
                    result = true;
                }
                else if (type == DataServer.ValueType.Float)
                {
                    var point = PointMapping <string> .GetInstance(_log).GetPoint(nameGroup.PointName);

                    point.PropertyChanged -= sendStringData;
                    result = true;
                }
            }
            return(result);
        }
        public void DateGetPointMappingsForRange()
        {
            ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerLoadPolicy.Lazy);

            ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName);

            Assert.IsNotNull(lsm);

            Shard s1 = lsm.CreateShard(new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0]));

            Assert.IsNotNull(s1);

            Shard s2 = lsm.CreateShard(new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[1]));

            Assert.IsNotNull(s2);

            DateTime val1 = DateTime.Now.Subtract(TimeSpan.FromMinutes(10));
            PointMapping <DateTime> p1 = lsm.CreatePointMapping(val1, s1);

            Assert.IsNotNull(p1);

            DateTime val2 = DateTime.Now.Subtract(TimeSpan.FromMinutes(20));
            PointMapping <DateTime> p2 = lsm.CreatePointMapping(val2, s1);

            Assert.IsNotNull(p2);

            DateTime val3 = DateTime.Now.Subtract(TimeSpan.FromMinutes(30));
            PointMapping <DateTime> p3 = lsm.CreatePointMapping(val3, s2);

            Assert.IsNotNull(p2);

            // Get all mappings in shard map.
            int count = 0;
            IEnumerable <PointMapping <DateTime> > allMappings = lsm.GetMappings();

            using (IEnumerator <PointMapping <DateTime> > mEnum = allMappings.GetEnumerator())
            {
                while (mEnum.MoveNext())
                {
                    count++;
                }
            }
            Assert.AreEqual(3, count);

            // Get all mappings in specified range.
            Range <DateTime> wantedRange = new Range <DateTime>(val3.AddMinutes(-5), val3.AddMinutes(15));

            count = 0;
            IEnumerable <PointMapping <DateTime> > mappingsInRange = lsm.GetMappings(wantedRange);

            using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsInRange.GetEnumerator())
            {
                while (mEnum.MoveNext())
                {
                    count++;
                }
            }
            Assert.AreEqual(2, count);

            // Get all mappings for a shard.
            count = 0;
            IEnumerable <PointMapping <DateTime> > mappingsForShard = lsm.GetMappings(s1);

            using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsForShard.GetEnumerator())
            {
                while (mEnum.MoveNext())
                {
                    count++;
                }
            }
            Assert.AreEqual(2, count);

            // Get all mappings in specified range for a particular shard.
            count = 0;
            IEnumerable <PointMapping <DateTime> > mappingsInRangeForShard = lsm.GetMappings(wantedRange, s1);

            using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsInRangeForShard.GetEnumerator())
            {
                while (mEnum.MoveNext())
                {
                    count++;
                }
            }
            Assert.AreEqual(1, count);
        }