static void Main(string[] args)
 {
     Test test = new Test();
     QualityThought.Batch2.NamespaceLibrary.UI.TestUI testui = new NamespaceLibrary.UI.TestUI();
     TestUI ui = new TestUI();
     QualityThought.Batch2.NamespaceLibrary.Common.TestCommon testCommon = new NamespaceLibrary.Common.TestCommon();
     TestCommon testC = new TestCommon();
     MyCommon.TestMe testMe = new MyCommon.TestMe();
     MyUI.TestMe testMeUI = new MyUI.TestMe();
 }
Exemple #2
0
        public void AssetTransfer_CopyAssetToTarget_LargeFileTest()
        {
            //Note: This is more of a system test rather than unit given its dependency on SharePoint

            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
                {
                    AssetTransfer assetTransfer = new AssetTransfer(sourceClientContext, targetClientContext);

                    // Very crude test - ensure the site is setup for this ahead of the test
                    // Note this file is not included in this project assets due to its licensing. Pls find a > 3MB file to use as a test.
                    var targetWebUrl = targetClientContext.Web.EnsureProperty(o => o.ServerRelativeUrl);
                    var sourceWebUrl = sourceClientContext.Web.EnsureProperty(o => o.ServerRelativeUrl);

                    var sourceFileServerRelativeUrl = $"{sourceWebUrl}/SiteImages/bigstock-Html-Web-Code-57446159.jpg";
                    var targetLocation = $"{targetWebUrl}/Shared%20Documents"; //Shared Documents for example, Site Assets may not exist on vanilla sites

                    assetTransfer.CopyAssetToTargetLocation(sourceFileServerRelativeUrl, targetLocation);
                }
            }

            Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
Exemple #3
0
        public void WebPartTests()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                ctx.Load(ctx.Web, w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup.Title);
                ctx.Load(ctx.Site, s => s.ServerRelativeUrl);
                ctx.ExecuteQueryRetry();

                var listGuid  = Guid.NewGuid();
                var listTitle = "MyList";
                var web       = ctx.Web;

                ProvisioningTemplate template = new ProvisioningTemplate();
                template.Parameters.Add("test", "test");
                var parser = new TokenParser(ctx.Web, template);
                parser.AddToken(new ListIdToken(web, listTitle, listGuid));
                parser.ParseString($"{{listid:{listTitle}}}");
                var listId = parser.ParseStringWebPart($"{{listid:{listTitle}}}", web, null);
                Assert.IsTrue(listGuid.ToString() == listId);

                var parameterValue = parser.ParseStringWebPart("{parameter:test}", web, null);
                Assert.IsTrue("test" == parameterValue);
            }
        }
        private static void CreateSiteCollection(string template, string siteUrl)
        {
            // check if site exists
            using (var tenantCtx = TestCommon.CreateTenantClientContext())
            {
                Tenant tenant = new Tenant(tenantCtx);

                if (tenant.SiteExists(siteUrl))
                {
                    Console.WriteLine("Deleting existing site {0}", siteUrl);
                    tenant.DeleteSiteCollection(siteUrl, false);
                }
                Console.WriteLine("Creating new site {0}", siteUrl);
                tenant.CreateSiteCollection(new Entities.SiteEntity()
                {
                    Lcid           = 1033,
                    TimeZoneId     = 4,
                    SiteOwnerLogin = (TestCommon.Credentials as SharePointOnlineCredentials).UserName,
                    Title          = "Template Site",
                    Template       = template,
                    Url            = siteUrl,
                }, true, true);
            }
        }
        public void SchemaDefinitionForPredictionEngine()
        {
            var fileName  = TestCommon.GetDataPath(DataDir, TestDatasets.adult.trainFilename);
            var loader    = _ml.Data.CreateTextLoader(new TextLoader.Options(), new MultiFileSource(fileName));
            var data      = loader.Load(new MultiFileSource(fileName));
            var pipeline1 = _ml.Transforms.Categorical.OneHotEncoding("Cat", "Workclass", maximumNumberOfKeys: 3)
                            .Append(_ml.Transforms.Concatenate("Features", "Cat", "NumericFeatures"));
            var model1 = pipeline1.Fit(data);

            var pipeline2 = _ml.Transforms.Categorical.OneHotEncoding("Cat", "Workclass", maximumNumberOfKeys: 4)
                            .Append(_ml.Transforms.Concatenate("Features", "Cat", "NumericFeatures"));
            var model2 = pipeline2.Fit(data);

            var outputSchemaDefinition = SchemaDefinition.Create(typeof(OutputData));

            outputSchemaDefinition["Features"].ColumnType = model1.GetOutputSchema(data.Schema)["Features"].Type;
            var engine1 = _ml.Model.CreatePredictionEngine <InputData, OutputData>(model1, outputSchemaDefinition: outputSchemaDefinition);

            outputSchemaDefinition = SchemaDefinition.Create(typeof(OutputData));
            outputSchemaDefinition["Features"].ColumnType = model2.GetOutputSchema(data.Schema)["Features"].Type;
            var engine2 = _ml.Model.CreatePredictionEngine <InputData, OutputData>(model2, outputSchemaDefinition: outputSchemaDefinition);

            var prediction = engine1.Predict(new InputData()
            {
                Workclass = "Self-emp-not-inc", NumericFeatures = new float[6]
            });

            Assert.Equal((engine1.OutputSchema["Features"].Type as VectorDataViewType).Size, prediction.Features.Length);
            Assert.True(prediction.Features.All(x => x == 0));
            prediction = engine2.Predict(new InputData()
            {
                Workclass = "Self-emp-not-inc", NumericFeatures = new float[6]
            });
            Assert.Equal((engine2.OutputSchema["Features"].Type as VectorDataViewType).Size, prediction.Features.Length);
            Assert.True(prediction.Features.Select((x, i) => i == 3 && x == 1 || x == 0).All(b => b));
        }
