/// <summary>
        /// Add Organization Unit
        /// Documentation https://developers.google.com/directory/directory_v1/reference/orgunits/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customerId">Immutable ID of the G Suite account</param>
        /// <param name="body">A valid Directory directory_v1 body.</param>
        /// <returns>OrgUnitResponse</returns>
        public static OrgUnit Insert(DirectoryService service, string customerId, OrgUnit body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (customerId == null)
                {
                    throw new ArgumentNullException(customerId);
                }

                // Make the request.
                return(service.Orgunits.Insert(body, customerId).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Orgunits.Insert failed.", ex);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Create a service connection to google.
        /// </summary>
        /// <param name="userEmail">The API email to use for authentication.</param>
        /// <param name="gService">The type of service to connect to.</param>
        /// <returns>Returns an open connection to the google api service, or null.</returns>
        private static BaseClientService BuildService(string userEmail, GoogleServices gService = GoogleServices.Directory)
        {
            X509Certificate2 certificate = new X509Certificate2(Properties.Resources.gsd_api,"notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
                {
                    Scopes = Scopes,
                    User = userEmail
                }.FromCertificate(certificate));

            switch (gService)
            {
                case GoogleServices.Directory:
                    DirectoryService directoryService = new DirectoryService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return directoryService;
                case GoogleServices.Drive:
                    DriveService driveService = new DriveService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return driveService;
            }
            return null;
        }
        public void Test_Run_Ok_With_Explicit_Transaction()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            var v1_00_transactionDirectory = Directory.CreateDirectory(Path.Combine(_testConfiguration.WorkspacePath, "v1.00", RESERVED_DIRECTORY_NAME.TRANSACTION)).FullName;

            _testDataService.CreateScriptFile(Path.Combine(v1_00_transactionDirectory, $"test_v1_00.sql"), _testDataService.GetSqlForCreateDbObject(TEST_DBOBJECTS.DB_OBJECT_1));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            var v1_01_transactionDirectory = Directory.CreateDirectory(Path.Combine(_testConfiguration.WorkspacePath, "v0.01", RESERVED_DIRECTORY_NAME.TRANSACTION)).FullName;

            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.01"), $"test_v1_01.sql"), _testDataService.GetSqlForCreateDbObject(TEST_DBOBJECTS.DB_OBJECT_2));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            var v1_02_transactionDirectory = Directory.CreateDirectory(Path.Combine(_testConfiguration.WorkspacePath, "v0.02", RESERVED_DIRECTORY_NAME.TRANSACTION)).FullName;

            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.02"), $"test_v1_02.sql"), _testDataService.GetSqlForCreateDbObject(TEST_DBOBJECTS.DB_OBJECT_3));

            //act
            var configuration    = _testConfiguration.GetFreshConfiguration();
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, TEST_DBOBJECTS.DB_OBJECT_1).ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, TEST_DBOBJECTS.DB_OBJECT_2).ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, TEST_DBOBJECTS.DB_OBJECT_3).ShouldBeTrue();
        }
        public void Test_Run_Transaction_Mode_None()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"test_v1_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_00"));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.01"), $"test_v1_01.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_01"));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.02"), $"test_v1_02.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_02"));

            //act
            var configuration = _testConfiguration.GetFreshConfiguration();

            configuration.TransactionMode = TRANSACTION_MODE.NONE;
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_00").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_01").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_02").ShouldBeTrue();
        }
Esempio n. 5
0
        /// <summary>
        /// Lists the domain aliases of the customer.
        /// Documentation https://developers.google.com/directory/directory_v1/reference/domainAliases/list
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customer">Immutable ID of the G Suite account.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DomainAliasesResponse</returns>
        public static DomainAliases List(DirectoryService service, string customer, DomainAliasesListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (customer == null)
                {
                    throw new ArgumentNullException(customer);
                }

                // Building the initial request.
                var request = service.DomainAliases.List(customer);

                // Applying optional parameters to the request.
                request = (DomainAliasesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request DomainAliases.List failed.", ex);
            }
        }
