Ejemplo n.º 1
0
        private void AddDeviceNumberEx(IDictionary <string, ResultOrError <StorageDeviceNumber> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <StorageDeviceNumber> result = GetResultOrError <StorageDeviceNumber>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string deviceType                 = node["DeviceType"].Attributes["result"].Value;
            string deviceGuidFlags            = node["DeviceGuidFlags"].Attributes["result"].Value;
            string deviceNumber               = node["DeviceNumber"].Attributes["result"].Value;
            string devicePartition            = node["DevicePartition"].Attributes["result"].Value;
            StorageDeviceNumber storageDevNum = new StorageDeviceNumber()
            {
                DeviceType      = (DeviceType)int.Parse(deviceType, CultureInfo.InvariantCulture),
                DeviceGuidFlags = (DeviceGuidFlags)int.Parse(deviceGuidFlags, CultureInfo.InvariantCulture),
                DeviceGuid      = new Guid(node["DeviceGuid"].Attributes["result"].Value),
                DeviceNumber    = int.Parse(deviceNumber, CultureInfo.InvariantCulture),
                PartitionNumber = int.Parse(devicePartition, CultureInfo.InvariantCulture),
            };

            dictionary.Add(path, new ResultOrError <StorageDeviceNumber>(storageDevNum));
        }
        public static IEnumerable <object[]> VerifySetupAsync_DataProvider()
        {
            // SCENARIO: An unsuccessful setup verification result.
            // EXPECT: Null to be returned, and an error to be logged.
            var unsuccessfulResponse = new ResultOrError <VerifySetupResponse>
            {
                Success      = false,
                Result       = null,
                ErrorMessage = "Hmm, something went wrong.",
            };
            var mockExtension1 = new Mock <IPlatformExtension>();

            mockExtension1
            .Setup(ext => ext.VerifySetupAsync("123", "abcdefg"))
            .ReturnsAsync(unsuccessfulResponse);
            yield return(new object[]
            {
                null,
                mockExtension1,
                new SetupRequest {
                    AccountId = "123",
                    SetupKey = "abcdefg",
                },
            });

            // SCENARIO: A successful setup verification result.
            // EXPECT: A verification response, and no errors to be logged.
            var successfulResponse = new ResultOrError <VerifySetupResponse>
            {
                Success = true,
                Result  = new VerifySetupResponse
                {
                    AccountId     = "202",
                    AccountDomain = "test.com",
                    ApiKey        = "the_api_key",
                    ApiSecret     = "the_api_secret",
                },
            };
            var mockExtension2 = new Mock <IPlatformExtension>();

            mockExtension2
            .Setup(ext => ext.VerifySetupAsync("202", "hijklmnop"))
            .ReturnsAsync(successfulResponse);
            yield return(new object[]
            {
                new VerifySetupResponse
                {
                    AccountId = "202",
                    AccountDomain = "test.com",
                    ApiKey = "the_api_key",
                    ApiSecret = "the_api_secret",
                },
                mockExtension2,
                new SetupRequest
                {
                    AccountId = "202",
                    SetupKey = "hijklmnop",
                },
            });
        }
Ejemplo n.º 3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            reader.DateTimeZoneHandling     = DateTimeZoneHandling.Utc;
            reader.DateFormatString         = Utils.DateTimeFormat;
            reader.DateParseHandling        = DateParseHandling.DateTime;
            serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            serializer.DateFormatString     = Utils.DateTimeFormat;
            serializer.DateParseHandling    = DateParseHandling.DateTime;

            var resultOrError = new ResultOrError <T>();

            if (reader.TokenType == JsonToken.StartObject)
            {
                var jsonObject = JObject.Load(reader);
                if (jsonObject["errorCode"] == null)
                {
                    T result = new T();
                    serializer.Populate(jsonObject.CreateReader(), result);
                    resultOrError.Result = result;
                }
                else
                {
                    serializer.Populate(jsonObject.CreateReader(), resultOrError);
                }
            }
            else
            {
                var jsonArray = JArray.Load(reader);
                T   result    = new T();
                serializer.Populate(jsonArray.CreateReader(), result);
                resultOrError.Result = result;
            }
            return(resultOrError);
        }