Exemple #6
0
        public async Task SaveMultipleAppmetadataAsync()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response  = TestConstants.CreateMsalTokenResponse();
            MsalTokenResponse response2 = TestConstants.CreateMsalTokenResponse();

            response2.FamilyId = "1";

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle);

            requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            await cache.SaveTokenResponseAsync(requestParams, response2).ConfigureAwait(false);

            cache.Accessor.AssertItemCount(
                expectedAtCount: 1,
                expectedRtCount: 2, // a normal RT and an FRT
                expectedAccountCount: 1,
                expectedIdtCount: 1,
                expectedAppMetadataCount: 1);

            var metadata = cache.Accessor.GetAllAppMetadata().First();

            Assert.AreEqual(TestConstants.ClientId, metadata.ClientId);
            Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, metadata.Environment);
            Assert.AreEqual(TestConstants.FamilyId, metadata.FamilyId);

            Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => rt.FamilyId == "1"));
            Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => string.IsNullOrEmpty(rt.FamilyId)));
        }
Exemple #7
0
        public void ListExistsByGuidTest()
        {
            var listName = "samplelist_" + DateTime.Now.ToFileTime();
            var listGuid = Guid.NewGuid();

            using (var clientContext = TestCommon.CreateClientContext())
            {
                var list = clientContext.Web.CreateList(
                    ListTemplateType.GenericList,
                    listName,
                    false);


                clientContext.Load <List>(list, l => l.Id);
                clientContext.ExecuteQueryRetry();

                Assert.IsNotNull(list);
                Assert.IsTrue(clientContext.Web.ListExists(list.Id));

                //Delete List
                list.DeleteObject();
                clientContext.ExecuteQueryRetry();
            }
        }
        public async Task BreakRoleInheritanceTestNoCopyAssignmentsNoClearSubscopes()
        {
            //TestCommon.Instance.Mocking = false;

            using (var context = await TestCommon.Instance.GetContextAsync(TestCommon.TestSite))
            {
                // Create a new list
                string listName = TestCommon.GetPnPSdkTestAssetName("BreakRoleInheritanceTestNoCopyAssignmentsNoClearSubscopes");
                await InitializeTestListAsync(context, listName);

                var myList = await context.Web.Lists.GetByTitleAsync(listName, p => p.Title, p => p.Items);


                // get first item and do a break role inheritance
                var first = myList.Items.First();

                await first.BreakRoleInheritanceBatchAsync(false, false);

                await context.ExecuteAsync();

                // Delete the list
                await myList.DeleteAsync();
            }
        }
        private static void CleanupAllTestSiteCollections(ClientContext tenantContext)
        {
            string devSiteUrl = TestCommon.AppSetting("SPODevSiteUrl");

            var tenant = new Tenant(tenantContext);

            try
            {
                using (ClientContext cc = tenantContext.Clone(devSiteUrl))
                {
                    var sites = cc.Web.SiteSearch();

                    foreach (var site in sites)
                    {
                        if (site.Url.ToLower().Contains(sitecollectionNamePrefix.ToLower()))
                        {
                            tenant.DeleteSiteCollection(site.Url);
                        }
                    }
                }
            }
            catch
            { }
        }
        void IntrospectGamShapeFunctions()
        {
            // Concurrency must be 1 to assure that the mapping is done sequentially.
            var mlContext = new MLContext(seed: 1);

            // Load the Iris dataset.
            var data = mlContext.Data.LoadFromTextFile <Iris>(
                TestCommon.GetDataPath(DataDir, TestDatasets.iris.trainFilename),
                hasHeader: TestDatasets.iris.fileHasHeader,
                separatorChar: TestDatasets.iris.fileSeparator);

            // Compose the transformation.
            var pipeline = mlContext.Transforms.Concatenate("Features", Iris.Features)
                           .Append(mlContext.Regression.Trainers.Gam(
                                       new GamRegressionTrainer.Options {
                NumberOfIterations = 100, NumberOfThreads = 1
            }));

            // Fit the pipeline.
            var model = pipeline.Fit(data);

            // Extract the normalizer from the trained pipeline.
            var gamModel = model.LastTransformer.Model;

            // Take look at the shape functions.
            for (int i = 0; i < gamModel.NumberOfShapeFunctions; i++)
            {
                var shapeFunctionBins   = gamModel.GetBinUpperBounds(i);
                var shapeFunctionValues = gamModel.GetBinEffects(i);

                // Validate that the shape functions lengths match.
                Assert.Equal(shapeFunctionBins.Count, shapeFunctionValues.Count);
                Common.AssertFiniteNumbers(shapeFunctionBins as IList <double>, shapeFunctionBins.Count - 1);
                Common.AssertFiniteNumbers(shapeFunctionValues as IList <double>);
            }
        }
        public void BeginReadWhileWriting()
        {
            FileHelperAsyncEngine eng = new FileHelperAsyncEngine(typeof(SampleType));

            var filename = TestCommon.GetTempFile("TempWrite.txt");

            Assert.Throws <BadUsageException>(()
                                              =>
            {
                try
                {
                    eng.BeginWriteFile(filename);
                    eng.BeginReadString("jejjeje");
                }
                finally
                {
                    eng.Close();
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                }
            });
        }