Esempio n. 6
0
        public async Task <int> CreateGroupAsync(IEnumerable <Models.Group> groups)
        {
            int countCreatadGroups = 0;

            // Create Directory API service.
            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName       = "GSuiteGroups"
            });

            var requestGroupsList = service.Groups.List();

            requestGroupsList.Customer = "my_customer";
            var existingGroup = await Task.Run(() => requestGroupsList.Execute().GroupsValue);

            foreach (var item in groups)
            {
                if (existingGroup.Count(x => x.Email.ToLower() == item.Name.ToLower()) == 0)
                {
                    var request = service.Groups.Insert(new Google.Apis.Admin.Directory.directory_v1.Data.Group()
                    {
                        Name = item.Name, Email = item.Name
                    });
                    await Task.Run(() => request.Execute());

                    countCreatadGroups++;
                }
            }

            // Get existing groups in GSuite
            _existGroups = await Task.Run(() => requestGroupsList.Execute().GroupsValue);

            return(countCreatadGroups);
        }
Esempio n. 7
0
        /// <summary>
        /// Inserts a Domain alias of the customer.
        /// Documentation https://developers.google.com/directory/directory_v1/reference/domainAliases/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customer">Immutable ID of the G Suite account.</param>
        /// <param name="body">A valid Directory directory_v1 body.</param>
        /// <returns>DomainAliasResponse</returns>
        public static DomainAlias Insert(DirectoryService service, string customer, DomainAlias body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (customer == null)
                {
                    throw new ArgumentNullException(customer);
                }

                // Make the request.
                return(service.DomainAliases.Insert(body, customer).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request DomainAliases.Insert failed.", ex);
            }
        }
Esempio n. 8
0
        public void Test_Create_Multiline_Script_With_Terminator_Inside_Statements()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);

            string sqlFileName    = "Test_Single_Run_Single_Standard";
            string sqlObjectName1 = TEST_DBOBJECTS.DB_OBJECT_1;
            string sqlObjectName2 = TEST_DBOBJECTS.DB_OBJECT_2;
            string sqlObjectName3 = TEST_DBOBJECTS.DB_OBJECT_3;

            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"{sqlFileName}.sql"), _testDataService.GetSqlForMultilineWithTerminatorInsideStatements(sqlObjectName1, sqlObjectName2, sqlObjectName3));

            //act
            var configuration    = _testConfiguration.GetFreshConfiguration();
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{sqlObjectName1}").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{sqlObjectName2}").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{sqlObjectName3}").ShouldBeTrue();
        }