Ejemplo n.º 4
0
        protected override void TestTaskOfResult(ResultOrError <int> result)
        {
            Task[] tasks = new Task[]
            {
                result.Async().Bind(() => ResultOrError <int> .Success()),
                result.Async().Bind(() => Result <int, int> .Success(100)),
                result.Async().Bind(() => Result <int, int> .Success(101), error => Result <int, int> .Error(500)),
                result.Async().BindOnError(error => ResultOrError <int> .Error(500)),
                result.Async().BindOnError(error => Result.Error()),

                result.Async().OnSuccess(() => { }),
                result.Async().OnSuccess(() => 101),
                result.Async().OnError(error => { }),
                result.Async().OnError(error => 500),

                result.Async().Either(() => { }, error => { }),
                result.Async().Either(() => 101, error => { }),
                result.Async().Either(() => { }, error => 500),
                result.Async().Either(() => 101, error => 500),

                result.Async().Ensure(() => true, () => 500),
                result.Async().Match(() => true, error => false),
            };

            Task.WaitAll(tasks);
        }
Ejemplo n.º 5
0
        private ResultOrError <Matrix, string> CalculateMatrices(
            IReadOnlyList <Matrix> matrices,
            Func <Matrix, Matrix, ResultOrError <Matrix, string> > operation)
        {
            if (matrices.Count < 2)
            {
                return(ResultOrError <Matrix, string> .FromError("Нужно минимум две матрицы"));
            }

            Matrix result = null;

            for (var i = 1; i < matrices.Count; i++)
            {
                var rightOp       = matrices[i];
                var leftOp        = result ?? matrices[i - 1];
                var resultOrError = operation(leftOp, rightOp);
                if (resultOrError.IsError)
                {
                    return(ResultOrError <Matrix, string> .FromError($"Ошибка при обработке матрицы #{i}: {resultOrError.Error}"));
                }

                result = resultOrError.Result;
            }
            return(ResultOrError <Matrix, string> .FromResult(result));
        }
Ejemplo n.º 6
0
        public async Task <ResultOrError <PagedResult <ExpenseModel> > > GetMany(Guid userId, int pageNumber, int pageSize = 50, DateTimeOffset?fromDate = null, DateTimeOffset?toDate = null)
        {
            if (!await _context.DoesExist <User>(userId))
            {
                return(CommonErrors.UserNotExist);
            }

            var baseQuery = _context.Expenses
                            .Include(x => x.Aggregate)
                            .Include(x => x.ExpenseType)
                            .Where(x => x.Aggregate.UserId == userId);

            if (fromDate.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.Aggregate.AddedDate >= fromDate.Value);
            }

            if (toDate.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.Aggregate.AddedDate <= toDate.Value);
            }

            var totalItems = await baseQuery.CountAsync();

            var items = totalItems == 0
                ? new List <ExpenseModel>()
                : await baseQuery.OrderByDescending(x => x.Aggregate.AddedDate)
                        .Skip((pageNumber - 1) * pageSize)
                        .Take(pageSize)
                        .Select(x => x.ToModel())
                        .ToListAsync();

            return(ResultOrError <PagedResult <ExpenseModel> > .FromResult(
                       new PagedResult <ExpenseModel>(items, totalItems)));
        }
Ejemplo n.º 7
0
        private void AddVolumeInfo(IDictionary <string, ResultOrError <VolumeInfo> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <VolumeInfo> result = GetResultOrError <VolumeInfo>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string     flags   = node["Flags"].Attributes["result"].Value;
            VolumeInfo volInfo = new VolumeInfo()
            {
                VolumeLabel  = node["Label"].Attributes["result"].Value,
                VolumeSerial = node["SerialNumber"].Attributes["result"].Value,
                FileSystem   = node["FileSystem"].Attributes["result"].Value,
                Flags        = (FileSystemFlags)int.Parse(flags, CultureInfo.InvariantCulture)
            };

            dictionary.Add(path, new ResultOrError <VolumeInfo>(volInfo));
        }
