コード例 #1
0
        public ConsoleDispatcher(IPrivateWpfConsole wpfConsole)
        {
            UtilityMethods.ThrowIfArgumentNull(wpfConsole);

            this.WpfConsole = wpfConsole;
        }
コード例 #2
0
 //3  Takes a Tower Slot as a parameter, passes it along to the Add Tower Window field and shows it at the position of the slot
 public void ShowAddTowerWindow(GameObject towerSlot)
 {
     addTowerWindow.SetActive(true);
     addTowerWindow.GetComponent <AddTowerWindow>().towerSlotToAddTowerTo = towerSlot;
     UtilityMethods.MoveUiElementToWorldPosition(addTowerWindow.GetComponent <RectTransform>(), towerSlot.transform.position);
 }
コード例 #3
0
 private void kuacsbElevate_Click(object sender, EventArgs e)
 {
     UtilityMethods.ElevateProcessWithAdministrativeRights(@"C:\\Windows\\Notepad.exe");
 }
コード例 #4
0
ファイル: PatientService.cs プロジェクト: ProbaFirma10/Proba
 private DoctorAppointment CheckIfAppointmentsAreInPastOneMonthFromToday(DoctorAppointment appointment)
 {
     return((UtilityMethods.ParseDateInCorrectFormat(appointment.CancelDateString) > DateTime.Now.AddDays(-32)) ? appointment : null);
 }
コード例 #5
0
        /// <summary>
        /// Test helper to test a multipart upload without using the Transfer Utility
        /// </summary>
        /// <param name="algorithm">checksum algorithm</param>
        /// <param name="bucketName">bucket to upload the object to</param>
        /// <param name="disablePayloadSigning">whether the request payload should be signed</param>
        private void MultipartTestHelper(CoreChecksumAlgorithm algorithm, string bucketName, bool disablePayloadSigning)
        {
            var random            = new Random();
            var nextRandom        = random.Next();
            var filePath          = Path.Combine(Path.GetTempPath(), "multi-" + nextRandom + ".txt");
            var retrievedFilepath = Path.Combine(Path.GetTempPath(), "retreived-" + nextRandom + ".txt");
            var totalSize         = MegSize * 15;

            UtilityMethods.GenerateFile(filePath, totalSize);
            string key = "key-" + random.Next();

            Stream inputStream = File.OpenRead(filePath);

            try
            {
                InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest()
                {
                    BucketName        = bucketName,
                    Key               = key,
                    ChecksumAlgorithm = ChecksumAlgorithm.FindValue(algorithm.ToString())
                };

                InitiateMultipartUploadResponse initResponse = Client.InitiateMultipartUpload(initRequest);

                // Upload part 1
                UploadPartRequest uploadRequest = new UploadPartRequest()
                {
                    BucketName            = bucketName,
                    Key                   = key,
                    UploadId              = initResponse.UploadId,
                    PartNumber            = 1,
                    PartSize              = 5 * MegSize,
                    InputStream           = inputStream,
                    ChecksumAlgorithm     = ChecksumAlgorithm.FindValue(algorithm.ToString()),
                    DisablePayloadSigning = disablePayloadSigning
                };
                UploadPartResponse up1Response = Client.UploadPart(uploadRequest);

                // Upload part 2
                uploadRequest = new UploadPartRequest()
                {
                    BucketName            = bucketName,
                    Key                   = key,
                    UploadId              = initResponse.UploadId,
                    PartNumber            = 2,
                    PartSize              = 5 * MegSize,
                    InputStream           = inputStream,
                    ChecksumAlgorithm     = ChecksumAlgorithm.FindValue(algorithm.ToString()),
                    DisablePayloadSigning = disablePayloadSigning
                };

                UploadPartResponse up2Response = Client.UploadPart(uploadRequest);

                // Upload part 3
                uploadRequest = new UploadPartRequest()
                {
                    BucketName            = bucketName,
                    Key                   = key,
                    UploadId              = initResponse.UploadId,
                    PartNumber            = 3,
                    InputStream           = inputStream,
                    ChecksumAlgorithm     = ChecksumAlgorithm.FindValue(algorithm.ToString()),
                    DisablePayloadSigning = disablePayloadSigning,
                    IsLastPart            = true
                };

                UploadPartResponse up3Response = Client.UploadPart(uploadRequest);

                ListPartsRequest listPartRequest = new ListPartsRequest()
                {
                    BucketName = bucketName,
                    Key        = key,
                    UploadId   = initResponse.UploadId
                };

                ListPartsResponse listPartResponse = Client.ListParts(listPartRequest);
                Assert.AreEqual(3, listPartResponse.Parts.Count);
                AssertPartsAreEqual(up1Response, listPartResponse.Parts[0]);
                AssertPartsAreEqual(up2Response, listPartResponse.Parts[1]);
                AssertPartsAreEqual(up3Response, listPartResponse.Parts[2]);

                CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest()
                {
                    BucketName = bucketName,
                    Key        = key,
                    UploadId   = initResponse.UploadId
                };
                compRequest.AddPartETags(up1Response, up2Response, up3Response);

                CompleteMultipartUploadResponse compResponse = Client.CompleteMultipartUpload(compRequest);
                Assert.IsNotNull(compResponse.ETag);
                Assert.AreEqual(key, compResponse.Key);
                Assert.IsNotNull(compResponse.Location);

                // Get the file back from S3 and assert it is still the same.
                var getRequest = new GetObjectRequest
                {
                    BucketName   = bucketName,
                    Key          = key,
                    ChecksumMode = ChecksumMode.ENABLED
                };

                var getResponse = Client.GetObject(getRequest);
                getResponse.WriteResponseStreamToFile(retrievedFilepath);
                UtilityMethods.CompareFiles(filePath, retrievedFilepath);

                // We don't expect the checksum to be validated on getting an entire multipart object,
                // because it's actually the checksum-of-checksums
                Assert.AreEqual(CoreChecksumAlgorithm.NONE, getResponse.ResponseMetadata.ChecksumAlgorithm);
                Assert.AreEqual(ChecksumValidationStatus.NOT_VALIDATED, getResponse.ResponseMetadata.ChecksumValidationStatus);
            }
            finally
            {
                inputStream.Close();
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                if (File.Exists(retrievedFilepath))
                {
                    File.Delete(retrievedFilepath);
                }
            }
        }