Esempio n. 9
0
        public void Test_Create_Multiline_Script_With_Error_Must_Rollback()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);

            string sqlFileName    = "Test_Single_Run_Failed_Script_Must_Rollback";
            string sqlObjectName1 = TEST_DBOBJECTS.DB_OBJECT_1;
            string sqlObjectName2 = TEST_DBOBJECTS.DB_OBJECT_2;

            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v0.00"), $"{sqlFileName}.sql"), _testDataService.GetSqlForMultilineWithError(sqlObjectName1, sqlObjectName2));

            //act
            try
            {
                var configuration    = _testConfiguration.GetFreshConfiguration();
                var migrationService = _migrationServiceFactory.Create(configuration.Platform);
                migrationService.Run();
            }
            catch (Exception ex)
            {
                //used try/catch this instead of Assert.ThrowsException because different vendors
                //throws different exception type and message content
                ex.Message.ShouldNotBeNullOrEmpty();
            }

            //assert
            _testDataService.GetCurrentDbVersion(_testConfiguration.ConnectionString).ShouldBeNull();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{sqlObjectName1}").ShouldBeFalse();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{sqlObjectName2}").ShouldBeFalse();
        }
        public void GetSubFolders_ShouldThrowDirectoryNotFoundException_WhenPathDoesntExist()
        {
            var imageFileBuilderMock = new Mock <IImageFileBuilder>();
            var service = new DirectoryService(imageFileBuilderMock.Object);

            Assert.Throws <DirectoryNotFoundException>(() => service.GetSubFolders(TestFolder + "randomString"));
        }
        public void Copy_ShouldCopyFolder_WithItsContent()
        {
            var imageFileBuilderMock     = new Mock <IImageFileBuilder>();
            var sourcePath               = TestFolder + "FB51D97B-5106-45EC-8EA6-A8ACE3EA7558\\";
            var destinationDirectoryPath = TestFolder + "E5C698D6-C470-412C-8F3E-703100AD2A79\\";
            var subFolder1               = "folder1\\";
            var subFolder2               = "folder2\\";
            var file1 = "testFile1.jpg";

            Directory.CreateDirectory(sourcePath);
            Directory.CreateDirectory(destinationDirectoryPath);
            Directory.CreateDirectory(sourcePath + subFolder1);
            Directory.CreateDirectory(sourcePath + subFolder2);

            var fileStream = File.Create(sourcePath + subFolder2 + file1);

            fileStream.Close();

            var service = new DirectoryService(imageFileBuilderMock.Object);

            service.Copy(sourcePath, destinationDirectoryPath);

            Assert.True(Directory.Exists(sourcePath + subFolder1) && Directory.Exists(destinationDirectoryPath + subFolder1) &&
                        File.Exists(sourcePath + subFolder2 + file1) && File.Exists(sourcePath + subFolder2 + file1));
        }
        public void GetSubFolders_ShouldThrowArgumentException_WhenPathIsEmpty()
        {
            var imageFileBuilderMock = new Mock <IImageFileBuilder>();
            var service = new DirectoryService(imageFileBuilderMock.Object);

            Assert.Throws <ArgumentException>(() => service.GetSubFolders(String.Empty));
        }
        public void ReadTopDirectoryReadsDirectory()
        {
            // Arrange
            var currentDirectory = new DirectoryInfo("./");
            var pattern          = $"*.{extension}";
            var filesInDir       = currentDirectory.EnumerateFiles(pattern).ToList();

            filesInDir.ForEach(file => file.Delete());

            var file1 = new FileInfo(Path.ChangeExtension(Path.GetRandomFileName(), extension));
            var file2 = new FileInfo(Path.ChangeExtension(Path.GetRandomFileName(), extension));

            File.WriteAllText(file1.FullName, content1);
            File.WriteAllText(file2.FullName, content2);
            var tested   = new DirectoryService(new FileService());
            var expected = new Dictionary <string, string>
            {
                { file1.Name, content1 },
                { file2.Name, content2 },
            };

            // Act

            var actual = tested.ReadTopDirectory(file1.Directory.FullName, pattern);

            // Assert

            Assert.Equal(expected, actual);

            // Cleanup
            file1.Delete();
            file2.Delete();
        }
        /// <summary>
        /// Updates a customer. This method supports patch semantics.
        /// Documentation https://developers.google.com/directory/directory_v1/reference/customers/patch
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customerKey">Id of the customer to be updated</param>
        /// <param name="body">A valid Directory directory_v1 body.</param>
        /// <returns>CustomerResponse</returns>
        public static Customer Patch(DirectoryService service, string customerKey, Customer body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (customerKey == null)
                {
                    throw new ArgumentNullException(customerKey);
                }

                // Make the request.
                return(service.Customers.Patch(body, customerKey).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Customers.Patch failed.", ex);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Retrieves a domain alias of the customer.
        /// Documentation https://developers.google.com/directory/directory_v1/reference/domainAliases/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customer">Immutable ID of the G Suite account.</param>
        /// <param name="domainAliasName">Name of domain alias to be retrieved.</param>
        /// <returns>DomainAliasResponse</returns>
        public static DomainAlias Get(DirectoryService service, string customer, string domainAliasName)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (customer == null)
                {
                    throw new ArgumentNullException(customer);
                }
                if (domainAliasName == null)
                {
                    throw new ArgumentNullException(domainAliasName);
                }

                // Make the request.
                return(service.DomainAliases.Get(customer, domainAliasName).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request DomainAliases.Get failed.", ex);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Reads the track information in all media files found in the folder specified by <paramref name="path"/>, including subfolders
        /// if specified.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="includeSubfolders">If <c>true</c>, include subfolders.</param>
        /// <param name="extensions">The extensions.</param>
        /// <returns>
        /// A list of <see cref="ITrackInfo"/>.
        /// </returns>
        public static IEnumerable <ITrackInfo> ReadTracksInfo(
            string path,
            bool includeSubfolders,
            string extensions = DefaultExtensions)
        {
            var results = new List <ITrackInfo>();

            if (includeSubfolders)
            {
                IEnumerable <string> folders = DirectoryService.SafeFolders(path);
                if (folders == null)
                {
                    return(results);
                }

                foreach (string folderName in folders)
                {
                    results.AddRange(ReadTracksInfo(folderName, true, extensions));
                }
            }

            return(results
                   .Concat(from ext in extensions.Split(',')
                           from file in Directory.EnumerateFiles(path, ext)
                           select ReadTrackInfo(file))
                   .OrderBy(x => x.FileName));
        }
        /// <summary>
        /// Retrieve Organization Unit
        /// Documentation https://developers.google.com/directory/directory_v1/reference/orgunits/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="customerId">Immutable ID of the G Suite account</param>
        /// <param name="orgUnitPath">Full path of the organization unit or its Id</param>
        /// <returns>OrgUnitResponse</returns>
        public static OrgUnit Get(DirectoryService service, string customerId, string orgUnitPath)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (customerId == null)
                {
                    throw new ArgumentNullException(customerId);
                }
                if (orgUnitPath == null)
                {
                    throw new ArgumentNullException(orgUnitPath);
                }

                // Make the request.
                return(service.Orgunits.Get(customerId, orgUnitPath).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Orgunits.Get failed.", ex);
            }
        }
        public void Test_Verify()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"test_v1_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_00"));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.01"), $"test_v1_01.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_01"));

            var configuration    = _testConfiguration.GetFreshConfiguration();
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.02"), $"test_v1_02.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_02"));

            //act
            configuration.IsVerifyOnly         = true;
            configuration.IsAutoCreateDatabase = false;
            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_00").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_01").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_02").ShouldBeFalse();
        }
        public void Test_Run_With_Parameterized_Tokens(string versionFolder, string scriptName)
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, versionFolder), $"{scriptName}.sql"), _testDataService.GetSqlForCreateDbObjectWithTokens($"{scriptName}"));

            //act
            List <KeyValuePair <string, string> > tokens = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Token1", "Token1Value"),
                new KeyValuePair <string, string>("Token2", "Token2Value"),
                new KeyValuePair <string, string>("Token3", "Token3Value"),
            };

            var configuration = _testConfiguration.GetFreshConfiguration();

            configuration.Tokens = tokens;
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, $"{scriptName}_Token1Value_Token2Value_Token3Value").ShouldBeTrue();
        }
        public void Test_Run_With_Faulty_Script_Throws_Error_Must_Rollback_All_Changes()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"test_v1_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_00"));
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $".sql"), _testDataService.GetSqlForCreateBulkTable("TestCsv"));
            File.Copy(Path.Combine(Path.Combine(Environment.CurrentDirectory, "Data"), "TestCsv.csv"), Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), "TestCsv.csv"));
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"test_v1_00_error.sql"), _testDataService.GetSqlForCreateDbObjectWithError($"test_v1_00_error"));

            //act
            try
            {
                var configuration    = _testConfiguration.GetFreshConfiguration();
                var migrationService = _migrationServiceFactory.Create(configuration.Platform);
                migrationService.Run();
            }
            catch (Exception ex)
            {
                //used try/catch this instead of Assert.ThrowsException because different vendors
                //throws different exception type and message content
                ex.Message.ShouldNotBeNullOrEmpty();
            }

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_00").ShouldBeFalse();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "TestCsv").ShouldBeFalse();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_00_error").ShouldBeFalse();
        }
        public void Test_Run_Without_AutocreateDB_Throws_Exception()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            //act and assert
            try
            {
                var configuration = _testConfiguration.GetFreshConfiguration();
                configuration.IsAutoCreateDatabase = false;

                var migrationService = _migrationServiceFactory.Create(configuration.Platform);
                migrationService.Run();
            }
            catch (Exception ex)
            {
                //used try/catch this instead of Assert.ThrowsException because different vendors
                //throws different exception type and message content
                ex.Message.ShouldNotBeNullOrEmpty();
            }
        }
        public void Test_Run_With_Target_Version_Skipped_Versions_Higher_Than_Target_Version()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.00"), $"test_v1_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_00"));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.01"), $"test_v1_01.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_01"));

            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v1.02"), $"test_v1_02.sql"), _testDataService.GetSqlForCreateDbObject($"test_v1_02"));

            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v2.00"), $"test_v2_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v2_00"));

            //act
            var configuration = _testConfiguration.GetFreshConfiguration();

            configuration.TargetVersion = "v1.01";
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_00").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_01").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_02").ShouldBeFalse();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v1_03").ShouldBeFalse();
        }