Ejemplo n.º 8
0
 protected override void TestKeepMethodsOfResult(ResultOrError <int> result)
 {
     result.Keep(() => 100, out int num);
     result.KeepOnSuccess(() => 100, out int sCode);
     result.KeepOnError(error => 500, out int eCode);
     result.KeepEither(() => 100, error => 500, out int statusCode);
     result.KeepEither(() => 100, error => 500, out int successCode, out int errorCode);
 }
Ejemplo n.º 9
0
        public ResultOrError <IReadOnlyList <Matrix>, string> TransposeAllMatrices(IReadOnlyList <Matrix> matrices)
        {
            var resultMatrices = matrices
                                 .Select(_matrixCalculator.TransposeMatrix)
                                 .ToArray();

            return(ResultOrError <IReadOnlyList <Matrix>, string> .FromResult(resultMatrices));
        }
Ejemplo n.º 10
0
        public ResultOrError <Matrix, string> AddMatrices(Matrix leftOp, Matrix rightOp)
        {
            if (leftOp.Width != rightOp.Width || leftOp.Height != rightOp.Height)
            {
                return(ResultOrError <Matrix, string> .FromError("У матриц при сложении не совпали размеры"));
            }
            var newMatrix = new int[leftOp.ValuesOneDimensional.Length];

            for (var i = 0; i < leftOp.ValuesOneDimensional.Length; i++)
            {
                newMatrix[i] = leftOp.ValuesOneDimensional[i] + rightOp.ValuesOneDimensional[i];
            }
            return(ResultOrError <Matrix, string> .FromResult(new Matrix(leftOp.Height, leftOp.Width, newMatrix)));
        }
Ejemplo n.º 11
0
        private ResultOrError <Matrix, string> ParseMatrix(string s)
        {
            var    lines          = s.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToArray();
            var    firstLineWidth = 0;
            Matrix result         = null;

            for (var i = 0; i < lines.Length; i++)
            {
                var line = lines[i].Split(' ')
                           .Select(intString => int.TryParse(intString, out var x)
                                                ? ResultOrError <int, string> .FromResult(x)
                                                : ResultOrError <int, string> .FromError($"{intString} не является валидным числом"))
                           .ToArray();

                if (!line.Any())
                {
                    return(ResultOrError <Matrix, string> .FromError("В матрице не могут быть пустые строки"));
                }
                if (line.Any(n => n.IsError))
                {
                    return(ResultOrError <Matrix, string> .FromError(line.First(n => n.IsError).Error));
                }

                if (i == 0)
                {
                    firstLineWidth = line.Length;
                    result         = new Matrix(lines.Length, line.Length);
                }

                if (line.Length != firstLineWidth)
                {
                    return(ResultOrError <Matrix, string> .FromError(
                               $"Число элементов в строке #{i + 1} отличается от первой строки"));
                }

                for (var j = 0; j < firstLineWidth; j++)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    result.ValuesOneDimensional[i * firstLineWidth + j] = line[j].Result;
                }
            }

            return(ResultOrError <Matrix, string> .FromResult(result));
        }
Ejemplo n.º 12
0
        public ResultOrError <CalculationTask, string> GetTaskDetails()
        {
            using (var streamReader = _fileReadStreamProvider.GetFileContent())
            {
                var text  = streamReader.ReadToEnd();
                var parts = text.Split(new[] { Environment.NewLine + Environment.NewLine },
                                       StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length < 2)
                {
                    return(ResultOrError <CalculationTask, string> .FromError("Некорректный формат"));
                }

                var operation = ParseOperation(parts.First());
                if (operation == null)
                {
                    return(ResultOrError <CalculationTask, string> .FromError($"Неизвестная операция {parts.First()}"));
                }

                if (TwoOperandsOperations.Contains(operation.Value) && parts.Length < 3)
                {
                    return(ResultOrError <CalculationTask, string> .FromError(
                               "Для сложения/вычитания/умножения нужно как минимум две матрицы"));
                }

                var matrices = new Matrix[parts.Length - 1];
                for (var i = 1; i < parts.Length; i++)
                {
                    var matrixOrError = ParseMatrix(parts[i]);
                    if (matrixOrError.IsError)
                    {
                        return(ResultOrError <CalculationTask, string> .FromError(
                                   $"Ошибка в матрице #{i}: {matrixOrError.Error}"));
                    }

                    matrices[i - 1] = matrixOrError.Result;
                }

                return(ResultOrError <CalculationTask, string> .FromResult(new CalculationTask
                {
                    Matrices = matrices,
                    Operation = operation.Value
                }));
            }
        }