コード例 #6
0
        public void TestSingleUploadViaTransferUtility(CoreChecksumAlgorithm algorithm)
        {
            var transferConfig = new TransferUtilityConfig {
                MinSizeBeforePartUpload = 6000000
            };
            var transfer          = new TransferUtility(Client, transferConfig);
            var content           = new string('a', 5000000);
            var key               = UtilityMethods.GenerateName(nameof(ChecksumTests));
            var filePath          = Path.Combine(Path.GetTempPath(), key + ".txt");
            var retrievedFilepath = Path.Combine(Path.GetTempPath(), "retreived-" + key + ".txt");

            try
            {
                // Create the file
                using (StreamWriter writer = File.CreateText(filePath))
                {
                    writer.Write(content);
                }

                var uploadRequest = new TransferUtilityUploadRequest
                {
                    BucketName        = _bucketName,
                    Key               = key,
                    FilePath          = filePath,
                    ChecksumAlgorithm = ChecksumAlgorithm.FindValue(algorithm.ToString())
                };

                transfer.Upload(uploadRequest);

                // Get the file back from S3 and assert it is still the same.
                var getRequest = new GetObjectRequest
                {
                    BucketName   = _bucketName,
                    Key          = uploadRequest.Key,
                    ChecksumMode = ChecksumMode.ENABLED
                };

                var getResponse = Client.GetObject(getRequest);
                var getBody     = new StreamReader(getResponse.ResponseStream).ReadToEnd();
                Assert.AreEqual(content, getBody);

                Assert.AreEqual(algorithm.ToString(), getResponse.ResponseMetadata.ChecksumAlgorithm.ToString(), true);
                Assert.AreEqual(ChecksumValidationStatus.PENDING_RESPONSE_READ, getResponse.ResponseMetadata.ChecksumValidationStatus);

                // This should validate the checksum, so "assert" that no exceptions are thrown,
                // though it doesn't expose the response metadata like above
                transfer.Download(new TransferUtilityDownloadRequest
                {
                    BucketName   = _bucketName,
                    Key          = uploadRequest.Key,
                    FilePath     = retrievedFilepath,
                    ChecksumMode = ChecksumMode.ENABLED
                });
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                if (File.Exists(retrievedFilepath))
                {
                    File.Delete(retrievedFilepath);
                }
            }
        }
コード例 #7
0
        private static void RecordPurchaseLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
        {
            var purchaseLedgerTransaction = new LedgerTransaction();
            var accountsPayableName       = purchaseTransaction.Supplier.Name + " Accounts Payable";

            if (!LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Transaction"))
            {
                return;
            }
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, "Inventory", "Debit", purchaseTransaction.Total);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, accountsPayableName, "Credit", purchaseTransaction.Total);
            context.SaveChanges();
        }
コード例 #8
0
        public static void WaitForObject(IAmazonS3 client, string bucketName, string key, int maxSeconds)
        {
            var sleeper = UtilityMethods.ListSleeper.Create();

            UtilityMethods.WaitUntilSuccess(() => { client.GetObject(bucketName, key); }, sleeper, maxSeconds);
        }
コード例 #9
0
        private static void RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(
            ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal totalCOGSChanged)
        {
            var purchaseTransactionTotalCOGSChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment (COGS)");
            context.SaveChanges();

            if (totalCOGSChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Credit", totalCOGSChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Debit", -totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Credit", -totalCOGSChanged);
            }
            context.SaveChanges();
        }
コード例 #10
0
        private static void RecordPaymentLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction, decimal paymentAmount, string paymentMode)
        {
            var accountsPayableName      = purchaseTransaction.Supplier.Name + " Accounts Payable";
            var paymentLedgerTransaction = new LedgerTransaction();

            if (!LedgerTransactionHelper.AddTransactionToDatabase(context, paymentLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Payment"))
            {
                return;
            }
            context.SaveChanges();

            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, accountsPayableName, "Debit", paymentAmount);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, paymentMode, "Credit", paymentAmount);
            context.SaveChanges();
        }
コード例 #11
0
        public IActionResult Create()
        {
            ViewBag.Options = UtilityMethods.GetCategoryEnumsAsList();

            return(View());
        }