Esempio n. 23
0
        /// <summary>
        /// Retrieve Group Member
        /// Documentation https://developers.google.com/directory/directory_v1/reference/members/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="groupKey">Email or immutable Id of the group</param>
        /// <param name="memberKey">Email or immutable Id of the member</param>
        /// <returns>MemberResponse</returns>
        public static Member Get(DirectoryService service, string groupKey, string memberKey)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (groupKey == null)
                {
                    throw new ArgumentNullException(groupKey);
                }
                if (memberKey == null)
                {
                    throw new ArgumentNullException(memberKey);
                }

                // Make the request.
                return(service.Members.Get(groupKey, memberKey).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Members.Get failed.", ex);
            }
        }
Esempio n. 24
0
        private string ResetPassword()
        {
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                User   = AdminUser,
                Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser, DirectoryService.Scope.AdminDirectoryGroup }
            }.FromPrivateKey(PrivateKey));

            var cs = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GSuiteUpdatePassword"
            };

            var t = new DirectoryService(cs);

            var request = t.Users.Update(new User
            {
                Password = NewPassword
            }, UserEmail);

            var res = request.Execute();

            return("Success");
        }
        public void Test_Run_Dash_Character_In_Database_Name()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v0.00"), $"test_v0_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v0_00"));

            //use database name with dash
            var databaseName = "yuniqldb-raw-dev";

            _testConfiguration.ConnectionString = _testConfiguration.ConnectionString.Replace(_testConfiguration.DatabaseName, databaseName);
            _testConfiguration.DatabaseName     = databaseName;

            //act
            var configuration    = _testConfiguration.GetFreshConfiguration();
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v0_00").ShouldBeTrue();
        }