Ejemplo n.º 13
0
        private void AddItem <T>(IDictionary <string, ResultOrError <T> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            ResultOrError <T> result = GetResultOrError <T>(node);

            if (result == null)
            {
                throw new ArgumentException("Complex types not supported", nameof(dictionary));
            }

            dictionary.Add(path, result);
        }
Ejemplo n.º 14
0
        protected override void TestSingleResult(ResultOrError <int> result)
        {
            result.Bind(() => ResultOrError <int> .Success());
            result.Bind(() => Result <int, int> .Success(100));
            result.Bind(() => Result <int, int> .Success(101), error => Result <int, int> .Error(500));
            result.BindOnError(error => ResultOrError <int> .Error(500));
            result.BindOnError(error => Result.Error());

            result.OnSuccess(() => { });
            result.OnSuccess(() => 101);
            result.OnError(error => { });
            result.OnError(error => 500);

            result.Either(() => { }, error => { });
            result.Either(() => 101, error => { });
            result.Either(() => { }, error => 500);
            result.Either(() => 101, error => 500);

            result.Ensure(() => true, () => 500);
            result.Match(() => true, error => false);
        }
Ejemplo n.º 15
0
        protected override void TestLargeContent(ResultOrError <string> result)
        {
            result.Bind(() => ResultOrError <string> .Success());
            result.Bind(() => Result <string, string> .Success(LargeContent));
            result.Bind(() => Result <string, string> .Success(LargeContent), error => Result <string, string> .Error(error));
            result.BindOnError(error => ResultOrError <string> .Error(error));
            result.BindOnError(error => Result <string, string> .Error(error));

            result.OnSuccess(() => { });
            result.OnSuccess(() => LargeContent);
            result.OnError(error => { });
            result.OnError(error => error);

            result.Either(() => { }, error => { });
            result.Either(() => LargeContent, error => { });
            result.Either(() => { }, error => error);
            result.Either(() => LargeContent, error => error);

            result.Ensure(() => true, () => LargeContent);
            result.Match(() => LargeContent, error => error);
        }
Ejemplo n.º 16
0
        protected override void TestIEnumerableOfResult(ResultOrError <int>[] results)
        {
            results.Bind(() => ResultOrError <int> .Success()).Count();
            results.Bind(() => Result <int, int> .Success(100)).Count();
            results.Bind(() => Result <int, int> .Success(101), error => Result <int, int> .Error(500)).Count();
            results.BindOnError(error => ResultOrError <int> .Error(500)).Count();
            results.BindOnError(error => Result.Error()).Count();

            results.OnSuccess(() => { }).Count();
            results.OnSuccess(() => 101).Count();
            results.OnError(error => { }).Count();
            results.OnError(error => 500).Count();

            results.Either(() => { }, error => { }).Count();
            results.Either(() => 101, error => { }).Count();
            results.Either(() => { }, error => 500).Count();
            results.Either(() => 101, error => 500).Count();

            results.Ensure(() => true, () => 500).Count();
            results.Match(() => true, error => false).Count();
        }