コード例 #12
0
        public MainWindow()
        {
            InitializeComponent();
#if DEBUG
            DebuggingTools DebuggingTools = new DebuggingTools();
            Debug.WriteLine("DEBUG MODE. DEBUGGING TOOLS HAVE BEEN INSTANTIATED");
#endif

            #region Checks wether the values of the settings are valid. If they aren't, set the default value
            if (Settings.Default.Language != "it" && Settings.Default.Language != "en")
            {
                Settings.Default.Language = "en";
                Settings.Default.Save();
                Settings.Default.Reload();
                Process.Start(Application.ResourceAssembly.Location); //Restart the application
                Application.Current.Shutdown(0);
            }
            if (ThemeManager.ThemeColors.Contains(Settings.Default.ThemeColor) == false)
            {
                Settings.Default.ThemeColor = ThemeManager.ThemeColors[0];
                Settings.Default.Save();
                Settings.Default.Reload();
                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown(0);
            }
            if (ThemeManager.ThemeModes.Contains(Settings.Default.ThemeMode) == false)
            {
                Settings.Default.ThemeMode = ThemeManager.ThemeModes[0];
                Settings.Default.Save();
                Settings.Default.Reload();
                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown(0);
            }
            if (Settings.Default.TempFolderPath == "" || Directory.Exists(Settings.Default.TempFolderPath) == false)
            {
                Directory.CreateDirectory($"{Path.GetTempPath()}ImageConverter");
                Settings.Default.TempFolderPath = $"{Path.GetTempPath()}ImageConverter";
                Settings.Default.Save();
                Settings.Default.Reload();
            }
            #endregion

            #region Apply theme type and themecolor
            MainWindowGrid.Background    = ThemeManager.SolidColorBrushOfThemeMode();
            TitleTextBox.Foreground      = ThemeManager.SolidColorBrushOfThemeColor();
            ThemeManager.solidColorBrush = new SolidColorBrush()
            {
                Color = ThemeManager.RunningOrStaticConversionTextBlockColor,
            };
            ConversionResultTextBlock.Foreground = ThemeManager.solidColorBrush;

            //Applies the selected theme color to every label's background in every ComboBox
            foreach (var control in OptionsStackPanel.Children)
            {
                foreach (var label in UtilityMethods.FindLabelsInComboBoxesInSPs(ref OptionsStackPanel))
                {
                    label.Background = ThemeManager.SolidColorBrushOfThemeColor();
                }
            }

            //If the selected ThemeMode is DarkTheme the ThemeColor will be applied to the text of all the labels in the options stackpanel
            if (Settings.Default.ThemeMode == "DarkTheme")
            {
                ThemeManager.ApplyThemeColorToLabelsInSP(ref OptionsStackPanel);
                ImagesNamesTextBlock.Foreground      = ThemeManager.SolidColorBrushOfThemeColor();
                ConversionResultTextBlock.Foreground = ThemeManager.SolidColorBrushOfThemeColor();
                IconSizesTextBlock.Foreground        = ThemeManager.SolidColorBrushOfThemeColor();
                foreach (CheckBox checkBox in IconSizesMatrixGrid.Children)
                {
                    checkBox.Foreground = ThemeManager.SolidColorBrushOfThemeColor();
                }
            }
            #endregion
            #region Hide some controls that should not viewable at the initial state of the app
            InsertNewImagesModeBttn.Source       = new BitmapImage(new System.Uri("pack://application:,,,/Resources/ReplaceImages.png"));
            ConversionResultTextBlock.Visibility = Visibility.Collapsed;
            WarningTextBlock.Text            = string.Empty;
            GifOptionsSP.Visibility          = Visibility.Collapsed;
            ReplaceTransparencySP.Visibility = Visibility.Collapsed;
            QualityOptionSP.Visibility       = Visibility.Collapsed;
            TiffOptionsSP.Visibility         = Visibility.Collapsed;
            IcoOptionsSP.Visibility          = Visibility.Collapsed;
            SavePathOptionSP.Visibility      = Visibility.Collapsed;
            #endregion
            #region Apply translation to all the visible controls
            if (Settings.Default.Language == "it")
            {
                ImgViewer.Source = new BitmapImage(new System.Uri("pack://application:,,,/Resources/ImageConverterDragAndDropIT.png"));
                StartConversionBttn.ButtonText      = LanguageManager.IT_StartConversionBttnText;
                ChooseFormatLabel.Content           = LanguageManager.IT_ChooseFormatLabelText;
                ConversionResultTextBlock.Text      = LanguageManager.IT_ConversionResultTextBlockRunning;
                GifRepeatTimes.Content              = LanguageManager.IT_GifRepeatTimesLabelText;
                EmptyImgViewerCntxtMenuBttn.Header  = LanguageManager.IT_ImageViewerContextMenuText;
                GifFramesDelayTimeLabel.Content     = LanguageManager.IT_GifFramesDelayTimeLabelText;
                InsertNewImagesModeBttn.ToolTip     = LanguageManager.IT_ReplaceExistingImagesToolTip;
                ReplacePngTransparencyLabel.Content = LanguageManager.IT_ReplacePngTransparencyLabelText;
                QualityLabel.Content         = LanguageManager.IT_QualityLabelText;
                CompressionAlgoLabel.Content = LanguageManager.IT_CompressionAlgoLabelText;
                ImageSavePathLabel.Content   = LanguageManager.IT_ImageSavePathLabelText;
                ChooseFolderBttn.Content     = LanguageManager.IT_ChooseFolderBttnText;
                IconSizesTextBlock.Text      = LanguageManager.IT_IconSizesTextBlockText;
                //Each item in the combobox that contains a series of colors to replace a png transparency with
                foreach (Label item in ReplTranspColCB.Items)
                {
                    switch (item.Content)
                    {
                    case "Nothing":
                        item.Content = LanguageManager.IT_Nothing;
                        break;

                    case "White":
                        item.Content = LanguageManager.IT_White;
                        break;

                    case "Black":
                        item.Content = LanguageManager.IT_Black;
                        break;

                    default:
                        return;
                    }
                }
            }
            else if (Settings.Default.Language == "en")
            {
                ImgViewer.Source = new BitmapImage(new System.Uri("pack://application:,,,/Resources/ImageConverterDragAndDropEN.png"));
                StartConversionBttn.ButtonText      = LanguageManager.EN_StartConversionBttnText;
                ChooseFormatLabel.Content           = LanguageManager.EN_ChooseFormatLabelText;
                ConversionResultTextBlock.Text      = LanguageManager.EN_ConversionResultTextBlockRunning;
                GifRepeatTimes.Content              = LanguageManager.EN_GifRepeatTimesLabelText;
                EmptyImgViewerCntxtMenuBttn.Header  = LanguageManager.EN_ImageViewerContextMenuText;
                GifFramesDelayTimeLabel.Content     = LanguageManager.EN_GifRepeatTimesLabelText;
                InsertNewImagesModeBttn.ToolTip     = LanguageManager.EN_ReplaceExistingImagesToolTip;
                ReplacePngTransparencyLabel.Content = LanguageManager.EN_ReplacePngTransparencyLabelText;
                QualityLabel.Content         = LanguageManager.EN_QualityLabelText;
                CompressionAlgoLabel.Content = LanguageManager.EN_CompressionAlgoLabelText;
                ImageSavePathLabel.Content   = LanguageManager.EN_ImageSavePathLabelText;
                ChooseFolderBttn.Content     = LanguageManager.EN_ChooseFolderBttnText;
                IconSizesTextBlock.Text      = LanguageManager.EN_IconSizesTextBlockText;
                //Each item in the combobox that contains a series of colors to replace a png transparency with
                foreach (Label item in ReplTranspColCB.Items)
                {
                    switch (item.Content)
                    {
                    case "Nothing":
                        item.Content = LanguageManager.EN_Nothing;
                        break;

                    case "White":
                        item.Content = LanguageManager.EN_White;
                        break;

                    case "Black":
                        item.Content = LanguageManager.EN_Black;
                        break;

                    default:
                        return;
                    }
                }
            }
            #endregion
        }
コード例 #13
0
        /// <summary>
        /// Checks wether the files the user wants to drop are images/contain valid images
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgViewer_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(DataFormats.FileDrop) != null)
            {
                //Get files the user is trying to convert
                string[] droppingFiles = e.Data.GetData(DataFormats.FileDrop) as string[];
                //If the droopping files aren't images
                if (UtilityMethods.IsOrContainsImage(droppingFiles) == false)
                {
                    if (Settings.Default.Language == "it")
                    {
                        WarningTextBlock.Text = LanguageManager.IT_WarningUnsupportedFile;
                    }
                    else if (Settings.Default.Language == "en")
                    {
                        WarningTextBlock.Text = LanguageManager.EN_WarningUnsupportedFile;
                    }
                }

                //If the user wants to ADD (not replace) some new images to the already present ones, check if the any of the dropping-files
                //are already present in the list of images to convert
                if (local_pathsOfImagesToConvert.Count != 0 && (string)InsertNewImagesModeBttn.Tag == "Add")
                {
                    foreach (var file in droppingFiles)
                    {
                        //if the file is a folder check the files inside it
                        if (File.GetAttributes(file) == FileAttributes.Directory)
                        {
                            foreach (var fileInFolder in Directory.GetFiles(file))
                            {
                                if (local_pathsOfImagesToConvert.Contains(fileInFolder))
                                {
                                    if (Settings.Default.Language == "it")
                                    {
                                        WarningTextBlock.Text = LanguageManager.IT_SomeImagesAreAlreadyPresent;
                                    }
                                    else if (Settings.Default.Language == "en")
                                    {
                                        WarningTextBlock.Text = LanguageManager.EN_SomeImagesAreAlreadyPresent;
                                    }
                                    break;
                                }
                            }
                        }
                        //Else check the files
                        else if (local_pathsOfImagesToConvert.Contains(file))
                        {
                            if (Settings.Default.Language == "it")
                            {
                                WarningTextBlock.Text = LanguageManager.IT_SomeImagesAreAlreadyPresent;
                            }
                            else if (Settings.Default.Language == "en")
                            {
                                WarningTextBlock.Text = LanguageManager.EN_SomeImagesAreAlreadyPresent;
                            }
                            break;
                        }
                    }
                }
            }
        }
