Пример #1
0
        /// <summary>
        /// Starts the application
        /// </summary>
        /// <param name="args">The argument (source file name) to be passed in.</param>
        static async Task Main(string[] args)
        {
            var             fileIoService = new FileInteropService();
            FullNameFactory nameFactory   = new FullNameFactory();
            var             service       = new NameSortingService(fileIoService, nameFactory);

            try
            {
                // Get the file path to read from
                var filePath = args.FirstOrDefault();

                if (Debugger.IsAttached) // Override file path when executing in VS
                {
                    filePath = "./unsorted-names-list.txt";
                }

                if (filePath == null)
                {
                    throw new ArgumentNullException(nameof(filePath), "Must specify the source file path.");
                }

                Console.WriteLine($"Beginning name sorting, retrieving names from: {filePath}.{_newline}");

                // Infer destination file name as per spec, this allows for change of directory,
                // -- However can be brittle for long file paths (ie. directory that contains unsorted).
                var destinationPath = filePath.Replace("unsorted", "sorted");
                var start           = DateTimeOffset.Now;

                var sortedNames = await service.SortNames(filePath, destinationPath);

                // Display the result.
                sortedNames.ForEach(
                    name =>
                {
                    var index = sortedNames.IndexOf(name);
                    Console.WriteLine($"{index}. {name.ToText()}");
                });

                var elapsedTime = DateTimeOffset.Now.Subtract(start);
                Console.WriteLine($"{_newline}Sorting complete, results available at {destinationPath}. Took {elapsedTime.TotalSeconds} seconds.");
            }
            catch (ArgumentNullException argNullEx)
            {
                Console.WriteLine("Please make sure you've supplied all the arguments and try again.");
                Console.WriteLine(argNullEx);
            }
            catch (InvalidNameException badNameEx)
            {
                Console.WriteLine("It appears you've provided an invalid name. Lets try that again with proper input shall we?");
                Console.WriteLine($"Detail: {badNameEx.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine("An unexpected error occurred, check below for details.");
                Console.WriteLine(e);
            }
        }
 void WriteType(IType type)
 {
     if (type == null)
     {
         helper.Error("Custom attribute: Type is null");
         WriteUTF8String(UTF8String.Empty);
     }
     else
     {
         WriteUTF8String(FullNameFactory.AssemblyQualifiedName(type, helper));
     }
 }
Пример #3
0
        /// <summary>
        /// Метод создания базовых реквизитов
        /// </summary>
        /// <param name="lastName">фамилия</param>
        /// <param name="firstName">имя</param>
        /// <param name="middleName">отчество</param>
        /// <param name="series">серия</param>
        /// <param name="number">номер</param>
        /// <param name="address">адрес</param>
        /// <param name="phoneNumber">номер телефона</param>
        /// <param name="email">эмейл</param>
        /// <returns>паспортные данные, контактные данные</returns>
        private static (Passport passport, Contact contact) CreateBaseRequisites(string lastName, string firstName, string middleName,
                                                                                 string series, string number,
                                                                                 string address,
                                                                                 string phoneNumber, string email)
        {
            //Паспортные данные
            var fullName        = FullNameFactory.CreateFullName(lastName, firstName, middleName);
            var seriesAndNumber = SeriesAndNumberFactory.CreateSeriesAndNumber(series, number);
            var passport        = PassportFactory.CreatePassport(fullName, seriesAndNumber, address);

            //Контактные данные
            var phone   = PhoneNumberFactory.CreateNumber(phoneNumber);
            var contact = ContactFactory.CreateContact(phone, email);

            return(passport, contact);
        }
Пример #4
0
        public void CreateNewFullName_WithSeparatorMissingFromInput_ThrowsInvalidNameException()
        {
            // We make a wrong assumption that the string is separated by ';'
            // Arrange
            string nameString = "Holey;Dooley";

            // Act && Assert
            Assert.Throws <InvalidNameException>(() => _fullNameFactory.CreateNewFullName(nameString));

            // Or we instantiate the factory with the wrong separator -> ','
            // Arrange
            _fullNameFactory = new FullNameFactory(new [] { ',' });
            nameString       = "Holey Dooley";

            // Act && Assert
            Assert.Throws <InvalidNameException>(() => _fullNameFactory.CreateNewFullName(nameString));
        }
Пример #5
0
        public void CreateNewFullName_WithValidNameAndAlternateSeparator_CreatesNewFullNameInstance()
        {
            // Test instantiation with a different separator
            // Arrange
            string nameString   = "James,Smashing,Bond";
            var    altSeparator = new[] { ',' };

            _fullNameFactory = new FullNameFactory(altSeparator);

            // Act
            var result = _fullNameFactory.CreateNewFullName(nameString);

            // Assert
            Assert.That(result.GivenNames, Is.EqualTo(new[] { "James", "Smashing" }));
            Assert.That(result.LastName, Is.EqualTo("Bond"));
            Assert.That(result.SeparatedBy, Is.EqualTo(altSeparator));
            // Test this still represents a comma separated string.
            Assert.That(result.ToText(), Is.EqualTo("James Smashing Bond"));
            Assert.That(result.ToString(), Is.EqualTo(nameString));
        }
Пример #6
0
        static int AppendTypeNameWithArguments(StringBuilder b, ITypeDefOrRef?type, IList <TypeSig> genericArguments)
        {
            if (type is null)
            {
                return(0);
            }
            int outerTypeParameterCount = 0;

            if (type.DeclaringType is not null)
            {
                ITypeDefOrRef declType = type.DeclaringType;
                outerTypeParameterCount = AppendTypeNameWithArguments(b, declType, genericArguments);
                b.Append('.');
            }
            else
            {
                int len = b.Length;
                FullNameFactory.NamespaceSB(type, true, b);
                if (len != b.Length)
                {
                    b.Append('.');
                }
            }
            b.Append(SplitTypeParameterCountFromReflectionName(type.Name, out int localTypeParameterCount));

            if (localTypeParameterCount > 0)
            {
                int totalTypeParameterCount = outerTypeParameterCount + localTypeParameterCount;
                b.Append('{');
                for (int i = outerTypeParameterCount; i < totalTypeParameterCount && i < genericArguments.Count; i++)
                {
                    if (i > outerTypeParameterCount)
                    {
                        b.Append(',');
                    }
                    AppendTypeName(b, genericArguments[i]);
                }
                b.Append('}');
            }
            return(outerTypeParameterCount + localTypeParameterCount);
        }
Пример #7
0
        /// <summary>
        /// Метод создания базовых реквизитов
        /// </summary>
        /// <param name="lastName">фамилия</param>
        /// <param name="firstName">имя</param>
        /// <param name="middleName">отчество</param>
        /// <param name="series">серия</param>
        /// <param name="number">номер</param>
        /// <param name="address">адрес</param>
        /// <param name="phoneNumber">номер телефона</param>
        /// <param name="email">эмейл</param>
        /// <param name="cardName">наименование карты</param>
        /// <param name="accountType">тип аккаунта</param>
        /// <returns>паспортные данные, контактные данные, аккаунт</returns>
        private static (Passport passport, Contact contact, Account account) CreateBaseRequisites(string lastName, string firstName, string middleName,
                                                                                                  string series, string number,
                                                                                                  string address,
                                                                                                  string phoneNumber, string email,
                                                                                                  string cardName, AccountType accountType)
        {
            //Паспортные данные
            var fullName        = FullNameFactory.CreateFullName(lastName, firstName, middleName);
            var seriesAndNumber = SeriesAndNumberFactory.CreateSeriesAndNumber(series, number);
            var passport        = PassportFactory.CreatePassport(fullName, seriesAndNumber, address);

            //Контактные данные
            var phone   = PhoneNumberFactory.CreateNumber(phoneNumber);
            var contact = ContactFactory.CreateContact(phone, email);

            //Данные аккаунта
            var card    = SimpleCardFactory.CreateCard(cardName, default);
            var deposit = new NullDeposit();
            var account = SimpleAccountFactory.CreateAccount(accountType, card, deposit);

            return(passport, contact, account);
        }
        /// <summary>
        /// Add an instruction's operand to <paramref name="sb"/>
        /// </summary>
        /// <param name="sb">Place result here</param>
        /// <param name="instr">The instruction</param>
        /// <param name="extra">A string that will be added before the operand, if there's
        /// an operand.</param>
        public static void AddOperandString(StringBuilder sb, Instruction instr, string extra)
        {
            var op = instr.Operand;

            switch (instr.OpCode.OperandType)
            {
            case OperandType.InlineBrTarget:
            case OperandType.ShortInlineBrTarget:
                sb.Append(extra);
                AddInstructionTarget(sb, op as Instruction);
                break;

            case OperandType.InlineField:
            case OperandType.InlineMethod:
            case OperandType.InlineTok:
            case OperandType.InlineType:
                sb.Append(extra);
                if (op is IFullName)
                {
                    sb.Append((op as IFullName).FullName);
                }
                else if (op != null)
                {
                    sb.Append(op.ToString());
                }
                else
                {
                    sb.Append("null");
                }
                break;

            case OperandType.InlineI:
            case OperandType.InlineI8:
            case OperandType.InlineR:
            case OperandType.ShortInlineI:
            case OperandType.ShortInlineR:
                sb.Append($"{extra}{op}");
                break;

            case OperandType.InlineSig:
                sb.Append(extra);
                sb.Append(FullNameFactory.MethodFullName(null, (UTF8String)null, op as MethodSig, null, null, null, null));
                break;

            case OperandType.InlineString:
                sb.Append(extra);
                EscapeString(sb, op as string, true);
                break;

            case OperandType.InlineSwitch:
                var targets = op as IList <Instruction>;
                if (targets == null)
                {
                    sb.Append("null");
                }
                else
                {
                    sb.Append('(');
                    for (int i = 0; i < targets.Count; i++)
                    {
                        if (i != 0)
                        {
                            sb.Append(',');
                        }
                        AddInstructionTarget(sb, targets[i]);
                    }
                    sb.Append(')');
                }
                break;

            case OperandType.InlineVar:
            case OperandType.ShortInlineVar:
                sb.Append(extra);
                if (op == null)
                {
                    sb.Append("null");
                }
                else
                {
                    sb.Append(op.ToString());
                }
                break;

            case OperandType.InlineNone:
            case OperandType.InlinePhi:
            default:
                break;
            }
        }
Пример #9
0
 static void AppendTypeName(StringBuilder b, TypeSig type)
 {
     type = type.RemovePinnedAndModifiers();
     if (type is null)
     {
         return;
     }
     if (type is GenericInstSig giType)
     {
         AppendTypeNameWithArguments(b, giType.GenericType is null ? null : giType.GenericType.TypeDefOrRef, giType.GenericArguments);
         return;
     }
     if (type is ArraySigBase arrayType)
     {
         AppendTypeName(b, arrayType.Next);
         b.Append('[');
         var lowerBounds = arrayType.GetLowerBounds();
         var sizes       = arrayType.GetSizes();
         for (int i = 0; i < arrayType.Rank; i++)
         {
             if (i > 0)
             {
                 b.Append(',');
             }
             if (i < lowerBounds.Count && i < sizes.Count)
             {
                 b.Append(lowerBounds[i]);
                 b.Append(':');
                 b.Append(sizes[i] + lowerBounds[i] - 1);
             }
         }
         b.Append(']');
         return;
     }
     if (type is ByRefSig refType)
     {
         AppendTypeName(b, refType.Next);
         b.Append('@');
         return;
     }
     if (type is PtrSig ptrType)
     {
         AppendTypeName(b, ptrType.Next);
         b.Append('*');
         return;
     }
     if (type is GenericSig gp)
     {
         b.Append('`');
         if (gp.IsMethodVar)
         {
             b.Append('`');
         }
         b.Append(gp.Number);
     }
     else
     {
         var typeRef = type.ToTypeDefOrRef();
         if (typeRef.DeclaringType is not null)
         {
             AppendTypeName(b, typeRef.DeclaringType.ToTypeSig());
             b.Append('.');
             b.Append(typeRef.Name);
         }
         else
         {
             FullNameFactory.FullNameSB(type, false, null, null, null, b);
         }
     }
 }
 /// <summary>
 /// Constructs a new NameSortingService
 /// </summary>
 public NameSortingService(FileInteropService fileInteropService, FullNameFactory fullNameFactory)
 {
     _fileInteropService = fileInteropService;
     _fullNameFactory    = fullNameFactory;
 }
Пример #11
0
 bool IFullNameFactoryHelper.MustUseAssemblyName(IType type) => FullNameFactory.MustUseAssemblyName(module, type);
Пример #12
0
        /// <summary>
        /// Метод заполнения репозитория клиентами
        /// </summary>
        /// <param name="dbContext">контекст данных</param>
        /// <param name="quantity">кол-во клиентов</param>
        private static void FillRepository(AppDbContext dbContext, int quantity)
        {
            Parallel.For(1, quantity + 1, (i) =>
            {
                lock (locker)
                {
                    Client client = null;

                    decimal cardBalance    = random.Next(1, 10) * 10000;
                    decimal depositBalance = random.Next(1, 10) * 10000;
                    bool capitalization    = Convert.ToBoolean(random.Next(2));

                    //Паспортные данные
                    var passport = PassportFactory.CreatePassport(
                        FullNameFactory.CreateFullName(Gender.Female),
                        SeriesAndNumberFactory.CreateSeriesAndNumber(),
                        $"Адрес_{i}");

                    //Контактные данные
                    var contact = ContactFactory.CreateContact(PhoneNumberFactory.CreateNumber(), $"Client@Email_{i}.ru");

                    switch (random.Next(Enum.GetNames(typeof(ClientType)).Length))
                    {
                    case (int)ClientType.Individual:

                        //Данные аккаунта
                        var card    = IndividualsCardFactories[random.Next(IndividualsCardFactories.Length)].CreateCard(cardBalance);
                        var deposit = random.Next(2) == 0 ?
                                      new DefaultDepositFactory().CreateDeposit(depositBalance, capitalization, ClientType.Individual) :
                                      new NullDeposit();

                        var individualAccount = AccountFactories[random.Next(AccountFactories.Length)].CreateAccount(card, deposit);

                        //Создание физ. лица
                        client = IndividualFactory.CreateIndividual(passport, contact, individualAccount);
                        break;

                    case (int)ClientType.Entity:

                        //Данные аккаунта
                        card    = EntitiesCardFactories[random.Next(EntitiesCardFactories.Length)].CreateCard(cardBalance);
                        deposit = random.Next(2) == 0 ?
                                  new DefaultDepositFactory().CreateDeposit(depositBalance, capitalization, ClientType.Entity) :
                                  new NullDeposit();

                        var entityAccount = AccountFactories[random.Next(AccountFactories.Length)].CreateAccount(card, deposit);

                        //Данные компании
                        var company = CompanyFactory.CreateCompany($"Компания_{i}", $"http:\\Company.Website_{i}.ru");

                        //Создание юр.лица
                        client = EntityFactory.CreateEntity(passport, contact, entityAccount, company);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    ProcessingCountEvent?.Invoke(Count++);
                    dbContext.Add(client);
                }
            });

            dbContext.SaveChanges();
        }
Пример #13
0
 public void Setup()
 {
     _fullNameFactory = new FullNameFactory(_defaultSeparator);
 }
Пример #14
0
 public override string ToString()
 {
     return(FullNameFactory.MethodFullName("", Name, MethodSig));
 }
Пример #15
0
        byte[] Write(MarshalType marshalType)
        {
            if (marshalType is null)
            {
                return(null);
            }

            var type = marshalType.NativeType;

            if (type != NativeType.RawBlob)
            {
                if ((uint)type > byte.MaxValue)
                {
                    helper.Error("Invalid MarshalType.NativeType");
                }
                writer.WriteByte((byte)type);
            }
            bool canWrite = true;

            switch (type)
            {
            case NativeType.FixedSysString:
                var fixedSysString = (FixedSysStringMarshalType)marshalType;
                if (fixedSysString.IsSizeValid)
                {
                    WriteCompressedUInt32((uint)fixedSysString.Size);
                }
                break;

            case NativeType.SafeArray:
                var safeArray = (SafeArrayMarshalType)marshalType;
                if (UpdateCanWrite(safeArray.IsVariantTypeValid, "VariantType", ref canWrite))
                {
                    WriteCompressedUInt32((uint)safeArray.VariantType);
                }
                if (UpdateCanWrite(safeArray.IsUserDefinedSubTypeValid, "UserDefinedSubType", ref canWrite))
                {
                    Write(safeArray.UserDefinedSubType.AssemblyQualifiedName);
                }
                break;

            case NativeType.FixedArray:
                var fixedArray = (FixedArrayMarshalType)marshalType;
                if (UpdateCanWrite(fixedArray.IsSizeValid, "Size", ref canWrite))
                {
                    WriteCompressedUInt32((uint)fixedArray.Size);
                }
                if (UpdateCanWrite(fixedArray.IsElementTypeValid, "ElementType", ref canWrite))
                {
                    WriteCompressedUInt32((uint)fixedArray.ElementType);
                }
                break;

            case NativeType.Array:
                var array = (ArrayMarshalType)marshalType;
                if (UpdateCanWrite(array.IsElementTypeValid, "ElementType", ref canWrite))
                {
                    WriteCompressedUInt32((uint)array.ElementType);
                }
                if (UpdateCanWrite(array.IsParamNumberValid, "ParamNumber", ref canWrite))
                {
                    WriteCompressedUInt32((uint)array.ParamNumber);
                }
                if (UpdateCanWrite(array.IsSizeValid, "Size", ref canWrite))
                {
                    WriteCompressedUInt32((uint)array.Size);
                }
                if (UpdateCanWrite(array.IsFlagsValid, "Flags", ref canWrite))
                {
                    WriteCompressedUInt32((uint)array.Flags);
                }
                break;

            case NativeType.CustomMarshaler:
                var custMarshaler = (CustomMarshalType)marshalType;
                Write(custMarshaler.Guid);
                Write(custMarshaler.NativeTypeName);
                var cm     = custMarshaler.CustomMarshaler;
                var cmName = cm is null ? string.Empty : FullNameFactory.AssemblyQualifiedName(cm, this);
                Write(cmName);
                Write(custMarshaler.Cookie);
                break;

            case NativeType.IUnknown:
            case NativeType.IDispatch:
            case NativeType.IntF:
                var iface = (InterfaceMarshalType)marshalType;
                if (iface.IsIidParamIndexValid)
                {
                    WriteCompressedUInt32((uint)iface.IidParamIndex);
                }
                break;

            case NativeType.RawBlob:
                var data = ((RawMarshalType)marshalType).Data;
                if (data is not null)
                {
                    writer.WriteBytes(data);
                }
                break;

            default:
                break;
            }

            return(outStream.ToArray());
        }
Пример #16
0
 bool IFullNameFactoryHelper.MustUseAssemblyName(IType type) =>
 FullNameFactory.MustUseAssemblyName(module, type, optimizeCustomAttributeSerializedTypeNames);
Пример #17
0
 public static string GetMergedName(IType type, ModuleDef module)
 {
     return(FullNameFactory.FullName(type, false, null, null) + $"@{module.Name}");
 }