Esempio n. 26
0
        /// <summary>
        /// Retrieve all members in a group (paginated)
        /// Documentation https://developers.google.com/directory/directory_v1/reference/members/list
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Directory service.</param>
        /// <param name="groupKey">Email or immutable Id of the group</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>MembersResponse</returns>
        public static Members List(DirectoryService service, string groupKey, MembersListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (groupKey == null)
                {
                    throw new ArgumentNullException(groupKey);
                }

                // Building the initial request.
                var request = service.Members.List(groupKey);

                // Applying optional parameters to the request.
                request = (MembersResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Members.List failed.", ex);
            }
        }
        public void Test_Run_Fail_Migration_When_Version_With_Explicit_Transaction_Directory_Has_Files()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);

            var transactionDirectory = Directory.CreateDirectory(Path.Combine(_testConfiguration.WorkspacePath, "v0.00", RESERVED_DIRECTORY_NAME.TRANSACTION)).FullName;

            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v0.00"), $"test_v0_00.sql"), _testDataService.GetSqlForCreateDbObject(TEST_DBOBJECTS.DB_OBJECT_1));

            //act & assert
            try
            {
                var configuration    = _testConfiguration.GetFreshConfiguration();
                var migrationService = _migrationServiceFactory.Create(configuration.Platform);
                migrationService.Run();
            }
            catch (Exception ex)
            {
                //used try/catch this instead of Assert.ThrowsException because different vendors
                //throws different exception type and message content
                ex.Message.ShouldNotBeNullOrEmpty();
            }
        }