Ejemplo n.º 17
0
        private void AddStorageDevice(IDictionary <string, ResultOrError <VolumeDeviceQuery> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <VolumeDeviceQuery> result = GetResultOrError <VolumeDeviceQuery>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string            removableMedia = node["RemovableMedia"].Attributes["result"].Value;
            string            cmdQueuing     = node["CommandQueueing"].Attributes["result"].Value;
            string            scsiDevType    = node["ScsiDeviceType"].Attributes["result"].Value;
            string            scsiDevMod     = node["ScsiModifier"].Attributes["result"].Value;
            string            busType        = node["BusType"].Attributes["result"].Value;
            VolumeDeviceQuery devQuery       = new VolumeDeviceQuery()
            {
                VendorId           = node["VendorId"].Attributes["result"].Value,
                DeviceSerialNumber = node["DeviceSerialNumber"].Attributes["result"].Value,
                ProductId          = node["ProductId"].Attributes["result"].Value,
                ProductRevision    = node["ProductRevision"].Attributes["result"].Value,
                RemovableMedia     = bool.Parse(removableMedia),
                CommandQueueing    = bool.Parse(cmdQueuing),
                ScsiDeviceType     = (ScsiDeviceType)int.Parse(scsiDevType, CultureInfo.InvariantCulture),
                ScsiDeviceModifier = int.Parse(scsiDevMod, CultureInfo.InvariantCulture),
                BusType            = (BusType)int.Parse(busType, CultureInfo.InvariantCulture)
            };

            dictionary.Add(path, new ResultOrError <VolumeDeviceQuery>(devQuery));
        }
Ejemplo n.º 18
0
        private void AddDiskExtents(IDictionary <string, ResultOrError <DiskExtent[]> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <DiskExtent[]> result = GetResultOrError <DiskExtent[]>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            // There may be zero or more disk extents.
            XmlNodeList       extentNodes = node.SelectNodes("DiskExtent");
            List <DiskExtent> extents     = new List <DiskExtent>();

            foreach (XmlElement extentNode in extentNodes)
            {
                string offset = extentNode["Offset"].Attributes["result"].Value;
                string length = extentNode["Length"].Attributes["result"].Value;
                extents.Add(new DiskExtent()
                {
                    Device         = extentNode["Device"].Attributes["result"].Value,
                    StartingOffset = long.Parse(offset, CultureInfo.InvariantCulture),
                    ExtentLength   = long.Parse(length, CultureInfo.InvariantCulture),
                });
            }

            dictionary.Add(path, new ResultOrError <DiskExtent[]>(extents.ToArray()));
        }
Ejemplo n.º 19
0
        private async Task <ResultOrError <T> > CallAsync <T>(
            string requestUri, Dictionary <string, string> dataMap)
        {
            HttpResponseMessage httpResponse = null;
            var result = new ResultOrError <T>();

            try
            {
                httpResponse = await httpClient.PostAsync(requestUri, new FormUrlEncodedContent(dataMap));

                var data = await httpResponse.Content.ReadAsStringAsync();

                JsonConvert.PopulateObject(data, result);
            }
            finally
            {
                if (httpResponse != null)
                {
                    httpResponse.Dispose();
                }
            }
            return(result);
        }
Ejemplo n.º 20
0
        public ResultOrError <Matrix, string> MultiplyMatrices(Matrix leftOp, Matrix rightOp)
        {
            if (leftOp.Width != rightOp.Height)
            {
                return(ResultOrError <Matrix, string> .FromError("У матриц при умножении не совпали размеры"));
            }

            var result = new Matrix(leftOp.Height, rightOp.Width);

            for (int i = 0; i < leftOp.Height; i++)
            {
                for (int j = 0; j < rightOp.Width; j++)
                {
                    var value = 0;
                    for (int k = 0; k < leftOp.Width; k++)
                    {
                        value += leftOp[i, k] * rightOp[k, j];
                    }

                    result[i, j] = value;
                }
            }
            return(ResultOrError <Matrix, string> .FromResult(result));
        }