コード例 #14
0
 public void ShowTowerInfoWindow(Tower tower)
 {
     towerInfoWindow.GetComponent <TowerInfoWindow>().tower = tower; towerInfoWindow.SetActive(true);
     UtilityMethods.MoveUiElementToWorldPosition(towerInfoWindow.GetComponent <RectTransform>(), tower.transform.position);
 }
コード例 #15
0
        public void TestDBParameterOperations()
        {
            const string     engine             = "mysql5.1";
            var              parameterGroupName = "dotnet-test-param-group-" + DateTime.Now.Ticks;
            DBParameterGroup parameterGroup     = null;
            DBParameterGroup parameterGroup2    = null;

            try
            {
                // Create a parameter group
                parameterGroup = Client.CreateDBParameterGroupAsync(
                    new CreateDBParameterGroupRequest
                {
                    DBParameterGroupName   = parameterGroupName,
                    Description            = "description",
                    DBParameterGroupFamily = engine
                }).Result.DBParameterGroup;
                Assert.AreEqual(parameterGroupName, parameterGroup.DBParameterGroupName);
                Assert.AreEqual("description", parameterGroup.Description);
                Assert.IsTrue(parameterGroup.DBParameterGroupFamily.StartsWith("mysql"));

                // Describe it
                var dbParameterGroups = Client.DescribeDBParameterGroupsAsync(
                    new DescribeDBParameterGroupsRequest
                {
                    DBParameterGroupName = parameterGroupName,
                    MaxRecords           = 20
                }).Result.DBParameterGroups;

                Assert.AreEqual(1, dbParameterGroups.Count);
                Assert.AreEqual(parameterGroupName, dbParameterGroups[0].DBParameterGroupName);
                Assert.AreEqual("description", dbParameterGroups[0].Description);
                Assert.IsTrue(dbParameterGroups[0].DBParameterGroupFamily.StartsWith("mysql"));


                // Describe the params in a group
                var parameters = Client.DescribeDBParametersAsync(
                    new DescribeDBParametersRequest
                {
                    DBParameterGroupName = parameterGroupName,
                    MaxRecords           = 20
                }).Result.Parameters;
                // We can't request a specific parameter, so we rely on the fact that most
                // parameters will have the following fields populated.
                assertValidParameter(parameters[0]);


                // Describe the defaults for an engine
                var engineDefaultParameters = Client.DescribeEngineDefaultParametersAsync(
                    new DescribeEngineDefaultParametersRequest
                {
                    DBParameterGroupFamily = engine,
                    MaxRecords             = 20
                }).Result.EngineDefaults;
                Assert.AreEqual(engine, engineDefaultParameters.DBParameterGroupFamily);
                Assert.IsFalse(engineDefaultParameters.Parameters.Count == 0);
                assertValidParameter(engineDefaultParameters.Parameters[0]);


                // Reset the parameter group
                var resetParameterGroupName = Client.ResetDBParameterGroupAsync(
                    new ResetDBParameterGroupRequest
                {
                    DBParameterGroupName = parameterGroupName,
                    ResetAllParameters   = true
                }).Result.DBParameterGroupName;
                Assert.AreEqual(parameterGroupName, resetParameterGroupName);


                // Modify the parameter group
                var newParameter = new Parameter
                {
                    ParameterName  = "character_set_client",
                    ParameterValue = "ascii",
                    ApplyMethod    = "immediate"
                };

                var modifyDbParameterGroupRequest = new ModifyDBParameterGroupRequest
                {
                    DBParameterGroupName = parameterGroupName,
                };
                modifyDbParameterGroupRequest.Parameters.Add(newParameter);
                var modifiedParameterGroupName = Client.ModifyDBParameterGroupAsync(modifyDbParameterGroupRequest)
                                                 .Result.DBParameterGroupName;
                Assert.AreEqual(parameterGroupName, modifiedParameterGroupName);

                // Copy the parameter group
                parameterGroup2 = Client.CopyDBParameterGroupAsync(new CopyDBParameterGroupRequest
                {
                    SourceDBParameterGroupIdentifier  = parameterGroupName,
                    TargetDBParameterGroupIdentifier  = parameterGroupName + "copy",
                    TargetDBParameterGroupDescription = "Copy of " + parameterGroupName
                }).Result.DBParameterGroup;
                Assert.AreEqual(parameterGroupName + "copy", parameterGroup2.DBParameterGroupName);
                Assert.AreEqual("Copy of " + parameterGroupName, parameterGroup2.Description);
                Assert.IsTrue(parameterGroup2.DBParameterGroupFamily.StartsWith("mysql"));
            }
            finally
            {
                if (parameterGroup != null)
                {
                    UtilityMethods.WaitUntilSuccess(() => Client.DeleteDBParameterGroupAsync(new DeleteDBParameterGroupRequest
                    {
                        DBParameterGroupName = parameterGroup.DBParameterGroupName
                    }).Wait());
                }
                if (parameterGroup2 != null)
                {
                    UtilityMethods.WaitUntilSuccess(() => Client.DeleteDBParameterGroupAsync(new DeleteDBParameterGroupRequest
                    {
                        DBParameterGroupName = parameterGroup2.DBParameterGroupName
                    }).Wait());
                }
            }
        }