Esempio n. 28
0
        public void CopyImages_GivenValidsPaths_ReturnStatusSuccess()
        {
            //arrange
            DirectoryService service       = new DirectoryService("");
            string           fromDirectory = "fromDirectory";
            string           toDirectory   = "toDirectory";

            Directory.CreateDirectory(fromDirectory);
            Directory.CreateDirectory(toDirectory);
            string imgName = "img.jpg";
            string img     = Path.Combine(fromDirectory, imgName);

            using (FileStream fs = File.Create(img))
            {
                for (byte i = 0; i < 10; i++)
                {
                    fs.WriteByte(i);
                }
            }

            //act
            DirectoryStatus d = service.CopyImages(fromDirectory, toDirectory);

            //assert
            d.Should().Be(DirectoryStatus.Success);

            Directory.Delete(fromDirectory, true);
            Directory.Delete(toDirectory, true);
        }
        public void Test_Run_Draft_Always_Executed()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v0.00"), $"test_v0_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v0_00"));

            //act, run with _draft is empty at this point
            var configuration    = _testConfiguration.GetFreshConfiguration();
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_v0_00").ShouldBeTrue();

            //arrange
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.DRAFT), $"test_draft_01.sql"), _testDataService.GetSqlForCreateDbObject($"test_draft_01"));
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.DRAFT), $"test_draft_02.sql"), _testDataService.GetSqlForCreateDbObject($"test_draft_02"));

            //act - runs again with _draft holding two script files
            migrationService.Run();

            //assert
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_draft_01").ShouldBeTrue();
            _testDataService.CheckIfDbObjectExist(_testConfiguration.ConnectionString, "test_draft_02").ShouldBeTrue();
        }
        public void Test_Run_With_Missing_Directories_In_Workspace_Must_Throw_Exception()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            _testDataService.CreateScriptFile(Path.Combine(Path.Combine(_testConfiguration.WorkspacePath, "v0.00"), $"test_v0_00.sql"), _testDataService.GetSqlForCreateDbObject($"test_v0_00"));

            Directory.Delete(Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.INIT), true);
            Directory.Delete(Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.POST), true);

            //act
            var exception = Assert.ThrowsException <YuniqlMigrationException>(() =>
            {
                var configuration    = _testConfiguration.GetFreshConfiguration();
                var migrationService = _migrationServiceFactory.Create(configuration.Platform);
                migrationService.Run();
            });

            //assert
            exception.Message.Contains("At least one required yuniql directory/folder is missing in your workspace").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.INIT)} / Missing").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.PRE)} / Found").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, "v0.00*")} / Found").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.DRAFT)} / Found").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.POST)} / Missing").ShouldBeTrue();
            exception.Message.Contains($"{Path.Combine(_testConfiguration.WorkspacePath, RESERVED_DIRECTORY_NAME.ERASE)} / Found").ShouldBeTrue();

            _testDataService.CheckIfDbExist(_testConfiguration.ConnectionString).ShouldBeFalse();
        }
        public void Test_Run_Database_Already_Updated()
        {
            //arrange
            var directoryService = new DirectoryService();
            var fileService      = new FileService();
            var workspaceService = new WorkspaceService(_traceService, directoryService, fileService);

            workspaceService.Init(_testConfiguration.WorkspacePath);
            workspaceService.IncrementMajorVersion(_testConfiguration.WorkspacePath, null);
            workspaceService.IncrementMinorVersion(_testConfiguration.WorkspacePath, null);

            //act
            var configuration = _testConfiguration.GetFreshConfiguration();

            configuration.TargetVersion = "v1.01";
            var migrationService = _migrationServiceFactory.Create(configuration.Platform);

            migrationService.Run();

            var versions = _testDataService.GetAllDbVersions(_testConfiguration.ConnectionString);

            versions.Count.ShouldBe(3);
            versions[0].Version.ShouldBe("v0.00");
            versions[1].Version.ShouldBe("v1.00");
            versions[2].Version.ShouldBe("v1.01");

            migrationService.Run();
            migrationService.Run();

            versions.Count.ShouldBe(3);
            versions[0].Version.ShouldBe("v0.00");
            versions[1].Version.ShouldBe("v1.00");
            versions[2].Version.ShouldBe("v1.01");
        }
        public void TestMethod1()
        {
            var dirService = new DirectoryService();

            var dir =  dirService.CreateDhlWaybillFolder(new List<string> (){"张三","李四"});

            ResourceReleaser resourceReleaser = new ResourceReleaser();

            string fullPath = resourceReleaser.ReleaseCXTemplate(dir);
        }
 private void ServiceInstance(string accountId, string certPath)
 {
     var auth = new ServiceOAuth(accountId, certPath);
     DirectoryService = auth.DirectoryService();
     GroupSettingsService = auth.GroupSettingsService();
     LicensingService = auth.LicensingService();
     ReportsService = auth.ReportsService();
     CalendarService = auth.CalendarService();
     DriveService = auth.DriveService();
     AuditService = auth.AuditService();
     TasksService = auth.TasksService();
 }