Exemple #12
0
        public void DiscardWriteRead2()
        {
            var engine = new FileHelperEngine <DiscardLastType1>();

            DiscardLastType1[] res = TestCommon.ReadTest <DiscardLastType1>(engine, "Good", "DiscardLast1.txt");


            var asyncEngine = new FileHelperAsyncEngine <DiscardLastType1>();

            asyncEngine.FooterText = "This is a new Footer....";

            asyncEngine.BeginWriteFile("temp.txt");
            asyncEngine.WriteNexts(res);
            asyncEngine.Close();

            asyncEngine.FooterText = "none none";

            asyncEngine.BeginReadFile("temp.txt");

            while (asyncEngine.ReadNext() != null)
            {
            }

            Assert.AreEqual(res.Length, asyncEngine.TotalRecords);
            Assert.AreEqual(expectedShortFooterText, asyncEngine.FooterText);

            asyncEngine.Close();

            Assert.AreEqual(res.Length, asyncEngine.TotalRecords);
            Assert.AreEqual(expectedShortFooterText, asyncEngine.FooterText);

            if (File.Exists("tempo.txt"))
            {
                File.Delete("tempo.txt");
            }
        }
Exemple #13
0
        public void DiscardWriteRead()
        {
            var engine = new FileHelperEngine <DiscardLastType1>();

            DiscardLastType1[] res = TestCommon.ReadTest <DiscardLastType1>(engine, "Good", "DiscardLast1.txt");
            engine.FooterText = expectedShortFooterText;

            engine.WriteFile("tempo.txt", res);

            engine.FooterText = "none none";

            DiscardLastType1[] res2 = engine.ReadFile(@"tempo.txt");

            Assert.AreEqual(res.Length, res2.Length);
            Assert.AreEqual(expectedShortFooterText, engine.FooterText);

            if (File.Exists("tempo.txt"))
            {
                File.Delete("tempo.txt");
            }

            Assert.AreEqual(4, res.Length);
            Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
        }