コード例 #16
0
        private async Task TestHashObjects()
        {
            string bucketName = "aws-sdk-net-s3link-" + DateTime.Now.Ticks;
            var    s3Client   = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast1);
            await s3Client.PutBucketAsync(bucketName);

            try
            {
                // Create and save item
                Product product = new Product
                {
                    Id          = 1,
                    Name        = "CloudSpotter",
                    CompanyName = "CloudsAreGrate",
                    Price       = 1200,
                    TagSet      = new HashSet <string> {
                        "Prod", "1.0"
                    },
                    CurrentStatus   = Status.Active,
                    FormerStatus    = Status.Upcoming,
                    Supports        = Support.Windows | Support.Abacus,
                    PreviousSupport = null,
                    InternalId      = "T1000",
                    IsPublic        = true,
                    AlwaysN         = true,
                    Rating          = 4,
                    Components      = new List <string> {
                        "Code", "Coffee"
                    },
                    KeySizes = new List <byte> {
                        16, 64, 128
                    },
                    CompanyInfo = new CompanyInfo
                    {
                        Name        = "MyCloud",
                        Founded     = new DateTime(1994, 7, 6),
                        Revenue     = 9001,
                        AllProducts = new List <Product>
                        {
                            new Product {
                                Id = 12, Name = "CloudDebugger"
                            },
                            new Product {
                                Id = 13, Name = "CloudDebuggerTester"
                            }
                        },
                        CompetitorProducts = new Dictionary <string, List <Product> >
                        {
                            {
                                "CloudsAreOK",
                                new List <Product>
                                {
                                    new Product {
                                        Id = 90, Name = "CloudSpotter RipOff"
                                    },
                                    new Product {
                                        Id = 100, Name = "CloudDebugger RipOff"
                                    },
                                }
                            },
                            {
                                "CloudsAreBetter",
                                new List <Product>
                                {
                                    new Product {
                                        Id = 92, Name = "CloudSpotter RipOff 2"
                                    },
                                    new Product {
                                        Id = 102, Name = "CloudDebugger RipOff 3"
                                    },
                                }
                            },
                        }
                    },
                    Map = new Dictionary <string, string>
                    {
                        { "a", "1" },
                        { "b", "2" }
                    }
                };

                product.FullProductDescription = S3Link.Create(SharedTestFixture.Context, bucketName, "my-product", Amazon.RegionEndpoint.USEast1);

                // await product.FullProductDescription.UploadStreamAsync(new MemoryStream(UTF8Encoding.UTF8.GetBytes("Lots of data")));
                await SharedTestFixture.Context.SaveAsync(product);

                // Test conversion
                var doc = SharedTestFixture.Context.ToDocument(product);
                Assert.NotNull(doc["Tags"].AsPrimitiveList());
                //if (DynamoDBEntryConversion.Schema == DynamoDBEntryConversion.ConversionSchema.V1)
                //    Assert.NotNull(doc["Components"].AsPrimitiveList());
                //else
                //    Assert.NotNull(doc["Components"].AsDynamoDBList());
                Assert.True(
                    doc["Components"].AsPrimitiveList() != null ||
                    doc["Components"].AsDynamoDBList() != null);
                Assert.NotNull(doc["CompanyInfo"].AsDocument());
                Assert.NotNull(doc["Supports"]);

                // Load item
                Product retrieved = await SharedTestFixture.Context.LoadAsync <Product>(1);

                Assert.Equal(product.Id, retrieved.Id);
                Assert.Equal(product.TagSet.Count, retrieved.TagSet.Count);
                Assert.Equal(product.Components.Count, retrieved.Components.Count);
                Assert.Null(retrieved.InternalId);
                Assert.Equal(product.CurrentStatus, retrieved.CurrentStatus);
                Assert.Equal(product.FormerStatus, retrieved.FormerStatus);
                Assert.Equal(product.Supports, retrieved.Supports);
                Assert.Equal(product.PreviousSupport, retrieved.PreviousSupport);
                Assert.Equal(product.IsPublic, retrieved.IsPublic);
                Assert.Equal(product.Rating, retrieved.Rating);
                Assert.Equal(product.KeySizes.Count, retrieved.KeySizes.Count);
                Assert.NotNull(retrieved.CompanyInfo);
                Assert.Equal(product.CompanyInfo.Name, retrieved.CompanyInfo.Name);
                Assert.Equal(product.CompanyInfo.Founded, retrieved.CompanyInfo.Founded);
                Assert.NotEqual(product.CompanyInfo.Revenue, retrieved.CompanyInfo.Revenue);
                Assert.Equal(product.CompanyInfo.AllProducts.Count, retrieved.CompanyInfo.AllProducts.Count);
                Assert.Equal(product.CompanyInfo.AllProducts[0].Id, retrieved.CompanyInfo.AllProducts[0].Id);
                Assert.Equal(product.CompanyInfo.AllProducts[1].Id, retrieved.CompanyInfo.AllProducts[1].Id);
                Assert.Equal(product.Map.Count, retrieved.Map.Count);
                Assert.Equal(product.CompanyInfo.CompetitorProducts.Count, retrieved.CompanyInfo.CompetitorProducts.Count);
                Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(0).Key, retrieved.CompanyInfo.CompetitorProducts.ElementAt(0).Key);
                Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(0).Value.Count, retrieved.CompanyInfo.CompetitorProducts.ElementAt(0).Value.Count);
                Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(1).Key, retrieved.CompanyInfo.CompetitorProducts.ElementAt(1).Key);
                Assert.Equal(product.CompanyInfo.CompetitorProducts.ElementAt(1).Value.Count, retrieved.CompanyInfo.CompetitorProducts.ElementAt(1).Value.Count);

                Assert.NotNull(retrieved.FullProductDescription);

                /*using(var stream = retrieved.FullProductDescription.OpenStream())
                 * using(var reader = new StreamReader(stream))
                 * {
                 *  Assert.Equal("Lots of data", reader.ReadToEnd());
                 * }*/


                // Try saving circularly-referencing object
                product.CompanyInfo.AllProducts.Add(product);
                await Assert.ThrowsAsync <InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(product));

                product.CompanyInfo.AllProducts.RemoveAt(2);

                // Create and save new item
                product.Id++;
                product.Price         = 94;
                product.TagSet        = null;
                product.Components    = null;
                product.CurrentStatus = Status.Upcoming;
                product.IsPublic      = false;
                product.AlwaysN       = false;
                product.Rating        = null;
                product.KeySizes      = null;
                await SharedTestFixture.Context.SaveAsync(product);

                // Load new item
                retrieved = await SharedTestFixture.Context.LoadAsync <Product>(product);

                Assert.Equal(product.Id, retrieved.Id);
                Assert.Null(retrieved.TagSet);
                Assert.Null(retrieved.Components);
                Assert.Null(retrieved.InternalId);
                Assert.Equal(product.CurrentStatus, retrieved.CurrentStatus);
                Assert.Equal(product.IsPublic, retrieved.IsPublic);
                Assert.Equal(product.AlwaysN, retrieved.AlwaysN);
                Assert.Equal(product.Rating, retrieved.Rating);
                Assert.Null(retrieved.KeySizes);

                // Enumerate all products and save their Ids
                List <int>            productIds = new List <int>();
                IEnumerable <Product> products   = await SharedTestFixture.Context.ScanAsync <Product>(new List <ScanCondition>()).GetNextSetAsync();

                foreach (var p in products)
                {
                    productIds.Add(p.Id);
                }
                Assert.Equal(2, productIds.Count);

                // Load first product
                var firstId = productIds[0];
                product = await SharedTestFixture.Context.LoadAsync <Product>(firstId);

                Assert.NotNull(product);
                Assert.Equal(firstId, product.Id);

                // Query GlobalIndex
                products = await SharedTestFixture.Context.QueryAsync <Product>(
                    product.CompanyName,            // Hash-key for the index is Company
                    QueryOperator.GreaterThan,      // Range-key for the index is Price, so the
                    new object[] { 90 },            // condition is against a numerical value
                    new DynamoDBOperationConfig     // Configure the index to use
                {
                    IndexName = "GlobalIndex",
                }).GetNextSetAsync();

                Assert.Equal(2, products.Count());

                // Query GlobalIndex with an additional non-key condition
                products = await SharedTestFixture.Context.QueryAsync <Product>(
                    product.CompanyName,            // Hash-key for the index is Company
                    QueryOperator.GreaterThan,      // Range-key for the index is Price, so the
                    new object[] { 90 },            // condition is against a numerical value
                    new DynamoDBOperationConfig     // Configure the index to use
                {
                    IndexName   = "GlobalIndex",
                    QueryFilter = new List <ScanCondition>
                    {
                        new ScanCondition("TagSet", ScanOperator.Contains, "1.0")
                    }
                }).GetNextSetAsync();

                Assert.Equal(1, products.Count());

                // Delete first product
                await SharedTestFixture.Context.DeleteAsync <Product>(firstId);

                product = await SharedTestFixture.Context.LoadAsync <Product>(product.Id);

                Assert.Null(product);

                // Scan the table
                products = await SharedTestFixture.Context.ScanAsync <Product>(new List <ScanCondition>()).GetNextSetAsync();

                Assert.Equal(1, products.Count());

                // Scan the table with consistent read
                products = await SharedTestFixture.Context.ScanAsync <Product>(
                    new ScanCondition[] { },
                    new DynamoDBOperationConfig { ConsistentRead = true }).GetNextSetAsync();

                Assert.Equal(1, products.Count());

                // Test a versioned product
                VersionedProduct vp = new VersionedProduct
                {
                    Id          = 3,
                    Name        = "CloudDebugger",
                    CompanyName = "CloudsAreGrate",
                    Price       = 9000,
                    TagSet      = new HashSet <string> {
                        "Test"
                    },
                };
                await SharedTestFixture.Context.SaveAsync(vp);

                // Update and save
                vp.Price++;
                await SharedTestFixture.Context.SaveAsync(vp);

                // Alter the version and try to save
                vp.Version = 0;
                await Assert.ThrowsAsync <ConditionalCheckFailedException>(() => SharedTestFixture.Context.SaveAsync(vp));

                // Load and save
                vp = await SharedTestFixture.Context.LoadAsync(vp);

                await SharedTestFixture.Context.SaveAsync(vp);
            }
            finally
            {
                await UtilityMethods.DeleteBucketWithObjectsAsync(s3Client, bucketName);
            }
        }
