Exemplo n.º 1
0
        public void GetGuidWorksWhenUnderlyingTypeIsRepresentedByString()
        {
            GuidType type = (GuidType)NHibernateUtil.Guid;

            Guid      value = Guid.NewGuid();
            DataTable data  = new DataTable("test");

            data.Columns.Add("guid", typeof(Guid));
            data.Columns.Add("varchar", typeof(string));
            DataRow row = data.NewRow();

            row["guid"]    = value;
            row["varchar"] = value.ToString();
            data.Rows.Add(row);
            var reader = data.CreateDataReader();

            reader.Read();

            using (var s = OpenSession())
            {
                var si = s.GetSessionImplementation();
                Assert.AreEqual(value, type.Get(reader, "guid", si));
                Assert.AreEqual(value, type.Get(reader, 0, si));
                Assert.AreEqual(value, type.Get(reader, "varchar", si));
                Assert.AreEqual(value, type.Get(reader, 1, si));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Пробует распознать тип переданного идентификатора <paramref name="guid"/>"/> и, в случае соответствия формата, помещает тип и численное значение идентификатора в <paramref name="type"/> и <paramref name="identifier"/> соответственно.
        /// Если формат не определен, то в <paramref name="type"/> и <paramref name="identifier"/> помещается <see cref="GuidType.Unknown"/> и 0 соответственно.
        /// </summary>
        /// <returns>Возвращает true, если формат идентификатора распознан и false в противном случае.</returns>
        public static bool TryParseGuid(Guid guid, out GuidType type, out int identifier)
        {
            type       = GuidType.Unknown;
            identifier = 0;

            var parts = guid.ToString("D").Split('-');

            if (parts[0] != IdentifierPrefix)
            {
                return(false);
            }

            var possibleGuidType = int.Parse(parts[1] + parts[2], System.Globalization.NumberStyles.HexNumber);

            switch (possibleGuidType)
            {
            case (int)GuidType.Module:
            case (int)GuidType.User:
                var signType = int.Parse(parts[3], System.Globalization.NumberStyles.HexNumber) != 0 ? -1 : 1;
                if (int.TryParse(parts[4], out int parsedValue))
                {
                    type       = (GuidType)possibleGuidType;
                    identifier = signType * parsedValue;
                    return(true);
                }
                return(false);

            default:
                return(false);
            }
        }
Exemplo n.º 3
0
        public ObjectGuid(uint full)
        {
            Full = full;

            if (Full >= WeenieMin && Full <= WeenieMax)
            {
                Type = GuidType.Weenie;
            }
            else if (Full >= StaticObjectMin && Full <= StaticObjectMax)
            {
                Type = GuidType.Static;
            }
            else if (Full >= GeneratorMin && Full <= GeneratorMax)
            {
                Type = GuidType.Generator;
            }
            else if (Full >= NonStaticMin && Full <= NonStaticMax)
            {
                Type = GuidType.Creature;
            }
            else if (Full >= PlayerMin && Full <= PlayerMax)
            {
                Type = GuidType.Player;
            }
            else if (Full >= ItemMin && Full <= ItemMax)
            {
                Type = GuidType.Item;
            }
            else
            {
                Type = GuidType.Undef;
            }
        }
 private static async Task <T?> Wrap <T>(Func <Task <T> > func, GuidType type, IStatusBar status)
 {
     try
     {
         return(await func());
     }
     catch (GuidServiceNotSetupException)
     {
         return(default);
Exemplo n.º 5
0
        public Transaction Load(ISqlConnectionInfo connection, Guid transactionGuid, GuidType guidType)
        {
            SqlQueryParameters parameters = new SqlQueryParameters();
            string             parameter  = guidType == GuidType.External ? "ExternalTransactionGuid" : "InternalTransactionGuid";

            parameters.Where = string.Format("[t].{0} = @{0}", parameter);
            parameters.Arguments.Add(parameter, transactionGuid);
            return(this.Load(connection, parameters));
        }
Exemplo n.º 6
0
        public Product Load(ISqlConnectionInfo connection, Guid value, GuidType type)
        {
            SqlQueryParameters parameters = new SqlQueryParameters();
            string             parameter  = type == GuidType.External ? "ExternalProductGuid" : "ProductGuid";

            parameters.Where = string.Format("[p].{0} = @{0}", parameter);
            parameters.Arguments.Add(parameter, value);
            return(this.Load(connection, parameters));
        }
Exemplo n.º 7
0
		public static Guid GenerateGuid(GuidType prefix, int bogus, int serviceLabel, uint seqId)
		{
			var bytes = new byte[16];
			BitConverter.GetBytes((int)prefix).CopyTo(bytes, 0);
			BitConverter.GetBytes(bogus).CopyTo(bytes, 4);
			BitConverter.GetBytes(serviceLabel).CopyTo(bytes, 8);
			BitConverter.GetBytes(seqId).CopyTo(bytes, 12);
			return new Guid(bytes);
		}
Exemplo n.º 8
0
        public Product Load(IConnectionInfo connection, Guid value, GuidType type)
        {
            ISqlConnectionInfo sqlConnection = connection as ISqlConnectionInfo;

            if (sqlConnection != null)
            {
                return(this.Load(sqlConnection, value, type));
            }
            using (sqlConnection = new SqlConnectionInfo(connection, this.Type))
                return(this.Load(sqlConnection, value, type));
        }
Exemplo n.º 9
0
        public Transaction Load(IConnectionInfo connection, Guid transactionGuid, GuidType guidType)
        {
            ISqlConnectionInfo sqlConnection = connection as ISqlConnectionInfo;

            if (sqlConnection != null)
            {
                return(this.Load(sqlConnection, transactionGuid, guidType));
            }
            using (sqlConnection = new SqlConnectionInfo(connection, this.Type))
                return(this.Load(sqlConnection, transactionGuid, guidType));
        }
Exemplo n.º 10
0
        public void ParseShouldReturnOptionGuidNone()
        {
            // Arrange
            var           input    = "not a Guid";
            Option <Guid> expected = None;

            // Act
            var result = GuidType.Parse(input);

            // Assert
            result.Should().Be(expected);
        }
Exemplo n.º 11
0
 private AsyncAutoCommand GenerateGuidCommand(GuidType type)
 {
     return(new AsyncAutoCommand(async() =>
     {
         var guid = await guidRangeService.GetNextGuidOrShowError(type, messageBoxService.Value);
         if (guid.HasValue)
         {
             clipboardService.Value.SetText(guid.Value.ToString());
             PublishNotification(new PlainNotification(NotificationType.Info, "Copied " + guid.Value + $" to your clipboard ({type})"));
         }
     }));
 }
Exemplo n.º 12
0
 private void RadioButton_PyKms_Click(object sender, RoutedEventArgs e)
 {
     CheckBoxAddComment.Visibility = RadioButtonKmsIds.Visibility = Visibility.Collapsed;
     RadioButtonSkuIds.IsChecked   = true;
     ExportFormat = ExportFormat.PyKms;
     GuidType     = GuidType.SkuId;
     GroupBoxGuidType.IsEnabled        = true;
     CheckBoxMultiLine.Visibility      = CheckBoxBlankLines.Visibility = Visibility.Collapsed;
     CheckBoxUseTabs.Visibility        = EncodingPanel.Visibility = Visibility.Visible;
     CheckBoxIncludeBetaSku.Visibility = CheckBoxNoDescription.Visibility = CheckBoxIncludeApp.Visibility = CheckBoxIncludeKms.Visibility = CheckBoxIncludeSku.Visibility = Visibility.Collapsed;
     Update();
 }
Exemplo n.º 13
0
        public void ParseShouldReturnOptionGuidSomeWhenInputFormat32DigitsSeparatedByHyphensEnclosedInParentheses()
        {
            // Arrange
            var           originalGuid = Guid.NewGuid();
            var           input        = originalGuid.ToString("P");
            Option <Guid> expected     = Some(originalGuid);

            // Act
            var result = GuidType.Parse(input);

            // Assert
            result.Should().Be(expected);
        }
Exemplo n.º 14
0
 private AsyncAutoCommand GenerateGuidRangeCommand(GuidType type, Func <uint> getter)
 {
     return(new AsyncAutoCommand(async() =>
     {
         var count = getter();
         var guid = await guidRangeService.GetNextGuidRangeOrShowError(type, count, messageBoxService.Value);
         if (guid.HasValue)
         {
             clipboardService.Value.SetText(guid.Value.ToString());
             PublishNotification(new PlainNotification(NotificationType.Info, "Copied " + guid.Value + $" to your clipboard ({type}). You have {count} consecutive guids"));
         }
     }, () => getter() > 0));
 }
Exemplo n.º 15
0
        public void ParseShouldReturnOptionGuidSomeWhenInputFormat4HexadecimalsEnclosedInBracesWithTheFourthSubsetOf8HexadecimalsEnclosedInBraces()
        {
            // Arrange
            var           originalGuid = Guid.NewGuid();
            var           input        = originalGuid.ToString("X");
            Option <Guid> expected     = Some(originalGuid);

            // Act
            var result = GuidType.Parse(input);

            // Assert
            result.Should().Be(expected);
        }
Exemplo n.º 16
0
        public void Equals()
        {
            GuidType type = (GuidType)NHibernateUtil.Guid;

            Guid lhs = new Guid("{01234567-abcd-abcd-abcd-0123456789ab}");
            Guid rhs = new Guid("{01234567-abcd-abcd-abcd-0123456789ab}");

            Assert.IsTrue(type.IsEqual(lhs, rhs));

            rhs = new Guid("{11234567-abcd-abcd-abcd-0123456789ab}");

            Assert.IsFalse(type.IsEqual(lhs, rhs));
        }
Exemplo n.º 17
0
        public static string GetGuidFormat(string guid, GuidType guidType)
        {
            string type = guidType.ToString();

            if (string.IsNullOrEmpty(guid))
            {
                return(Guid.NewGuid().ToString(type));
            }
            else
            {
                return(ConvertToGuid(guid).ToString(type));
            }
        }
Exemplo n.º 18
0
 public SmartGuid(ulong guid, int id, GuidType highType, ulong mapId = 0uL)
 {
     if (highType == GuidType.Creature)
     {
         this.Guid     |= guid;
         this.HighGuid |= 4398046511104uL;
         this.HighGuid |= mapId << 29;
     }
     else
     {
         this.Guid = guid;
     }
     this.HighGuid = ((ulong)highType << 58 | (ulong)((ulong)((long)id) << 6));
 }
Exemplo n.º 19
0
        /// <summary>
        /// Возвращает <see cref="Guid"/> на основе переданных идентификатора и типа идентификатора.
        /// </summary>
        /// <exception cref="ArgumentException">Возникает, если <paramref name="type"/> равен <see cref="GuidType.Unknown"/>.</exception>
        public static Guid GenerateGuid(GuidType type, int identifier)
        {
            switch (type)
            {
            case GuidType.Unknown:
                throw new ArgumentException($"В качестве типа идентификатора нельзя передавать {nameof(GuidType.Unknown)}.", nameof(type));

            case GuidType.Module:
            case GuidType.User:
                return(new Guid($"{IdentifierPrefix}-{((int)type).ToString("0000-0000")}-000{(identifier < 0 ? 1 : 0)}-{Math.Abs(identifier).ToString("000000000000")}"));

            default:
                throw new NotImplementedException();
            }
        }
Exemplo n.º 20
0
        public ObjectGuid(uint full)
        {
            Full = full;

            if (IsPlayer(full))
            {
                Type = GuidType.Player;
            }
            else if (IsStatic(full))
            {
                Type = GuidType.Static;
            }
            else if (IsDynamic(full))
            {
                Type = GuidType.Dynamic;
            }
            else
            {
                Type = GuidType.Undef;
            }
        }
Exemplo n.º 21
0
        public ObjectGuid(uint full)
        {
            Full = full;

            if (Full >= PlayerMin && Full <= PlayerMax)
            {
                Type = GuidType.Player;
            }
            else if (Full >= StaticObjectMin && Full <= StaticObjectMax)
            {
                Type = GuidType.Static;
            }
            else if (Full >= DynamicMin && Full <= DynamicMax)
            {
                Type = GuidType.Dynamic;
            }
            else
            {
                Type = GuidType.Undef;
            }
        }
Exemplo n.º 22
0
    public uint GetNextGuidRange(GuidType type, uint count)
    {
        if (!IsConfigured)
        {
            throw new GuidServiceNotSetupException();
        }
        if (count == 0)
        {
            throw new Exception("Cannot get 0 guids");
        }
        switch (type)
        {
        case GuidType.Creature:
        {
            if (data.CurrentCreature + count > data.StartCreature + data.CreatureCount)
            {
                throw new NoMoreGuidsException(type);
            }
            var counter = data.CurrentCreature;
            data.CurrentCreature += count;
            Save();
            return(counter);
        }

        case GuidType.GameObject:
        {
            if (data.CurrentGameObject + count > data.GameObjectCount + data.StartGameObject)
            {
                throw new NoMoreGuidsException(type);
            }
            var counter = data.CurrentGameObject;
            data.CurrentGameObject += count;
            Save();
            return(counter);
        }

        default:
            throw new ArgumentOutOfRangeException(nameof(type), type, null);
        }
    }
        /// <summary>
        /// Interrogates the expression instance populating the report column that is exposed to the Report API service.
        /// </summary>
        /// <param name="argument">The argument.</param>
        /// <param name="reportColumn">The report column.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        private static bool PopulateTypeFromArgument(ActivityArgument argument, out DatabaseType type, out EntityType resourceType)
        {
            resourceType = null;

            if (argument.Is <StringArgument>())
            {
                type = new StringType();
            }
            else if (argument.Is <IntegerArgument>())
            {
                type = new Int32Type();
            }
            else if (argument.Is <CurrencyArgument>())
            {
                type = new CurrencyType();
            }
            else if (argument.Is <DecimalArgument>())
            {
                type = new DecimalType();
            }
            else if (argument.Is <DateArgument>())
            {
                type = new DateType();
            }
            else if (argument.Is <TimeArgument>())
            {
                type = new TimeType();
            }
            else if (argument.Is <DateTimeArgument>())
            {
                type = new DateTimeType();
            }
            else if (argument.Is <GuidArgument>())
            {
                type = new GuidType();
            }
            else if (argument.Is <BoolArgument>())
            {
                type = new BoolType();
            }
            else if (argument.Is <TypedArgument>())
            {
                TypedArgument rla = argument.As <TypedArgument>();
                resourceType = Entity.Get <EntityType>(rla.ConformsToType);
                if (resourceType == null)
                {
                    type = null;
                    return(false);
                }
                if (resourceType.IsOfType.FirstOrDefault(t => t.Alias == "core:enumType") != null)
                {
                    // A choice field
                    type = new ChoiceRelationshipType();
                }
                else
                {
                    // Is a related resource
                    type = new InlineRelationshipType();
                }
            }
            else
            {
                type = null;
                return(false);
            }
            return(true);
        }
Exemplo n.º 24
0
		public static Guid GenerateGuid(GuidType prefix, int bogus, int serviceLabel, int seqId)
		{
			return GenerateGuid(prefix, bogus, serviceLabel, (uint)seqId);
		}
Exemplo n.º 25
0
 public ObjectGuid(uint low, GuidType high)
 {
     Full = low | ((uint)high << 24);
 }
Exemplo n.º 26
0
        /// <summary>
        /// 生成连续的GUID
        /// </summary>
        /// <param name="guidType">连续Guid类型</param>
        /// <returns></returns>
        public static Guid Create(GuidType guidType = GuidType.AsString)
        {
            // We start with 16 bytes of cryptographically strong random data.
            var randomBytes = new byte[10];

            RandomGenerator.GetBytes(randomBytes);

            // An alternate method: use a normally-created GUID to get our initial
            // random data:
            // byte[] randomBytes = Guid.NewGuid().ToByteArray();
            // This is faster than using RNGCryptoServiceProvider, but I don't
            // recommend it because the .NET Framework makes no guarantee of the
            // randomness of GUID data, and future versions (or different
            // implementations like Mono) might use a different method.

            // Now we have the random basis for our GUID.  Next, we need to
            // create the six-byte block which will be our timestamp.

            // We start with the number of milliseconds that have elapsed since
            // DateTime.MinValue.  This will form the timestamp.  There's no use
            // being more specific than milliseconds, since DateTime.Now has
            // limited resolution.

            // Using millisecond resolution for our 48-bit timestamp gives us
            // about 5900 years before the timestamp overflows and cycles.
            // Hopefully this should be sufficient for most purposes. :)
            var timestamp = DateTime.UtcNow.Ticks / 10000L;

            // Then get the bytes
            var timestampBytes = BitConverter.GetBytes(timestamp);

            // Since we're converting from an Int64, we have to reverse on
            // little-endian systems.
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(timestampBytes);
            }

            var guidBytes = new byte[16];

            switch (guidType)
            {
            case GuidType.AsString:
            case GuidType.AsBinary:

                // For string and byte-array version, we copy the timestamp first, followed
                // by the random data.
                Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
                Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);

                // If formatting as a string, we have to compensate for the fact
                // that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
                // respectively.  That means that it switches the order on little-endian
                // systems.  So again, we have to reverse.
                if (guidType == GuidType.AsString && BitConverter.IsLittleEndian)
                {
                    Array.Reverse(guidBytes, 0, 4);
                    Array.Reverse(guidBytes, 4, 2);
                }

                break;

            case GuidType.AtEnd:

                // For sequential-at-the-end versions, we copy the random data first,
                // followed by the timestamp.
                Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
                Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
                break;
            }

            return(new Guid(guidBytes));
        }
Exemplo n.º 27
0
 public WorldObject(ObjectType type, uint entry, GuidType high)
 {
     Type = type;
     Guid = new ObjectGuid(entry, high);
 }
 public static string CreateGuid(GuidType type = GuidType.D)
 => Guid.NewGuid().ToString(
     type == GuidType.B ? "B" :
     type == GuidType.D ? "D" :
     type == GuidType.N ? "N" :
     "P");
Exemplo n.º 29
0
 private void RadioButton_KmsIds_Click(object sender, RoutedEventArgs e)
 {
     GuidType = GuidType.KmsId;
     Update();
 }
Exemplo n.º 30
0
 public Transaction Load(Guid transactionGroupGuid, Guid transactionGuid, GuidType guidType)
 {
     using (SqlConnectionInfo connection = new SqlConnectionInfo(this.Type))
         return(this.Load(connection, transactionGroupGuid, transactionGuid, guidType));
 }
Exemplo n.º 31
0
 public ObjectGuid(uint low, GuidType high)
 {
     Debug.Assert(low <= 0xFFFFFFu);
     Full = low | ((uint)high << 24);
 }
Exemplo n.º 32
0
        /* Get MasterId from Guid *
         * Returns -1 on not found (wtf?) */
        protected async Task<Int64> GetMasterId(Guid pGuid, GuidType Type)
        {
            /* Store result */
            Int64 MasterId = -1;

            try
            {
                /* What table to search ? */
                switch (Type)
                {
                    case GuidType.Model:
                        {
                            /* Lookup in OrganizationView */
                            var ProdCheck = await (from Obj in Database.Models
                                                   where Obj.Guid == pGuid
                                                   select Obj.MasterId).FirstOrDefaultAsync();

                            /* Sanity */
                            if (ProdCheck != 0)
                                MasterId = ProdCheck;
                            else
                                MasterId = -1;
                        } break;

                    case GuidType.Request:
                        {
                            /* Lookup in OrganizationView */
                            var ProdCheck = await (from Obj in Database.TransactionRequests
                                                   where Obj.Guid == pGuid
                                                   select Obj.Id).FirstOrDefaultAsync();

                            /* Sanity */
                            if (ProdCheck != 0)
                                MasterId = ProdCheck;
                            else
                                MasterId = -1;
                        } break;
                }
            }
            catch (Exception) { }

            /* Done */
            return MasterId;
        }
Exemplo n.º 33
0
 public Product Load(Guid value, GuidType type)
 {
     using (SqlConnectionInfo connection = new SqlConnectionInfo(this.Type))
         return(this.Load(connection, value, type));
 }