Exemple #14
0
        public static async Task UpdateApplicationPackageAsync(string applicationId, string defaultVersion, string displayName, bool hasDefaultVersion)
        {
            string accountName       = TestCommon.Configuration.BatchAccountName;
            string resourceGroupName = TestCommon.Configuration.BatchAccountResourceGroup;

            BatchManagementClient mgmtClient = TestCommon.OpenBatchManagementClient();

            if (hasDefaultVersion)
            {
                await mgmtClient.Applications.UpdateApplicationAsync(
                    resourceGroupName,
                    accountName,
                    applicationId,
                    new UpdateApplicationParameters { AllowUpdates = true, DefaultVersion = defaultVersion, DisplayName = displayName });
            }
            else
            {
                await mgmtClient.Applications.UpdateApplicationAsync(
                    resourceGroupName,
                    accountName,
                    applicationId,
                    new UpdateApplicationParameters { AllowUpdates = true, DisplayName = displayName });
            }
        }
        internal void SiteCollectionCustomActionAdding(string url)
        {
            using (var cc = TestCommon.CreateClientContext(url))
            {
                // Ensure we can test clean
                DeleteCustomActions(cc);

                // Add custom actions
                var result = TestProvisioningTemplate(cc, "customaction_add.xml", Handlers.CustomActions);

                // Ensure the needed tokens are added to the target token parser, this is needed due to the tokenparser perf optimalizations
                result.TargetTokenParser.Tokens.Add(new SiteToken(cc.Web));
                result.TargetTokenParser.Tokens.Add(new SiteTitleToken(cc.Web));
                result.TargetTokenParser.Tokens.Add(new GroupSiteTitleToken(cc.Web));

                Assert.IsTrue(CustomActionValidator.Validate(result.SourceTemplate.CustomActions, result.TargetTemplate.CustomActions, result.TargetTokenParser, cc.Web));

                // Update custom actions
                var result2 = TestProvisioningTemplate(cc, "customaction_delta_1.xml", Handlers.CustomActions);
                // Ensure the needed tokens are added to the target token parser, this is needed due to the tokenparser perf optimalizations
                result2.TargetTokenParser.Tokens.Add(new SiteToken(cc.Web));
                result2.TargetTokenParser.Tokens.Add(new SiteTitleToken(cc.Web));
                result2.TargetTokenParser.Tokens.Add(new GroupSiteTitleToken(cc.Web));

                Assert.IsTrue(CustomActionValidator.Validate(result2.SourceTemplate.CustomActions, result2.TargetTemplate.CustomActions, result2.TargetTokenParser, cc.Web));

                // Update custom actions
                var result3 = TestProvisioningTemplate(cc, "customaction_1605_delta_2.xml", Handlers.CustomActions);
                // Ensure the needed tokens are added to the target token parser, this is needed due to the tokenparser perf optimalizations
                result3.TargetTokenParser.Tokens.Add(new SiteToken(cc.Web));
                result3.TargetTokenParser.Tokens.Add(new SiteTitleToken(cc.Web));
                result3.TargetTokenParser.Tokens.Add(new GroupSiteTitleToken(cc.Web));

                Assert.IsTrue(CustomActionValidator.Validate(result3.SourceTemplate.CustomActions, result3.TargetTemplate.CustomActions, result3.TargetTokenParser, cc.Web));
            }
        }