Ejemplo n.º 21
0
        private void AddDiskFreeSpace(IDictionary <string, ResultOrError <DiskFreeSpace> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <DiskFreeSpace> result = GetResultOrError <DiskFreeSpace>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string        sectorsPerCluster = node["SectorsPerCluster"].Attributes["result"].Value;
            string        bytesPerSector    = node["BytesPerSector"].Attributes["result"].Value;
            string        totalBytes        = node["TotalBytes"].Attributes["result"].Value;
            string        totalBytesFree    = node["TotalBytesFree"].Attributes["result"].Value;
            string        userBytesFree     = node["UserBytesFree"].Attributes["result"].Value;
            DiskFreeSpace freeInfo          = new DiskFreeSpace()
            {
                SectorsPerCluster = int.Parse(sectorsPerCluster, CultureInfo.InvariantCulture),
                BytesPerSector    = int.Parse(bytesPerSector, CultureInfo.InvariantCulture),
                TotalBytes        = long.Parse(totalBytes, CultureInfo.InvariantCulture),
                TotalBytesFree    = long.Parse(totalBytesFree, CultureInfo.InvariantCulture),
                UserBytesFree     = long.Parse(userBytesFree, CultureInfo.InvariantCulture),
            };

            dictionary.Add(path, new ResultOrError <DiskFreeSpace>(freeInfo));
        }
Ejemplo n.º 22
0
        private void AddAlignment(IDictionary <string, ResultOrError <StorageAccessAlignment> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <StorageAccessAlignment> result = GetResultOrError <StorageAccessAlignment>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string bytesPerCacheLine             = node["BytesPerCacheLine"].Attributes["result"].Value;
            string bytesOffsetForCacheAlignment  = node["BytesOffsetForCacheAlignment"].Attributes["result"].Value;
            string bytesPerLogicalSector         = node["BytesPerLogicalSector"].Attributes["result"].Value;
            string bytesPerPhysicalSector        = node["BytesPerPhysicalSector"].Attributes["result"].Value;
            string bytesOffsetForSectorAlignment = node["BytesOffsetForSectorAlignment"].Attributes["result"].Value;
            StorageAccessAlignment diskAlignment = new StorageAccessAlignment()
            {
                BytesPerCacheLine             = int.Parse(bytesPerCacheLine, CultureInfo.InvariantCulture),
                BytesOffsetForCacheAlignment  = int.Parse(bytesOffsetForCacheAlignment, CultureInfo.InvariantCulture),
                BytesPerLogicalSector         = int.Parse(bytesPerLogicalSector, CultureInfo.InvariantCulture),
                BytesPerPhysicalSector        = int.Parse(bytesPerPhysicalSector, CultureInfo.InvariantCulture),
                BytesOffsetForSectorAlignment = int.Parse(bytesOffsetForSectorAlignment, CultureInfo.InvariantCulture),
            };

            dictionary.Add(path, new ResultOrError <StorageAccessAlignment>(diskAlignment));
        }
Ejemplo n.º 23
0
        private void AddGeometry(IDictionary <string, ResultOrError <DiskGeometry> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <DiskGeometry> result = GetResultOrError <DiskGeometry>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string       mediaType = node["MediaType"].Attributes["result"].Value;
            string       cylinders = node["Cylinders"].Attributes["result"].Value;
            string       tracks    = node["TracksPerCylinder"].Attributes["result"].Value;
            string       sectors   = node["SectorsPerTrack"].Attributes["result"].Value;
            string       bytes     = node["BytesPerSector"].Attributes["result"].Value;
            DiskGeometry diskGeo   = new DiskGeometry()
            {
                MediaType         = (MediaType)int.Parse(mediaType, CultureInfo.InvariantCulture),
                Cylinders         = int.Parse(cylinders, CultureInfo.InvariantCulture),
                TracksPerCylinder = int.Parse(tracks, CultureInfo.InvariantCulture),
                SectorsPerTrack   = int.Parse(sectors, CultureInfo.InvariantCulture),
                BytesPerSector    = int.Parse(bytes, CultureInfo.InvariantCulture),
            };

            dictionary.Add(path, new ResultOrError <DiskGeometry>(diskGeo));
        }
        public static IEnumerable <object[]> VerifySetupAsync_DataProvider()
        {
            // SCENARIO: An unsuccessful setup verification result.
            // EXPECT: Null to be returned.
            var unsuccessfulResponse = new ResultOrError <VenueVerifySetupResponse>
            {
                Success      = false,
                Result       = null,
                ErrorMessage = "Hmm, something went wrong.",
            };
            var mockExtension1 = new Mock <IPlatformExtension>();

            mockExtension1
            .Setup(ext => ext.VenueVerifySetupAsync("123", "456", "abcdefg"))
            .ReturnsAsync(unsuccessfulResponse);
            yield return(new object[]
            {
                null,
                mockExtension1,
                new VenueSetupRequest
                {
                    Region = "ap-southeast-2",
                    AccountId = "123",
                    VenueId = "456",
                    SetupKey = "abcdefg",
                },
                "https://www.ivvy.com.au/extension/venue-verify",
            });

            // SCENARIO: A successful setup verification result.
            // EXPECT: A verification response.
            var successfulResponse = new ResultOrError <VenueVerifySetupResponse>
            {
                Success = true,
                Result  = new VenueVerifySetupResponse
                {
                    AccountId     = "123",
                    AccountDomain = "test.com",
                    VenueId       = "456",
                    VenueHashId   = "venuehashid",
                },
            };
            var mockExtension2 = new Mock <IPlatformExtension>();

            mockExtension2
            .Setup(ext => ext.VenueVerifySetupAsync("123", "456", "abcdefg"))
            .ReturnsAsync(successfulResponse);
            yield return(new object[]
            {
                new VenueVerifySetupResponse
                {
                    AccountId = "123",
                    AccountDomain = "test.com",
                    VenueId = "456",
                    VenueHashId = "venuehashid",
                },
                mockExtension2,
                new VenueSetupRequest
                {
                    Region = "ap-southeast-2",
                    AccountId = "123",
                    VenueId = "456",
                    SetupKey = "abcdefg",
                },
                "https://www.ivvy.com.au/extension/venue-verify",
            });
        }