Esempio n. 34
0
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Directory API service.
            var service = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Define parameters of request.
            UsersResource.ListRequest request = service.Users.List();
            request.Customer = "my_customer";
            request.MaxResults = 10;
            request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;

            // List users.
            IList<User> users = request.Execute().UsersValue;
            Console.WriteLine("Users:");
            if (users != null && users.Count > 0)
            {
                foreach (var userItem in users)
                {
                  Console.WriteLine("{0} ({1})", userItem.PrimaryEmail,
                      userItem.Name.FullName);
                }
            }
            else
            {
                Console.WriteLine("No users found.");
            }
            Console.Read();
        }
Esempio n. 35
0
        public void Validate()
        {
            const string serviceAccountEmail = "*****@*****.**";
            string serviceAccountCertPath = System.Web.HttpContext.Current.Server.MapPath("~/Assets/Gmail/lcps-admin-dir.p12");
            const string serviceAccountCertPassword = "******";
            const string userEmail = "*****@*****.**";

            var certificate = new X509Certificate2(serviceAccountCertPath,
                serviceAccountCertPassword,
                X509KeyStorageFlags.Exportable);
                ServiceAccountCredential credential = new ServiceAccountCredential(

               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
               Scopes = scopes,
               User = userEmail

               }.FromCertificate(certificate));

            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            });

            UsersResource.ListRequest request = service.Users.List();
            request.Customer = "my_customer";
            request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;

            // List users. UsersResource.ListRequest.Execute().UsersValue
            IList<User> users = request.Execute().UsersValue;

            if (users != null && users.Count > 0)
            {
                foreach (var userItem in users)
                {
                    string pe = userItem.PrimaryEmail;
                }
            }
            else
            {
                throw new Exception("No users");
            }
        }