Exemple #16
0
        public void DiscardWriteRead2()
        {
            engine = new FileHelperEngine(typeof(DiscardLastType1));

            DiscardLastType1[] res = (DiscardLastType1[])TestCommon.ReadTest(engine, @"Good\DiscardLast1.txt");


            asyncEngine = new FileHelperAsyncEngine(typeof(DiscardLastType1));

            asyncEngine.FooterText = "This is a new Footer....";

            asyncEngine.BeginWriteFile("temp.txt");
            asyncEngine.WriteNexts(res);
            asyncEngine.EndsWrite();

            asyncEngine.FooterText = "none none";

            asyncEngine.BeginReadFile("temp.txt");

            while (asyncEngine.ReadNext() != null)
            {
            }

            Assert.AreEqual(res.Length, asyncEngine.TotalRecords);
            Assert.AreEqual("This is a new Footer....\r\n", asyncEngine.FooterText);

            asyncEngine.EndsRead();

            Assert.AreEqual(res.Length, asyncEngine.TotalRecords);
            Assert.AreEqual("This is a new Footer....\r\n", asyncEngine.FooterText);

            if (File.Exists("tempo.txt"))
            {
                File.Delete("tempo.txt");
            }
        }
Exemple #17
0
        public void CrossSiteTransform_SameSite_OverwriteOffTest()
        {
            //Test Requires a test site
            using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
            {
                var pageTransformator = new PageTransformator(sourceClientContext);
                pageTransformator.RegisterObserver(new UnitTestLogObserver());

                var pages = sourceClientContext.Web.GetPages("wpp_with"); //Specific page - aim for one file

                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        // If target page exists, then overwrite it
                        Overwrite = false,

                        // Don't log test runs
                        SkipTelemetry = true,

                        TargetPagePrefix = "Converted_",
                    };

                    pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                    pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                    var result = Assert.ThrowsException <ArgumentException>(() =>
                    {
                        var result1 = pageTransformator.Transform(pti);
                        var result2 = pageTransformator.Transform(pti); //Run twice incase target site didnt have the file in the first place
                    });

                    Assert.IsTrue(result.Message.Contains("Not overwriting - there already exists a page with name"));
                }
            }
        }
Exemple #18
0
        public void Logging_NormalOperationTest()
        {
            using (var sourceClientContext = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(sourceClientContext);
                pageTransformator.RegisterObserver(new UnitTestLogObserver()); // Example of registering an observer, this can be anything really.

                var pages = sourceClientContext.Web.GetPages("wk").Take(1);

                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        // If target page exists, then overwrite it
                        Overwrite = true,

                        // Don't log test runs
                        SkipTelemetry = true,

                        // ModernizationCenter options
                        ModernizationCenterInformation = new ModernizationCenterInformation()
                        {
                            AddPageAcceptBanner = true
                        },

                        // Give the migrated page a specific prefix, default is Migrated_
                        TargetPagePrefix = "Converted_",

                        // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                        HandleWikiImagesAndVideos = false,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
        public void CleanUp()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var f = ctx.Web.GetFieldById <FieldText>(fieldId);                               // Guid matches ID in field caml.
                var calculatedField = ctx.Web.GetFieldById <FieldCalculated>(calculatedFieldId); // Guid matches ID in field caml.

                bool fieldDeleted = false;
                if (f != null)
                {
                    f.DeleteObject();
                    fieldDeleted = true;
                }
                if (calculatedField != null)
                {
                    calculatedField.DeleteObject();
                    fieldDeleted = true;
                }
                if (fieldDeleted)
                {
                    ctx.ExecuteQueryRetry();
                }
            }
        }
        public async Task EncryptionResourceTokenAuthAllowed()
        {
            User keyManagerUser = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(keyManagerUser.Id);

            PermissionProperties keyManagerUserPermission = await keyManagerUser.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.keyContainer));

            CosmosDataEncryptionKeyProvider dekProvider = new CosmosDataEncryptionKeyProvider(new TestKeyWrapProvider());
            TestEncryptor encryptor = new TestEncryptor(dekProvider);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient clientForKeyManagerUser = new CosmosClientBuilder(endpoint, keyManagerUserPermission.Token)
                                                   .WithEncryptor(encryptor)
                                                   .Build();

            Database databaseForKeyManagerUser = clientForKeyManagerUser.GetDatabase(EncryptionTests.databaseCore.Id);

            await dekProvider.InitializeAsync(databaseForKeyManagerUser, EncryptionTests.keyContainer.Id);

            DataEncryptionKeyProperties readDekProperties = await dekProvider.DataEncryptionKeyContainer.ReadDataEncryptionKeyAsync(EncryptionTests.dekId);

            Assert.AreEqual(EncryptionTests.dekProperties, readDekProperties);
        }