コード例 #17
0
        private void TestReplicationConfigurationForPrefix(string prefix)
        {
            var bucketName   = UtilityMethods.GenerateName();
            var euBucketName = "eu" + UtilityMethods.GenerateName();
            var euS3         = new AmazonS3Client(Amazon.RegionEndpoint.EUWest1);

            euS3.PutBucket(euBucketName);
            Client.PutBucket(bucketName);

            euS3.PutBucketVersioning(new PutBucketVersioningRequest
            {
                BucketName       = euBucketName,
                VersioningConfig = new S3BucketVersioningConfig
                {
                    Status = VersionStatus.Enabled
                }
            });

            Client.PutBucketVersioning(new PutBucketVersioningRequest
            {
                BucketName       = bucketName,
                VersioningConfig = new S3BucketVersioningConfig
                {
                    Status = VersionStatus.Enabled
                }
            });

            var roleArn = "arn:aws:iam::pikc123456:role/abcdef";
            var destinationBucketArn = "arn:aws:s3:::" + euBucketName;

            try
            {
                Client.PutBucketReplication(new PutBucketReplicationRequest {
                    BucketName    = bucketName,
                    Configuration = new ReplicationConfiguration
                    {
                        Role  = roleArn,
                        Rules =
                        {
                            new ReplicationRule
                            {
                                Id          = UtilityMethods.GenerateName(),
                                Prefix      = prefix,
                                Status      = ReplicationRuleStatus.Enabled,
                                Destination = new ReplicationDestination
                                {
                                    BucketArn = destinationBucketArn
                                }
                            }
                        }
                    }
                });

                var config = Client.GetBucketReplication(new GetBucketReplicationRequest
                {
                    BucketName = bucketName
                }).Configuration;

                Assert.IsNotNull(config);
                Assert.IsNotNull(config.Role);
                Assert.AreEqual(roleArn, config.Role);
                Assert.IsNotNull(config.Rules);
                Assert.AreEqual(1, config.Rules.Count);

                var rule = config.Rules.First();

                Assert.IsNotNull(rule);
                Assert.IsNotNull(rule.Id);
                Assert.IsNotNull(rule.Prefix);
                if (string.IsNullOrEmpty(prefix))
                {
                    Assert.AreEqual(string.Empty, rule.Prefix);
                }
                else
                {
                    Assert.AreEqual(prefix, rule.Prefix);
                }
                Assert.AreEqual(destinationBucketArn, rule.Destination.BucketArn);

                Client.PutObject(new PutObjectRequest {
                    BucketName  = bucketName,
                    ContentBody = "foo",
                    Key         = "foo-123"
                });

                var status = Client.GetObjectMetadata(new GetObjectMetadataRequest {
                    BucketName = bucketName,
                    Key        = "foo-123"
                }).ReplicationStatus;

                Assert.IsNotNull(status);

                Client.DeleteBucketReplication(new DeleteBucketReplicationRequest {
                    BucketName = bucketName
                });

                var noconfig = Client.GetBucketReplication(new GetBucketReplicationRequest {
                    BucketName = bucketName
                }).Configuration;

                Assert.IsFalse(noconfig.Rules.Any());
            }
            finally
            {
                AmazonS3Util.DeleteS3BucketWithObjects(euS3, euBucketName);
                AmazonS3Util.DeleteS3BucketWithObjects(Client, bucketName);
            }
        }