Esempio n. 36
0
        // GET: Google/GoogleConnect
        public ActionResult Index()
        {
            string p = HttpContext.Server.MapPath("~/Assets/API-Project.p12");
            String serviceAccountEmail = "*****@*****.**";
            X509Certificate2 certificate = new X509Certificate2(p, "notasecret", X509KeyStorageFlags.Exportable);
            ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[]
                    {
                        DirectoryService.Scope.AdminDirectoryUser
                    },
                User = "******"
            }.FromCertificate(certificate));

            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "LCPS-MSE-01",
            });



            //service.Users.List().Domain = "k12lcps.org";
            var list = service.Users.List();
            var results = list.Execute();

            
            foreach (User u in results.UsersValue)
            {
                string n = u.Name.FullName;
                int x = 0;
                x++;
            }
            

            return View();


        }
        /// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static DirectoryService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            // There are a lot of scopes check here: https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
            string[] scopes = new string[] {
                    DirectoryService.Scope.AdminDirectoryGroup  ,  // Manage your Groups
                    DirectoryService.Scope.AdminDirectoryUser   // Manage users 
                    };

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                    , scopes
                                                                    , userName
                                                                    , CancellationToken.None
                                                                    , new FileDataStore("Daimto.AdminSDK.Auth.Store")).Result;



                DirectoryService service = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Directory API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }
 public DirectoryController(DirectoryService directoryService, LookupService lookupService)
 {
     _directoryService = directoryService;
     _lookupService = lookupService;
 }
        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        public static DirectoryService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            // There are a lot of scopes check here: https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
            string[] scopes = new string[] {
                    DirectoryService.Scope.AdminDirectoryGroup  ,  // Manage your Groups
                    DirectoryService.Scope.AdminDirectoryUser   // Manage users 
                    };

            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                // Create the service.
                DirectoryService service = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Directory API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }
        }
 public void TestMethod1()
 {
     var dirService = new DirectoryService();
     dirService.CreateDhlWaybillFolder(new List<string>() { "xxx", "xxddd" });
 }
 private void SimpleInstance(string clientId, string clientSecret)
 {
     var auth = new SimpleOAuth(clientId, clientSecret);
     DirectoryService = auth.DirectoryService();
     GroupSettingsService = auth.GroupSettingsService();
     LicensingService = auth.LicensingService();
 }
Esempio n. 42
0
        static void Main(string[] args)
        {
            bool show_help = false;
            string domain = "";
            string pathRazorTemplate = "";
            string pathSecretFile = "client_secret.json";
            string user = "";

            var p = new OptionSet() {
            { "d|domain=", "the domain where you'll change the signatures.",
              v => domain = v },
            { "t|template=",
                "the file path of the razor template that will used.",
              v => pathRazorTemplate = v },
            { "s|secret=", "the file with the secret from Google console.",
              v => pathSecretFile = v },
            { "u|user="******"an specific user to apply the signature.",
              v => user = v },
            { "a|all", "apply the signature to every user form the domain.",
              v => { if (v != null) user=""; } },
            { "h|help",  "show this message and exit",
              v => show_help = v != null },
            };

            List<string> extra;
            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("Error: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try --help for more information.");
                return;
            }

            if (show_help)
            {
                ShowHelp(p);
                return;
            }

            UserCredential credential = GetCredentials(pathSecretFile);

            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            IList<User> users = new List<User>();

            if (!string.IsNullOrWhiteSpace(user))
            {
                users.Add(service.Users.Get(user).Execute());
            }
            else
            {
                UsersResource.ListRequest request = service.Users.List();
                request.Domain = domain;
                request.Projection = UsersResource.ListRequest.ProjectionEnum.Full;
                users = request.Execute().UsersValue;
            }

            OAuth2Parameters parameter = new OAuth2Parameters()
            {
                AccessToken = credential.Token.AccessToken
            };

            var requestFactory = new GOAuth2RequestFactory("apps", ApplicationName, parameter);
            var serviceGmail = new GoogleMailSettingsService("revolute.academy", ApplicationName);
            serviceGmail.RequestFactory = requestFactory;

            Console.WriteLine("Users:");
            if (users != null)
            {
                foreach (var userItem in users)
                {
                    if (userItem.IsMailboxSetup.HasValue && userItem.IsMailboxSetup.Value)
                    {
                        var signature = Render.Execute(pathRazorTemplate, userItem);
                        var userName = GetUser(userItem.PrimaryEmail);
                        dynamic obj = userItem.Organizations;

                        serviceGmail.UpdateSignature(userName, signature);
                        Console.WriteLine("New signature for {0}", userName);
                    }
                }
            }
            else
            {
                Console.WriteLine("No users found.");
            }

            Console.WriteLine("Signatures updated");
        }