Exemple #21
0
        internal void SiteCollectionListAdding(string url)
        {
            using (var cc = TestCommon.CreateClientContext(url))
            {
                // Ensure we can test clean
                DeleteLists(cc);

                // Add supporting files needed during add
                TestProvisioningTemplate(cc, "list_supporting_data_1.xml", Handlers.Fields | Handlers.ContentTypes);

                // Add lists
                var result = TestProvisioningTemplate(cc, "list_add.xml", Handlers.Lists);
                ListInstanceValidator lv = new ListInstanceValidator(cc);
                Assert.IsTrue(lv.Validate(result.SourceTemplate.Lists, result.TargetTemplate.Lists, result.TargetTokenParser));

                // Add supporting files needed during delta testing
                TestProvisioningTemplate(cc, "list_supporting_data_2.xml", Handlers.Files);

                // Delta lists
                var result2 = TestProvisioningTemplate(cc, "list_delta_1.xml", Handlers.Lists);
                ListInstanceValidator lv2 = new ListInstanceValidator(cc);
                Assert.IsTrue(lv2.Validate(result2.SourceTemplate.Lists, result2.TargetTemplate.Lists, result2.TargetTokenParser));
            }
        }
Exemple #22
0
        public void CanProvisionSite()
        {
            XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(@"{0}\..\..\Resources",
                                  AppDomain.CurrentDomain.BaseDirectory),
                    "Templates");

            var hierarchy = provider.GetHierarchy("ProvisioningSchema-2019-03-FullSample-01.xml");

            CanProvisionResult result = null;

            using (var pnpContext = new PnPProvisioningContext())
            {
                using (var context = TestCommon.CreateClientContext())
                {
                    var applyingInformation = new ProvisioningTemplateApplyingInformation();
                    result = CanProvisionRulesManager.CanProvision(context.Web, hierarchy.Templates[0], applyingInformation);
                }
            }

            Assert.IsNotNull(result);
            Assert.IsTrue(result.CanProvision);
        }
Exemple #23
0
        private void CoreRunAsync(params string[] pathElements)
        {
            var arr = new ArrayList();

            TestCommon.BeginReadTest(asyncEngine, pathElements);

            foreach (object record in asyncEngine)
            {
                arr.Add(record);
            }

            var res = (CustomersVerticalBar[])arr.ToArray(typeof(CustomersVerticalBar));

            Check.That(ExpectedRecords).IsEqualTo(res.Length);
            Check.That(ExpectedRecords).IsEqualTo(asyncEngine.TotalRecords);

            Check.That(expectedTextWithNTilde).IsEqualTo(res[1].CompanyName);
            Check.That(expectedTextWithEGrave).IsEqualTo(res[6].CompanyName);
            Check.That(expectedTextWithEAcute1).IsEqualTo(res[6].ContactName);

            Check.That(expectedTextWithEAcute2).IsEqualTo(res[6].Address);
            Check.That(expectedTextWithADiaeresis).IsEqualTo(res[4].Address);
            Check.That(expectedTextWithARing).IsEqualTo(res[4].City);
        }
Exemple #24
0
        public void DeployRetractAppTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                AppManager manager  = new AppManager(clientContext);
                var        appBytes = OfficeDevPnP.Core.Tests.Properties.Resources.almskip;

                var results = manager.Add(appBytes, $"appalmskip-{appGuid}.sppkg", true);

                var deployResults = manager.Deploy(results.Id);
                Assert.IsTrue(deployResults);

                var metadata = manager.GetAvailable(results.Id);
                Assert.IsTrue(metadata.Deployed);

                var retractResults = manager.Retract(results.Id);
                Assert.IsTrue(retractResults);

                metadata = manager.GetAvailable(results.Id);
                Assert.IsFalse(metadata.Deployed);

                manager.Remove(results.Id);
            }
        }