コード例 #18
0
        /// <summary>
        /// Gets a long-lived S3 Multi-Region Access Point for running integration tests against if
        /// if exists in the current account. If not, creates it and waits for it to be ready.
        /// </summary>
        /// <param name="s3ControlClient">S3Control client to create the MRAP with</param>
        /// <param name="s3Client">S3 client to create the backing bucket with</param>
        /// <returns>ARN of the new Multi-Region Access Point</returns>
        public static string GetOrCreateTestMRAP(IAmazonS3Control s3ControlClient, IAmazonS3 s3Client)
        {
            var accountId = new AmazonSecurityTokenServiceClient().GetCallerIdentity(new GetCallerIdentityRequest()).Account;

            // If the MRAP already exists, return it
            var mrapArn = CheckIfMRAPExists(s3ControlClient, accountId, TEST_MRAP_NAME);

            if (!string.IsNullOrEmpty(mrapArn))
            {
                return(mrapArn);
            }

            // Otherwise the MRAP doesn't exist, so we must create it, starting with the backing bucket.
            var putBucketRequest = new PutBucketRequest {
                BucketName = $"{accountId}-{TEST_MRAP_NAME}"
            };
            var backingBucketName = CreateBucketWithWait(s3Client, putBucketRequest);

            var createMrapRequest = new CreateMultiRegionAccessPointRequest
            {
                AccountId = accountId,
                Details   = new CreateMultiRegionAccessPointInput
                {
                    Name    = TEST_MRAP_NAME,
                    Regions = new List <Region>
                    {
                        new Region
                        {
                            Bucket = backingBucketName
                        }
                    }
                }
            };

            // Initiate the MRAP creation
            var asyncRequestArn = s3ControlClient.CreateMultiRegionAccessPoint(createMrapRequest).RequestTokenARN;

            // Wait until its status is READY
            UtilityMethods.WaitUntilSuccess(() =>
            {
                var request = new GetMultiRegionAccessPointRequest
                {
                    AccountId = accountId,
                    Name      = TEST_MRAP_NAME
                };

                var response = s3ControlClient.GetMultiRegionAccessPoint(request);

                if (response.AccessPoint.Status == MultiRegionAccessPointStatus.READY)
                {
                    // Wait for SSL provisioning to finish
                    Thread.Sleep(TimeSpan.FromMinutes(1));

                    return($"arn:aws:s3::{accountId}:accesspoint/{response.AccessPoint.Alias}");
                }
                else
                {
                    throw new Exception("S3 Multi-Region Access Point not ready yet, will continue waiting.");
                }
            });

            throw new Exception($"{nameof(GetOrCreateTestMRAP)} timed out while creating a new Multi-Region Access Point");
        }
コード例 #19
0
        public void SimpleUploadTest()
        {
            var fileName = UtilityMethods.GenerateName(@"SimpleUploadTest\SmallFile");

            Upload(fileName, 10 * MEG_SIZE, null);
        }
コード例 #20
0
        public void TestMultipartUploadViaTransferUtility(CoreChecksumAlgorithm algorithm)
        {
            var transferConfig = new TransferUtilityConfig {
                MinSizeBeforePartUpload = 6000000
            };
            var transfer          = new TransferUtility(Client, transferConfig);
            var content           = new string('a', 7000000);
            var key               = UtilityMethods.GenerateName(nameof(ChecksumTests));
            var filePath          = Path.Combine(Path.GetTempPath(), key + ".txt");
            var retrievedFilepath = Path.Combine(Path.GetTempPath(), "retreived-" + key + ".txt");

            try
            {
                // Create the file
                using (StreamWriter writer = File.CreateText(filePath))
                {
                    writer.Write(content);
                }

                var uploadRequest = new TransferUtilityUploadRequest
                {
                    BucketName        = _bucketName,
                    Key               = key,
                    FilePath          = filePath,
                    ChecksumAlgorithm = ChecksumAlgorithm.FindValue(algorithm.ToString())
                };

                transfer.Upload(uploadRequest);

                // Get the file back from S3 and assert it is still the same.
                GetObjectRequest getRequest = new GetObjectRequest
                {
                    BucketName   = _bucketName,
                    Key          = uploadRequest.Key,
                    ChecksumMode = ChecksumMode.ENABLED
                };

                var getResponse = Client.GetObject(getRequest);
                var getBody     = new StreamReader(getResponse.ResponseStream).ReadToEnd();
                Assert.AreEqual(content, getBody);

                // We don't expect the checksum to be validated on getting an entire multipart object,
                // because it's actually the checksum-of-checksums
                Assert.AreEqual(CoreChecksumAlgorithm.NONE, getResponse.ResponseMetadata.ChecksumAlgorithm);
                Assert.AreEqual(ChecksumValidationStatus.NOT_VALIDATED, getResponse.ResponseMetadata.ChecksumValidationStatus);

                // Similarily we don't expect this to validate either,
                // though it doesn't expose the reponse metadata
                transfer.Download(new TransferUtilityDownloadRequest
                {
                    BucketName   = _bucketName,
                    Key          = uploadRequest.Key,
                    FilePath     = retrievedFilepath,
                    ChecksumMode = ChecksumMode.ENABLED
                });
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                if (File.Exists(retrievedFilepath))
                {
                    File.Delete(retrievedFilepath);
                }
            }
        }
コード例 #21
0
 public ObjectWithFactory(T factory)
 {
     UtilityMethods.ThrowIfArgumentNull(factory);
     this.Factory = factory;
 }
コード例 #22
0
 private void SmoothlyLookAtTarget(Vector3 target)
 {
     towerPieceToAim.localRotation = UtilityMethods.
                                     SmoothlyLook(towerPieceToAim, target);
 }