Ejemplo n.º 25
0
        private void AddPartitionInfo(IDictionary <string, ResultOrError <PartitionInformation> > dictionary, string path, XmlElement node)
        {
            if (node == null)
            {
                return;
            }
            if (dictionary.ContainsKey(path))
            {
                return;
            }

            // Because this is a complex type, The XML will always return the default value.
            ResultOrError <PartitionInformation> result = GetResultOrError <PartitionInformation>(node);

            if (result != null)
            {
                dictionary.Add(path, result);
                return;
            }

            string         style      = node["Style"].Attributes["result"].Value;
            string         number     = node["Number"].Attributes["result"].Value;
            string         offset     = node["Offset"].Attributes["result"].Value;
            string         length     = node["Length"].Attributes["result"].Value;
            PartitionStyle partStyle  = (PartitionStyle)int.Parse(style, CultureInfo.InvariantCulture);
            int            partNumber = int.Parse(number, CultureInfo.InvariantCulture);
            long           partOffset = long.Parse(offset, CultureInfo.InvariantCulture);
            long           partLength = long.Parse(length, CultureInfo.InvariantCulture);

            switch (partStyle)
            {
            case PartitionStyle.MasterBootRecord:
                dictionary.Add(path, new ResultOrError <PartitionInformation>(
                                   new MbrPartition()
                {
                    Number        = partNumber,
                    Offset        = partOffset,
                    Length        = partLength,
                    Bootable      = bool.Parse(node["MbrBootable"].Attributes["result"].Value),
                    HiddenSectors = int.Parse(node["MbrOffset"].Attributes["result"].Value),
                    Type          = int.Parse(node["MbrType"].Attributes["result"].Value)
                }));
                break;

            case PartitionStyle.GuidPartitionTable:
                dictionary.Add(path, new ResultOrError <PartitionInformation>(
                                   new GptPartition()
                {
                    Number     = partNumber,
                    Offset     = partOffset,
                    Length     = partLength,
                    Type       = new Guid(node["GptType"].Attributes["result"].Value),
                    Id         = new Guid(node["GptId"].Attributes["result"].Value),
                    Name       = node["GptName"].Attributes["result"].Value,
                    Attributes = (EFIPartitionAttributes)long.Parse(node["GptAttributes"].Attributes["result"].Value, CultureInfo.InvariantCulture)
                }));
                break;

            default:
                dictionary.Add(path, new ResultOrError <PartitionInformation>(
                                   new PartitionInformation(partStyle)
                {
                    Number = partNumber,
                    Offset = partOffset,
                    Length = partLength
                }));
                break;
            }
        }