Exemple #25
0
        public async Task IteratorTest()
        {
            using (CosmosClient cosmosClient = TestCommon.CreateCosmosClient(new CosmosClientOptions() { Serializer = new FaultySerializer() }))
            {
                // Should not use the custom serializer for these operations
                Scripts scripts = cosmosClient.GetContainer(this.database.Id, this.container.Id).Scripts;
                string sprocBody = "function() { { var x = 42; } }";
                int numberOfSprocs = 3;
                string[] sprocIds = new string[numberOfSprocs];

                for (int i = 0; i < numberOfSprocs; i++)
                {
                    string sprocId = Guid.NewGuid().ToString();
                    sprocIds[i] = sprocId;

                    StoredProcedureResponse storedProcedureResponse =
                        await scripts.CreateStoredProcedureAsync(new StoredProcedureProperties(sprocId, sprocBody));
                    Assert.AreEqual(HttpStatusCode.Created, storedProcedureResponse.StatusCode);
                }

                List<string> readSprocIds = new List<string>();
                FeedIterator<StoredProcedureProperties> iter = scripts.GetStoredProcedureQueryIterator<StoredProcedureProperties>();
                while (iter.HasMoreResults)
                {
                    FeedResponse<StoredProcedureProperties> currentResultSet = await iter.ReadNextAsync();
                    {
                        foreach (StoredProcedureProperties storedProcedureSettingsEntry in currentResultSet)
                        {
                            readSprocIds.Add(storedProcedureSettingsEntry.Id);
                        }
                    }
                }

                CollectionAssert.AreEquivalent(sprocIds, readSprocIds);
            }
        }
Exemple #26
0
        public void SeattleMasterPageIsUnchanged()
        {
            using (var context = TestCommon.CreateClientContext())
            {
                var web = context.Web;
                //need to get the server relative url
                context.Load(web, w => w.ServerRelativeUrl);
                context.ExecuteQuery();
                //Use the existing context to directly get a copy of the seattle master page
                string          masterpageGalleryServerRelativeUrl = UrlUtility.Combine(UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl), "_catalogs/masterpage/");
                var             serverRelativeUrlOfSeattle         = UrlUtility.Combine(masterpageGalleryServerRelativeUrl, builtInMasterSeattle);
                FileInformation seattle = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, serverRelativeUrlOfSeattle);
                Assert.IsNotNull(seattle);


                //Compute a hash of the file
                var    hashAlgorithm = HashAlgorithm.Create();
                byte[] hash          = hashAlgorithm.ComputeHash(seattle.Stream);
                //Convert to a hex string for human consumption
                string hex = BitConverter.ToString(hash);
                //Check against last known hash
                Assert.AreEqual(knownHashOfSeattle, hex);
            }
        }
        public void AnotherDelimiterTest()
        {
            var engine = new FileHelperEngine <AnotherDelimiterType>();

            var res = TestCommon.ReadTest <AnotherDelimiterType>(engine, "Good", "CustomConverter2.txt");

            Assert.AreEqual(4, res.Length);

            Assert.AreEqual("Bahia Blanca", res[0].City);
            Assert.AreEqual("Sin Nombre", res[0].Street);
            Assert.AreEqual("13", res[0].Number);

            Assert.AreEqual("Saavedra", res[1].City);
            Assert.AreEqual("Florencio Sanches", res[1].Street);
            Assert.AreEqual("s/n", res[1].Number);

            Assert.AreEqual("Bs.As", res[2].City);
            Assert.AreEqual("12 de Octubre", res[2].Street);
            Assert.AreEqual("4", res[2].Number);

            Assert.AreEqual("Chilesito", res[3].City);
            Assert.AreEqual("Pololo", res[3].Street);
            Assert.AreEqual("5421", res[3].Number);
        }
        public async Task TestCustomJsonSerializer()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            Mock <CosmosSerializer> mockJsonSerializer = new Mock <CosmosSerializer>();

            //The item object will be serialized with the custom json serializer.
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();

            mockJsonSerializer.Setup(x => x.ToStream <ToDoActivity>(It.IsAny <ToDoActivity>()))
            .Callback(() => toStreamCount++)
            .Returns(TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem));

            mockJsonSerializer.Setup(x => x.FromStream <ToDoActivity>(It.IsAny <Stream>()))
            .Callback <Stream>(x => { x.Dispose(); fromStreamCount++; })
            .Returns(testItem);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosClient mockClient = TestCommon.CreateCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.WithCustomSerializer(mockJsonSerializer.Object));
            Container mockContainer = mockClient.GetContainer(this.database.Id, this.container.Id);

            Assert.AreEqual(mockJsonSerializer.Object, mockClient.ClientOptions.Serializer);

            //Validate that the custom json serializer is used for creating the item
            ItemResponse <ToDoActivity> response = await mockContainer.CreateItemAsync <ToDoActivity>(item : testItem);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            Assert.AreEqual(1, toStreamCount);
            Assert.AreEqual(1, fromStreamCount);

            await mockContainer.DeleteItemAsync <ToDoActivity>(testItem.id, new Cosmos.PartitionKey(testItem.pk));
        }