コード例 #23
0
        public void LambdaFunctionTest()
        {
            string functionName;
            string iamRoleName    = null;
            bool   iamRoleCreated = false;

            try
            {
                string iamRoleArn;
                string functionArn;
                CreateLambdaFunction(out functionName, out functionArn, out iamRoleName, out iamRoleArn);

                // List all the functions and make sure the newly uploaded function is in the collection
                UtilityMethods.WaitUntilSuccess(() =>
                {
                    var functions = EnumerateFunctions().ToList();
                    var function  = functions.FirstOrDefault(x => x.FunctionName == functionName);
                    Assert.IsNotNull(function);
                    Assert.AreEqual("helloworld.handler", function.Handler);
                    Assert.AreEqual(iamRoleArn, function.Role);
                });

                // Get the function with a presigned URL to the uploaded code
                var getFunctionResponse = Client.GetFunction(functionName);
                Assert.AreEqual("helloworld.handler", getFunctionResponse.Configuration.Handler);
                Assert.IsNotNull(getFunctionResponse.Code.Location);

                // Get the function's configuration only
                var getFunctionConfiguration = Client.GetFunctionConfiguration(functionName);
                Assert.AreEqual("helloworld.handler", getFunctionConfiguration.Handler);

                // Call the function
                var invokeAsyncResponse = Client.InvokeAsync(functionName);
                Assert.AreEqual(invokeAsyncResponse.Status, 202); // Status Code Accepted

                var clientContext       = @"{""System"": ""Windows""}";
                var clientContextBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(clientContext));
                var request             = new InvokeRequest
                {
                    FunctionName   = functionName,
                    InvocationType = InvocationType.RequestResponse,
                    LogType        = LogType.None,
                    ClientContext  = clientContext,
                    Payload        = @"{""Key"": ""testing""}"
                };
                Assert.AreEqual(clientContext, request.ClientContext);
                Assert.AreEqual(clientContextBase64, request.ClientContextBase64);

                // Call the function sync
                var invokeSyncResponse = Client.Invoke(request);
                Assert.IsNull(invokeSyncResponse.FunctionError);
                Assert.IsNull(invokeSyncResponse.LogResult);
                Assert.IsNotNull(invokeSyncResponse.Payload);
                Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
                Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);

                // Call the function sync, dry run, no payload
                invokeSyncResponse = Client.Invoke(new InvokeRequest
                {
                    FunctionName   = functionName,
                    InvocationType = InvocationType.DryRun,
                    LogType        = LogType.None,
                    ClientContext  = clientContext,
                    Payload        = @"{""Key"": ""testing""}"
                });
                Assert.IsNull(invokeSyncResponse.FunctionError);
                Assert.IsNull(invokeSyncResponse.LogResult);
                Assert.IsNotNull(invokeSyncResponse.Payload);
                Assert.AreEqual(0, invokeSyncResponse.Payload.Length);
                Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);

                // Call the function sync, pass non-JSON payload
                invokeSyncResponse = Client.Invoke(new InvokeRequest
                {
                    FunctionName   = functionName,
                    InvocationType = InvocationType.RequestResponse,
                    LogType        = LogType.None,
                    ClientContext  = clientContext,
                    Payload        = @"""Key"": ""testing"""
                });
                Assert.IsNotNull(invokeSyncResponse.FunctionError);
                Assert.IsNull(invokeSyncResponse.LogResult);
                Assert.IsNotNull(invokeSyncResponse.Payload);
                Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
                Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
            }
            finally
            {
                if (iamRoleCreated)
                {
                    iamClient.DeleteRole(new DeleteRoleRequest {
                        RoleName = iamRoleName
                    });
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Collects model metrics and returns a dictionary
        /// </summary>
        /// <param name="doc">The active document</param>
        /// <returns>Dictionary</returns>
        public Dictionary <string, object> CollectModelData(Document doc, Application app)
        {
            /*
             * the basic strategy is to use filtered element collectors to collect the relevant data.
             * some helper functions are defined in order to collect more complicated metrics that require the use of several element collectors.
             * examples: unused elements and redundant elements require helper functions
             */

            IList <FailureMessage> warnings  = doc.GetWarnings();
            IList <Element>        linkedRVT = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToList();
            Dictionary <string, IList <Element> > nonRvtLinks = RevitMethods.NonRVTLinkCollector(doc);
            IList <Element>        linkedCAD            = nonRvtLinks[RevitConstants.Strings.linkedCAD];
            IList <Element>        importedCAD          = nonRvtLinks[RevitConstants.Strings.importedCAD];
            IList <Element>        importedSKP          = nonRvtLinks[RevitConstants.Strings.importedSKP];
            IList <Element>        raster               = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RasterImages).WhereElementIsNotElementType().ToList();
            IList <Element>        sheets               = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToList();
            IList <View>           views                = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Cast <View>().Where(v => !v.IsTemplate).ToList();
            IList <View>           unplacedViews        = RevitMethods.UnplacedViewCollector(doc, sheets);
            IList <Element>        modelGroups          = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_IOSModelGroups).WhereElementIsNotElementType().ToList();
            IList <Element>        detailGroups         = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_IOSDetailGroups).WhereElementIsNotElementType().ToList();
            IList <Family>         inPlaceFamilies      = new FilteredElementCollector(doc).OfClass(typeof(Family)).Cast <Family>().Where(f => f.IsInPlace).ToList();
            IList <Element>        designOptionElements = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(e => e.DesignOption != null).ToList();
            IList <Workset>        worksets             = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset).ToList();
            IList <Element>        rooms                = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToList();
            IList <SpatialElement> unplacedRooms        = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().Cast <SpatialElement>().Where(r => r.Area == 0 && r.Location == null).ToList();
            IList <SpatialElement> redundantRooms       = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().Cast <SpatialElement>().Where(r => r.Area == 0 && r.Location != null).ToList();
            IList <Element>        redundantElements    = RevitMethods.RedundantElementsCollector(warnings, doc);
            int unusedElements = unplacedViews.Count + unplacedRooms.Count + RevitMethods.UnusedFamiliesCollector(doc).Count;

            // collect model specific information
            (string writeDate, string writeTime) = UtilityMethods.FormatDateTime();
            (string modelPath, string modelName, string modelSize) = RevitMethods.GetModelInfo(doc);
            string versionBuild = app.VersionBuild;

            // save collected data in a dictionary
            Dictionary <string, object> modelMetrics = new Dictionary <string, object>()
            {
                { "Model Name", modelName },
                { "Model Path", modelPath },
                { "Model Size", modelSize },
                { "Warnings", warnings },
                { "Linked RVT Files", linkedRVT },
                { "Linked CAD Files", linkedCAD },
                { "Imported CAD Files", importedCAD },
                { "Imported SKP Files", importedSKP },
                { "Raster Images", raster },
                { "Sheets", sheets },
                { "Views", views },
                { "Unplaced Views", unplacedViews },
                { "Model Groups", modelGroups },
                { "Detail Groups", detailGroups },
                { "In-place Families", inPlaceFamilies },
                { "Elements in Design Options", designOptionElements },
                { "Worksets", worksets },
                { "Rooms", rooms },
                { "Unplaced Rooms", unplacedRooms },
                { "Redundant and Unenclosed Rooms", redundantRooms },
                { "Redundant Elements", redundantElements },
                { "Unused Elements", unusedElements },
                { "Write Date", writeDate },
                { "Write Time", writeTime },
                { "Version Build", versionBuild },
            };

            return(modelMetrics);
        }
コード例 #25
0
 /// <summary>
 /// A text-based representation of the current state of the game board.
 /// </summary>
 /// <remarks>
 /// When rendering cells, use '<see cref="Constants.AliveCell"/>' for alive cells & '<see cref="Constants.DeadCell"/>' for dead cells.
 /// </remarks>
 /// <returns>
 /// A string representing the current state of the game board.
 /// </returns>
 public override string ToString()
 {
     return UtilityMethods.JaggedArrayToString(Cells);
 }