Exemple #29
0
        private async Task RunHappyPathTestAsync(LabResponse labResponse, string federationMetadata = "")
        {
            var factory          = new HttpSnifferClientFactory();
            var msalPublicClient = PublicClientApplicationBuilder
                                   .Create(labResponse.App.AppId)
                                   .WithTestLogging()
                                   .WithHttpClientFactory(factory)
                                   .WithAuthority(labResponse.Lab.Authority, "organizations")
                                   .Build();

            AuthenticationResult authResult
                = await GetAuthenticationResultWithAssertAsync(
                      labResponse,
                      factory,
                      msalPublicClient,
                      federationMetadata,
                      CorrelationId).ConfigureAwait(false);

            if (AuthorityInfo.FromAuthorityUri(labResponse.Lab.Authority + "/" + labResponse.Lab.TenantId, false).AuthorityType == AuthorityType.Aad)
            {
                AssertTenantProfiles(authResult.Account.GetTenantProfiles(), authResult.TenantId);
            }
            else
            {
                Assert.IsNull(authResult.Account.GetTenantProfiles());
            }

            TestCommon.ValidateNoKerberosTicketFromAuthenticationResult(authResult);
            // If test fails with "user needs to consent to the application, do an interactive request" error,
            // Do the following:
            // 1) Add in code to pull the user's password before creating the SecureString, and put a breakpoint there.
            // string password = ((LabUser)user).GetPassword();
            // 2) Using the MSAL Desktop app, make sure the ClientId matches the one used in integration testing.
            // 3) Do the interactive sign-in with the MSAL Desktop app with the username and password from step 1.
            // 4) After successful log-in, remove the password line you added in with step 1, and run the integration test again.
        }
Exemple #30
0
        public void DiscardWriteRead()
        {
            engine = new FileHelperEngine(typeof(DiscardLastType1));

            DiscardLastType1[] res = (DiscardLastType1[])TestCommon.ReadTest(engine, @"Good\DiscardLast1.txt");
            engine.FooterText = "This is a new Footer....\r\n";

            engine.WriteFile("tempo.txt", res);

            engine.FooterText = "none none";

            DiscardLastType1[] res2 = (DiscardLastType1[])engine.ReadFile(@"tempo.txt");

            Assert.AreEqual(res.Length, res2.Length);
            Assert.AreEqual("This is a new Footer....\r\n", engine.FooterText);

            if (File.Exists("tempo.txt"))
            {
                File.Delete("tempo.txt");
            }

            Assert.AreEqual(4, res.Length);
            Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
        }
Exemple #31
0
        private void CoreRunAsync(params string[] pathElements)
        {
            var arr = new ArrayList();

            TestCommon.BeginReadTest(asyncEngine, pathElements);

            foreach (object record in asyncEngine)
            {
                arr.Add(record);
            }

            var res = (CustomersVerticalBar[])arr.ToArray(typeof(CustomersVerticalBar));

            ExpectedRecords.AssertEqualTo <int>(res.Length, "Length is not equal");
            ExpectedRecords.AssertEqualTo <int>(asyncEngine.TotalRecords, "Total number of records not equal");

            expectedTextWithNTilde.AssertEqualTo <String>(res[1].CompanyName);
            expectedTextWithEGrave.AssertEqualTo <String>(res[6].CompanyName);
            expectedTextWithEAcute1.AssertEqualTo <String>(res[6].ContactName);

            expectedTextWithEAcute2.AssertEqualTo <String>(res[6].Address);
            expectedTextWithADiaeresis.AssertEqualTo <String>(res[4].Address);
            expectedTextWithARing.AssertEqualTo <String>(res[4].City);
        }