示例#1
0
        private void UploadDatabaseBackupScript(GoogleDriveManager googleDriveManager)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["Gallery"].ToString();
            var server           = new Server(new ServerConnection(new SqlConnection(connectionString)));
            var database         = server.Databases[new SqlConnectionStringBuilder(connectionString).InitialCatalog];
            var options          = new ScriptingOptions
            {
                ScriptData     = true,
                ScriptSchema   = true,
                ScriptDrops    = false,
                Indexes        = true,
                IncludeHeaders = true
            };

            byte[] bytes = null;
            using (var ms = new MemoryStream())
            {
                TextWriter tw = new StreamWriter(ms);

                foreach (Table table in database.Tables)
                {
                    foreach (var statement in table.EnumScript(options))
                    {
                        tw.WriteLine(statement);
                    }
                }

                tw.Flush();
                ms.Position = 0;
                bytes       = ms.ToArray();
            }

            googleDriveManager.Upload($"#Backup#{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.sql", bytes);
        }
示例#2
0
        public void Execute(IJobExecutionContext context)
        {
            using (var db = new GalleryContext())
            {
                var numberOfPicturesToUpload = Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfPicturesToUpload"].ToString());
                var pictureToProcessList     = db.Picture.Where(x => !x.IsBackupCopySaved).OrderBy(x => x.CreationDate).Take(numberOfPicturesToUpload).ToList();
                if (pictureToProcessList.Count == 0)
                {
                    return;
                }

                var googleDriveManager = new GoogleDriveManager();

                foreach (var pictureToProcess in pictureToProcessList)
                {
                    var regex           = new Regex($"^{pictureToProcess.id}[.-]");
                    var picturePathList = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Picture"))
                                          .Where(x => regex.IsMatch(Path.GetFileName(x)))
                                          .ToList();

                    picturePathList.ForEach(x => googleDriveManager.Upload(x));
                    pictureToProcess.IsBackupCopySaved = true;
                    db.SaveChanges();
                }

                UploadDatabaseBackupScript(googleDriveManager);
            }
        }
示例#3
0
        public ActionResult Create(News news)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string new_image = Url.Content("/images/default-news-img.png");
                    for (int i = 0; i < Request.Form.Files.Count; i++)
                    {
                        var image = Request.Form.Files[i];
                        if (image != null && image.ContentType.Contains("image/"))
                        {
                            string fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(image.FileName);

                            GoogleDriveManager driveClient = new GoogleDriveManager(hosting);

                            new_image = driveClient.DriveUploadAndGetSrc(image, DRIVE_FOLDER_NAME);
                        }
                    }
                    news.Images = new_image;

                    newsManager.AddNews(news);
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    return(View());
                }
            }
            return(View());
        }
        /// <summary>
        /// Synchronize files with Google Drive
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CmdDriveUpload_Click(object sender, EventArgs e)
        {
            // Change label to display that the upload is in progress
            lblDriveLastUploaded.Text = @"Upload in progres...";

            var filesList = new List <string>();

            foreach (var fileItem in checkedListDownloadUploadFiles.CheckedItems)
            {
                filesList.Add(Path.Combine(_settingsManager.Settings.ResourceFolderPath, fileItem.ToString().ToLower() + ".json"));
            }

            var driveManager = new GoogleDriveManager();

            for (var i = 0; i < filesList.Count; i++)
            {
                // Update label
                lblDriveLastUploaded.Text = @"Upload in progress... (" + (i + 1) + @"/" + filesList.Count + @")";

                Google.Apis.Drive.v3.Data.File responseFile;

                // save response file id to settings to find the file later
                switch (i)
                {
                case 0:
                    responseFile = await driveManager.UploadFile(filesList[i], ResourceType.Vacancies);

                    _settingsManager.SetGoogleDriveVacanciesFileId(responseFile.Id);
                    break;

                case 1:
                    responseFile = await driveManager.UploadFile(filesList[i], ResourceType.Blacklist);

                    _settingsManager.SetGoogleDriveBlacklistFileId(responseFile.Id);
                    break;

                case 2:
                    responseFile = await driveManager.UploadFile(filesList[i], ResourceType.Done);

                    _settingsManager.SetGoogleDriveDoneFileId(responseFile.Id);
                    break;

                case 3:
                    responseFile = await driveManager.UploadFile(filesList[i], ResourceType.Companies);

                    _settingsManager.SetGoogleDriveCompaniesFileId(responseFile.Id);
                    break;

                default:
                    break;
                }
            }

            _settingsManager.SetLastDriveUpload(DateTime.Now);
            UpdateLastDriveUploadLabel();
        }
示例#5
0
        public ActionResult Edit(News news)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string new_image = Url.Content("/images/default-news-img.png");
                    // EDIT EXISTING IMAGE
                    string existingImages = managerForImages.FindNewsById(news.Id).Images;
                    if (!String.IsNullOrEmpty(existingImages))
                    {
                        string[] images = existingImages.Split('|');
                        foreach (string field in Request.Form.Keys)
                        {
                            if (field.Contains("check_"))
                            {
                                var    checkbox = Request.Form[field];
                                string src      = field.Split('_')[1];
                                if (checkbox == "false")
                                {
                                    GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                                    driveClient.DriveMoveFileToTrash(src);
                                }
                                else
                                {
                                    new_image = src;
                                }
                            }
                        }
                    }

                    // UPLOADING NEW IMAGE
                    for (int i = 0; i < Request.Form.Files.Count; i++)
                    {
                        var image = Request.Form.Files[i];
                        if (image != null && image.ContentType.Contains("image/"))
                        {
                            string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(image.FileName);

                            GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                            new_image = driveClient.DriveUploadAndGetSrc(image, DRIVE_FOLDER_NAME);
                        }
                    }
                    news.Images = new_image;

                    newsManager.EditNews(news);
                    return(Redirect("/News/Details/" + news.Id));
                }
                catch
                {
                    return(View());
                }
            }
            return(View());
        }
        /// <summary>
        /// Download files from Google Drive and replace them locally
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CmdDownload_Click(object sender, EventArgs e)
        {
            // Warn user about overwriting files
            var dialogResult = MessageBox.Show(@"Are you sure? This will overwrite all your local resource files. It is irreversible.", @"Confirm overwrite",
                                               MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (dialogResult == DialogResult.Cancel)
            {
                return;
            }

            // Change label to display that the download is in progress
            lblDriveLastDownloaded.Text = @"Download in progres...";

            var driveManager = new GoogleDriveManager();

            var cnt = 1;

            foreach (var checkedItem in checkedListDownloadUploadFiles.CheckedItems)
            {
                // Update label
                lblDriveLastDownloaded.Text = @"Download in progress... (" + cnt++ + @"/" +
                                              checkedListDownloadUploadFiles.CheckedItems.Count + @")";

                switch (checkedItem.ToString())
                {
                case "Vacancies":
                    await driveManager.DownloadAndReplaceFile(ResourceType.Vacancies);

                    break;

                case "Blacklist":
                    await driveManager.DownloadAndReplaceFile(ResourceType.Blacklist);

                    break;

                case "Done":
                    await driveManager.DownloadAndReplaceFile(ResourceType.Done);

                    break;

                case "Companies":
                    await driveManager.DownloadAndReplaceFile(ResourceType.Companies);

                    break;

                default:
                    break;
                }
            }

            _settingsManager.SetLastDriveDownload(DateTime.Now);
            UpdateLastDriveDownloadLabel();
        }
        /// <summary>
        /// The constructor of the class
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            LoadTabContent();

            Text = @"Vacancy Scraper by Johannes Mols [v0.9.1]";

            var driveManager = new GoogleDriveManager();

            driveManager.UploadAllFiles();
        }
示例#8
0
        public ActionResult Edit(Partner pm)
        {
            if (ModelState.IsValid)
            {
                var file = Request.Form.Files["downl"];
                if (file != null && file.ContentType.Contains("image/"))
                {
                    string fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);

                    GoogleDriveManager driveClient = new GoogleDriveManager(hosting);

                    pm.Image = driveClient.DriveUploadAndGetSrc(file, DRIVE_FOLDER_NAME);
                }
                pmManager.Edit(pm);
                return(Redirect("/Partners"));
            }
            else
            {
                return(View());
            }
        }
示例#9
0
 public ActionResult Delete(int?id)
 {
     if (id != null)
     {
         Event e = eventsManager.FindEventById(id);
         if (e != null)
         {
             string[] images = e.Images.Split('|');
             foreach (string src in images)
             {
                 if (src.Contains("default"))    //don't delete default image
                 {
                     continue;
                 }
                 GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                 driveClient.DriveMoveFileToTrash(src);
             }
             eventsManager.RemoveEventById(id);
         }
     }
     return(RedirectToAction("Index"));
 }
示例#10
0
        public ActionResult Edit(Service svc)
        {
            if (ModelState.IsValid)
            {
                string file_name = Request.Form["file_name"];
                string link      = Request.Form["link"];
                var    file      = Request.Form.Files["download"];
                if (file != null && file.Length > 0)
                {
                    GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                    link = driveClient.DriveUploadAndGetSrc(file, DRIVE_FOLDER_FILES);
                }
                svc.File = file_name + "|" + link;

                svcManager.EditService(svc);
                return(Redirect("/Services/Details/" + svc.Id));
            }
            else
            {
                return(View());
            }
        }
示例#11
0
        /// <summary>
        /// Singleton 응용 프로그램 개체를 초기화합니다.  이것은 실행되는 작성 코드의 첫 번째
        /// 줄이며 따라서 main() 또는 WinMain()과 논리적으로 동일합니다.
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;



            /*** Injecting objects to public static instances ***/

            // App
            MobileService = new MobileServiceClient(
                "https://pinthecloud.azure-mobile.net/",
                "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23"
                );
            ApplicationSessions = new WSApplicationSessions();
            ApplicationSettings = new WSApplicationSettings();

            // Manager
            SpotManager         = new SpotManager();
            Geolocator          = new Geolocator();
            BlobStorageManager  = new BlobStorageManager();
            LocalStorageManager = new LocalStorageManager();

            OneDriveManager   = new OneDriveManager();
            DropBoxManager    = new DropboxManager();
            GoogleDriveManger = new GoogleDriveManager();


            /////////////////////////////////////////////////////
            // This order will be displayed at every App Pages
            /////////////////////////////////////////////////////
            StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager);
            StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager);
            StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger);
            Switcher.SetStorageToMainPlatform();
            AccountManager = new AccountManager();
        }
示例#12
0
        public ActionResult Create(Models.Event e)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string new_image = Url.Content("/images/default-event-img.png");
                    var    image     = Request.Form.Files["Images"];
                    if (image != null && image.ContentType.Contains("image/"))
                    {
                        string             fileName    = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(image.FileName);
                        GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                        new_image = driveClient.DriveUploadAndGetSrc(image, DRIVE_FOLDER_IMAGES);
                    }
                    e.Images = new_image;

                    string file_name = Request.Form["file_name"];
                    string link      = Request.Form["link"];
                    var    file      = Request.Form.Files["download"];
                    if (file != null && file.Length > 0)
                    {
                        GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                        link = driveClient.DriveUploadAndGetSrc(file, DRIVE_FOLDER_FILES);
                    }
                    e.Files = file_name + "|" + link;

                    eventsManager.AddEvent(e);
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    return(View());
                }
            }
            return(View());
        }
示例#13
0
        public ActionResult Edit(Models.Event e)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string new_image = Url.Content("/images/default-event-img.png");
                    // EDIT EXISTING IMAGES
                    string existingImages = managerForImages.FindEventById(e.Id).Images;
                    if (!String.IsNullOrEmpty(existingImages))
                    {
                        string[] images = existingImages.Split('|');
                        foreach (string field in Request.Form.Keys)
                        {
                            if (field.Contains("check_"))
                            {
                                var    checkbox = Request.Form[field];
                                string src      = field.Split('_')[1];
                                if (checkbox == "false" && !src.Contains("default"))
                                {
                                    GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                                    driveClient.DriveMoveFileToTrash(src);
                                }
                                else
                                {
                                    new_image = src;
                                }
                            }
                        }
                    }

                    // UPLOADING NEW IMAGES
                    for (int i = 0; i < Request.Form.Files.Count; i++)
                    {
                        var image = Request.Form.Files[i];
                        if (image != null && image.ContentType.Contains("image/"))
                        {
                            string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(image.FileName);

                            GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                            new_image = driveClient.DriveUploadAndGetSrc(image, DRIVE_FOLDER_IMAGES);
                        }
                    }
                    e.Images = new_image;

                    // Зарузка и формирование файла
                    string file_name = Request.Form["file_name"];
                    string link      = Request.Form["link"];
                    var    file      = Request.Form.Files["download"];
                    if (file != null && file.Length > 0)
                    {
                        GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                        link = driveClient.DriveUploadAndGetSrc(file, DRIVE_FOLDER_FILES);
                    }
                    e.Files = file_name + "|" + link;

                    eventsManager.EditEvent(e);
                    return(Redirect("/Events/Details/" + e.Id));
                }
                catch
                {
                    return(View());
                }
            }
            return(View());
        }
示例#14
0
        public void TestInit1()
        {
            //App.MobileService = new MobileServiceClient(
            //    "https://pinthecloud.azure-mobile.net/",
            //    "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23"
            //);
            App.ApplicationSessions = new WSApplicationSessions();
            App.ApplicationSettings = new WSApplicationSettings();

            // Manager
            App.SpotManager         = new SpotManager();
            App.Geolocator          = new Geolocator();
            App.BlobStorageManager  = new BlobStorageManager();
            App.LocalStorageManager = new LocalStorageManager();

            IStorageManager OneDriveManager   = new OneDriveManager();
            IStorageManager DropBoxManager    = new DropboxManager();
            IStorageManager GoogleDriveManger = new GoogleDriveManager();


            /////////////////////////////////////////////////////
            // This order will be displayed at every App Pages
            /////////////////////////////////////////////////////
            StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager);
            StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager);
            StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger);
            Switcher.SetStorageToMainPlatform();
            App.AccountManager = new AccountManager();


            if (!App.ApplicationSettings.Contains(Switcher.MAIN_PLATFORM_TYPE_KEY))
            {
                App.ApplicationSettings[Switcher.MAIN_PLATFORM_TYPE_KEY] = AppResources.OneDrive;
            }

            // Check nick name at frist login.
            if (!App.ApplicationSettings.Contains(StorageAccount.ACCOUNT_DEFAULT_SPOT_NAME_KEY))
            {
                App.ApplicationSettings[StorageAccount.ACCOUNT_DEFAULT_SPOT_NAME_KEY] = AppResources.AtHere;
            }

            // Check location access consent at frist login.
            if (!App.ApplicationSettings.Contains(StorageAccount.LOCATION_ACCESS_CONSENT_KEY))
            {
                App.ApplicationSettings[StorageAccount.LOCATION_ACCESS_CONSENT_KEY] = false;
            }


            // Do Signin work of each cloud storage.
            if (App.AccountManager.IsSignIn())
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    TaskHelper.AddTask(App.AccountManager.GetPtcId(), App.AccountManager.SignIn());
                    using (var itr = StorageHelper.GetStorageEnumerator())
                    {
                        while (itr.MoveNext())
                        {
                            if (itr.Current.IsSignIn())
                            {
                                TaskHelper.AddSignInTask(itr.Current.GetStorageName(), itr.Current.SignIn());
                            }
                        }
                    }
                }
            }
        }
示例#15
0
        static void Main(string[] args)
        {
            // ************************************************************
            // ASSUMPTION: Unit test has been run on Google Drive first
            // ************************************************************

            var googleDriveManager = new GoogleDriveManager();
            var googleSheetManager = new GoogleSheetManager();

            GoogleCredential credentialReadOnly   = null;
            GoogleCredential credentialFullAccess = null;

            DriveService driveServiceReadOnly   = null;
            DriveService driveServiceFullAccess = null;

            SheetsService sheetsServiceReadOnly   = null;
            SheetsService sheetsServiceFullAccess = null;

            #region STEP 0: Pre-test validation

            if (System.IO.File.Exists("client-secret.json") == false)
            {
                Console.WriteLine("******* ERROR: Please ensure you have downloaded your Google API .JSON file and copied into same folder as the .EXE *******");
                Console.ReadKey();
                return;
            }

            // Get the readonly drive credentials. (If it fails here run UnitTestGoogleDriveViaConsole to troubleshoot)
            credentialReadOnly = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.ReadOnlyScope);
            if (credentialReadOnly == null)
            {
                Console.WriteLine("******* PRE-TEST VALIDATION FAILED - Credentials returned null when getting Read Only Scope permissions");
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // Get the full access drive credentials. (If it fails here run UnitTestGoogleDriveViaConsole to troubleshoot)
            credentialFullAccess = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.FullAccessScope);
            if (credentialFullAccess == null)
            {
                Console.WriteLine("******* PRE-TEST VALIDATION FAILED - Credentials returned null when getting Full Access Scope permissions");
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // Get Drive Service Instance as Read-Only
            driveServiceReadOnly = googleDriveManager.CreateDriveServiceInstance(credentialReadOnly, "UnitTest Google Sheet Library");
            if (driveServiceReadOnly == null)
            {
                Console.WriteLine("******* STEP 2.2.1 - FAILED - drive service returned null getting it with Read Only credentials. ");
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // Get Drive Service Instance as Full Access
            driveServiceFullAccess = googleDriveManager.CreateDriveServiceInstance(credentialFullAccess, "UnitTest Google Sheet Library");
            if (driveServiceFullAccess == null)
            {
                Console.WriteLine("******* STEP 2.2.2 - FAILED - drive service returned null getting it with Full Access credentials. ");
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            var t1Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T1");
            if (t1Folder == null)
            {
                Console.WriteLine("******* ERROR: T1 folder should already exist. Please ensure you ran UnitTestGoogleDriveViaConsole first. *******");
                Console.ReadKey();
                return;
            }

            // Check if sheet exists and so delete it
            var sheetFile = googleDriveManager.GetSheetFileInChildFolderByName(driveServiceReadOnly, "TestSheet", t1Folder.Id);
            if (sheetFile != null)
            {
                googleDriveManager.DeleteFile(driveServiceFullAccess, sheetFile.Id);
            }

            #endregion

            #region STEP 1: Create the test sheet

            #region STEP 1.1: Negative Testing

            // STEP 1.1.1 - Test no drive service
            try { var expectedFailure = googleDriveManager.CreateGoogleSheet(null, string.Empty, string.Empty, null); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 1.1.1 - PASSED : EXPECTED FAILURE with no drive service passed: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 3.1.2 - Test drive service, no sheet name
            try { var expectedFailure = googleDriveManager.CreateGoogleSheet(driveServiceFullAccess, string.Empty, string.Empty, new List <string> {
                    t1Folder.Id
                }); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with drive service but no sheet name: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 1.2 Positive Testing

            var sheetFileId = googleDriveManager.CreateGoogleSheet(driveServiceFullAccess, "TestSheet", "Sheet used to Unit test CSHARP Sheet Library.", new List <string> {
                t1Folder.Id
            });
            if (string.IsNullOrEmpty(sheetFileId))
            {
                Console.WriteLine("******* ERROR: Failed to create test sheet *******");
                Console.ReadKey();
                return;
            }

            #endregion

            #endregion

            #region STEP 2: Assign Read Permissions to [email protected]

            // Get the permission object so we can use it to assign permission to the sheet
            var permission = googleDriveManager.CreateUserPermission("reader", "*****@*****.**");
            if (permission == null)
            {
                Console.WriteLine("******* ERROR: Failed to create user permission object for [email protected] *******");
                Console.ReadKey();
                return;
            }

            // Assign the permission to the sheet
            if (googleDriveManager.AssignPermissionToFile(driveServiceFullAccess, sheetFileId, permission) == false)
            {
                Console.WriteLine("******* ERROR: Failed to set reader permission for user [email protected] for spreadsheet *******");
                Console.ReadKey();
                return;
            }

            // Get the permission object so we can use it to assign permission to the sheet
            permission = googleDriveManager.CreateUserPermission("writer", "*****@*****.**");
            if (permission == null)
            {
                Console.WriteLine("******* ERROR: Failed to create user permission object for [email protected] *******");
                Console.ReadKey();
                return;
            }

            // Assign the permission to the sheet
            if (googleDriveManager.AssignPermissionToFile(driveServiceFullAccess, sheetFileId, permission) == false)
            {
                Console.WriteLine("******* ERROR: Failed to set write permission for user [email protected] for spreadsheet *******");
                Console.ReadKey();
                return;
            }

            #endregion

            #region STEP 3: Get Sheets Service Instance

            #region STEP 3.1: Negative Testing

            // STEP 3.1.1 - Test no credentials passed in and no application name
            try { var expectedFailure = googleSheetManager.CreateSheetServiceInstance(null, string.Empty); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.1 - PASSED : EXPECTED FAILURE with no credentials passed: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 2.1.2 - Test credentials passed in but no application name
            try { var expectedFailure = googleSheetManager.CreateSheetServiceInstance(credentialReadOnly, string.Empty); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with no application name passed: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 3.2: Positive Testing

            // STEP 3.2.1 - Test getting sheet service with ReadOnly Scope
            try
            {
                sheetsServiceReadOnly = googleSheetManager.CreateSheetServiceInstance(credentialReadOnly, "UnitTest Google Sheet Library");
                if (sheetsServiceReadOnly == null)
                {
                    Console.WriteLine("******* STEP 3.2.1 - FAILED - sheets service returned null getting it with Read Only credentials. ");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.2.1 - FAILED - Exception thrown getting sheets service using Read Only credentials.");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // STEP 3.2.2 - Test getting sheet service with Full Access Scope
            try
            {
                sheetsServiceFullAccess = googleSheetManager.CreateSheetServiceInstance(credentialFullAccess, "UnitTest Google Sheet Library");
                if (sheetsServiceFullAccess == null)
                {
                    Console.WriteLine("******* STEP 3.2.2 - FAILED - sheets service returned null getting it with Full Access credentials. ");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.2.2 - FAILED - Exception thrown getting sheets service using Full Access credentials.");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("******* STEP 3.2 - PASSED");
            Console.WriteLine("*******");
            Console.ReadKey();

            #endregion

            #endregion

            #region STEP 4: Read and Write Values from test sheet

            #region STEP 4.1 - Read range (should be blank)

            var testRange    = "Sheet1!A2:E2";
            var valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange);

            if (valueResults == null)
            {
                Console.WriteLine("******* ERROR: Failed to get range in sheet *******");
                Console.ReadKey();
                return;
            }

            // Review the cells are empty. The Values are stored in an array of arrays
            IList <IList <Object> > values = valueResults.Values;
            if (values == null || values.Count == 0)
            {
                Console.WriteLine("******* PASSED: Expected range in sheet to be empty as we just created it *******");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("******* ERROR: Failed as sheet range should have no data *******");
                Console.ReadKey();
                return;
            }

            #endregion

            #region STEP 4.2 - Write a single value and confirm it got written

            var singleCellTestRange = "Sheet1!A2";
            googleSheetManager.UpdateSheetCellValue(sheetsServiceFullAccess, sheetFileId, singleCellTestRange, "New Text In A2");
            var singleCellValueResult = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, singleCellTestRange);
            if (singleCellValueResult == null || singleCellValueResult.Values.Count == 0)
            {
                Console.WriteLine("******* ERROR: Failed to read back single cell value *******");
                Console.ReadKey();
                return;
            }

            if (singleCellValueResult.Values[0].Count == 0)
            {
                Console.WriteLine("******* ERROR: Failed to read back single cell value *******");
                Console.ReadKey();
                return;
            }

            if (singleCellValueResult.Values[0][0].ToString() != "New Text In A2")
            {
                Console.WriteLine("******* ERROR: Failed as single text value was not updated in the sheet *******");
                Console.ReadKey();
                return;
            }
            #endregion

            #region STEP 5: Bulk Write data to test sheet

            // Getting the range again as we did update a cell in the range.
            valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange);

            // Fill in values in the results
            for (int rowIndex = 0; rowIndex < valueResults.Values.Count; rowIndex++)
            {
                for (int colIndex = 0; colIndex < valueResults.Values[rowIndex].Count; colIndex++)
                {
                    valueResults.Values[rowIndex][colIndex] = rowIndex.ToString() + ":" + colIndex.ToString();
                }
            }

            // Write the values
            googleSheetManager.UpdateSheetDataRange(sheetsServiceFullAccess, sheetFileId, testRange, valueResults);

            // Getting the range again to confirm updates.
            valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange);

            // Check the expected values in the results
            for (int rowIndex = 0; rowIndex < valueResults.Values.Count; rowIndex++)
            {
                for (int colIndex = 0; colIndex < valueResults.Values[rowIndex].Count; colIndex++)
                {
                    if (valueResults.Values[rowIndex][colIndex].ToString() != rowIndex.ToString() + ":" + colIndex.ToString())
                    {
                        Console.WriteLine("******* ERROR: Failed as the value we expected to be updated was not: " + rowIndex.ToString() + ":" + colIndex.ToString() + " * ******");
                        Console.ReadKey();
                        return;
                    }
                }
            }

            #endregion

            #endregion
        }
示例#16
0
        static void Main(string[] args)
        {
            var googleDriveManager = new GoogleDriveManager();
            GoogleCredential credentialReadOnly     = null;
            GoogleCredential credentialFullAccess   = null;
            DriveService     driveServiceReadOnly   = null;
            DriveService     driveServiceFullAccess = null;

            // STEP 0: Pre-test validation
            if (System.IO.File.Exists("client-secret.json") == false)
            {
                Console.WriteLine("******* ERROR: Please ensure you have downloaded your Google API .JSON file and copied into same folder as the .EXE *******");
                Console.ReadKey();
                return;
            }

            #region STEP 1: Get the User Credentials

            #region STEP 1.1: Negative Testing

            // STEP 1.1.1 - Test no credentials file and no scope
            try { var expectedFailure = googleDriveManager.GetUserCredential(string.Empty, null); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 1.1.1 - PASSED : EXPECTED FAILURE with no credentials file: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 1.1.2 - Test credentials file supplied but no scope
            try { var expectedFailure = googleDriveManager.GetUserCredential("client-secret.json", null); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 1.1.2 - PASSED : EXPECTED FAILURE with no scope: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 1.2: Positive Testing

            // STEP 1.2.1 - Test getting credential with ReadOnly Scope
            try
            {
                credentialReadOnly = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.ReadOnlyScope);
                if (credentialReadOnly == null)
                {
                    Console.WriteLine("******* STEP 1.2.1 - FAILED - Credentials returned null when getting Read Only Scope permissions");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 1.2.1 - FAILED - Exception thrown getting credentials with Read Only Scope");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // STEP 1.2.1 - Test getting credential with Full Access Scope
            try
            {
                credentialFullAccess = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.FullAccessScope);
                if (credentialFullAccess == null)
                {
                    Console.WriteLine("******* STEP 1.2.2 - FAILED - Credentials returned null when getting Full Access Scope permissions");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 1.2.2 - FAILED - Exception thrown getting credentials with Full Access permissions");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("******* STEP 1.2 - PASSED - got both Read Only and Full Access Credentials");
            Console.WriteLine("*******");
            Console.ReadKey();

            #endregion

            #endregion

            #region STEP 2: Get Drive Service Instance

            #region STEP 2.1: Negative Testing

            // STEP 2.1.1 - Test no credentials passed in and no application name
            try { var expectedFailure = googleDriveManager.CreateDriveServiceInstance(null, string.Empty); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 2.1.1 - PASSED : EXPECTED FAILURE with no credentials passed: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 2.1.2 - Test credentials passed in but no application name
            try { var expectedFailure = googleDriveManager.CreateDriveServiceInstance(credentialReadOnly, string.Empty); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 2.1.2 - PASSED : EXPECTED FAILURE with no application name passed: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 2.2: Positive Testing

            // STEP 2.2.1 - Test getting drive service with ReadOnly Scope
            try
            {
                driveServiceReadOnly = googleDriveManager.CreateDriveServiceInstance(credentialReadOnly, "UnitTest Google Drive Library");
                if (driveServiceReadOnly == null)
                {
                    Console.WriteLine("******* STEP 2.2.1 - FAILED - drive service returned null getting it with Read Only credentials. ");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 2.2.1 - FAILED - Exception thrown getting drive service using Read Only credentials.");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            // STEP 2.2.2 - Test getting drive service with Full Access Scope
            try
            {
                driveServiceFullAccess = googleDriveManager.CreateDriveServiceInstance(credentialFullAccess, "UnitTest Google Drive Library");
                if (driveServiceFullAccess == null)
                {
                    Console.WriteLine("******* STEP 2.2.2 - FAILED - drive service returned null getting it with Full Access credentials. ");
                    Console.WriteLine("*******");
                    Console.ReadKey();
                    return;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 2.2.2 - FAILED - Exception thrown getting drive service using Full Access credentials.");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("******* STEP 2.2 - PASSED");
            Console.WriteLine("*******");
            Console.ReadKey();

            #endregion

            #endregion

            #region STEP 3: Testing Drive access at the Root Folder level

            IList <Google.Apis.Drive.v3.Data.File> folders = null;

            #region PRE-STEP: Ensure there are at least 11 folders in the root

            // check if T1 folder exists and if not create it
            var t1Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T1");
            if (t1Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T1")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T1 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // Confirm the create worked
            t1Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T1");
            if (t1Folder == null)
            {
                Console.WriteLine("******* ERROR: Cannot getting test folder T1 in the Root Folder *******");
                Console.ReadKey();
                return;
            }

            // check if T2 folder exists and if not create it
            var t2Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T2");
            if (t2Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T2")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T2 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T3 folder exists and if not create it
            var t3Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T3");
            if (t3Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T3")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T3 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T4 folder exists and if not create it
            var t4Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T4");
            if (t4Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T4")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T4 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T5 folder exists and if not create it
            var t5Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T5");
            if (t5Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T5")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T5 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T6 folder exists and if not create it
            var t6Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T6");
            if (t6Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T6")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T6 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T7 folder exists and if not create it
            var t7Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T7");
            if (t7Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T7")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T7 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T8 folder exists and if not create it
            var t8Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T8");
            if (t8Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T8")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T8 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T9 folder exists and if not create it
            var t9Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T9");
            if (t9Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T9")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T9 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T7 folder exists and if not create it
            var t10Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T10");
            if (t10Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T10")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T10 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T11 folder exists and if not create it
            var t11Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T11");
            if (t11Folder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T11")))
                {
                    Console.WriteLine("******* ERROR: Cannot create test folder T11 in the Root Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            #endregion

            #region STEP 3.1: Negative Testing

            // STEP 3.1.1 - Test no drive service, first page only
            try { var expectedFailure = googleDriveManager.GetFolderList(null, true); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.1 - PASSED : EXPECTED FAILURE with no drive service passed while asking for first page only: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 3.1.2 - Test no drive service, all pages
            try { var expectedFailure = googleDriveManager.GetFolderList(null, false); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with no drive service passed while asking for all pages: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 3.2: Positive Testing

            // STEP 3.2.1 - Test drive service, first page only
            folders = googleDriveManager.GetFolderList(driveServiceReadOnly, true);
            if (folders == null)
            {
                Console.WriteLine("******* ERROR: Cannot get the Root Folders (first page only) *******");
                Console.ReadKey();
                return;
            }
            foreach (var folder in folders)
            {
                Console.WriteLine(folder.Name);
            }

            // STEP 3.2.2 - Test drive service, all pages
            folders = googleDriveManager.GetFolderList(driveServiceReadOnly, false);
            if (folders == null)
            {
                Console.WriteLine("******* ERROR: Cannot get the Root Folders (all pages) *******");
                Console.ReadKey();
                return;
            }
            foreach (var folder in folders)
            {
                Console.WriteLine(folder.Name);
            }

            #endregion

            #endregion

            #region STEP 4: Test Delete and/or Create Child Folder

            // Check if "test" folder exists in the root if it exists delete and re-create it
            var testFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "Test");
            if (testFolder != null)
            {
                // Delete it and then we can recreate it for our test.
                // WARNING: When using DeleteFile it totally deletes it from the drive. It does NOT put it in trash.
                if (googleDriveManager.DeleteFile(driveServiceFullAccess, testFolder.Id) == false)
                {
                    Console.WriteLine("******* ERROR: Cannot delete the test folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // Create the test folder in the root
            var testFolderId = googleDriveManager.CreateFolder(driveServiceFullAccess, "Test");
            if (string.IsNullOrEmpty(testFolderId) == true)
            {
                Console.WriteLine("******* ERROR: Cannot create test folder *******");
                Console.ReadKey();
                return;
            }

            // Assign the test folder permissions for "readwatchcreate.com" domain
            var permission = googleDriveManager.CreateUserPermission("reader", "*****@*****.**");
            if (permission == null)
            {
                Console.WriteLine("******* ERROR: Could not create reader permission for 'readwatchcreate.com' domain *******");
                Console.ReadKey();
                return;
            }

            if (googleDriveManager.AssignPermissionToFile(driveServiceFullAccess, testFolderId, permission) == false)
            {
                Console.WriteLine("******* ERROR: Could not set reader permission for 'readwatchcreate.com' domain on test folder *******");
                Console.ReadKey();
                return;
            }

            #endregion

            #region STEP 5: Testing Drive access at the Child Folder level

            #region PRE-STEP: Ensure there are at least 11 child folders in the T1 folder

            // check if T1Child folder exists and if not create it
            var t1ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T1Child", testFolderId);
            if (t1ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T1Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T1Child in the Test Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T2Child folder exists and if not create it
            var t2ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T2Child", testFolderId);
            if (t2ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T2Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T2Child folder in the Test Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T3Child folder exists and if not create it
            var t3ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T3Child", testFolderId);
            if (t3ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T3Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T3Child folder in the T3 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T4Child folder exists and if not create it
            var t4ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T4Child", testFolderId);
            if (t4ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T4Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T4Child folder in the T4 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T5Child folder exists and if not create it
            var t5ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T5Child", testFolderId);
            if (t5ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T5Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T5Child folder in the T5 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T6Child folder exists and if not create it
            var t6ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T6Child", testFolderId);
            if (t6ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T6Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T6Child folder in the T6 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T7Child folder exists and if not create it
            var t7ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T7Child", testFolderId);
            if (t7ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T7Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T7Child folder in the T7 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T8Child folder exists and if not create it
            var t8ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T8Child", testFolderId);
            if (t8ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T8Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T8Child folder in the T8 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T9Child folder exists and if not create it
            var t9ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T9Child", testFolderId);
            if (t9ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T9Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T9Child folder in the T9 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T10Child folder exists and if not create it
            var t10ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T10Child", testFolderId);
            if (t10ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T10Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T10Child folder in the T10 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            // check if T11Child folder exists and if not create it
            var t11ChildFolder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T11Child", testFolderId);
            if (t11ChildFolder == null)
            {
                if (string.IsNullOrEmpty(googleDriveManager.CreateFolder(driveServiceFullAccess, "T11Child", new List <string> {
                    testFolderId
                })))
                {
                    Console.WriteLine("******* ERROR: Cannot create T11Child folder in the T11 Folder *******");
                    Console.ReadKey();
                    return;
                }
            }

            #endregion

            #region STEP 3.1: Negative Testing

            // STEP 3.1.1 - Test no drive service, first page only
            try { var expectedFailure = googleDriveManager.GetFileList(null, true); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.1 - PASSED : EXPECTED FAILURE with no drive service passed while asking for first page only: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            // STEP 3.1.2 - Test no drive service, all pages
            try { var expectedFailure = googleDriveManager.GetFolderList(null, false); }
            catch (Exception exception)
            {
                Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with no drive service passed while asking for all pages: ");
                Console.WriteLine(exception.ToString());
                Console.WriteLine("*******");
                Console.ReadKey();
            }

            #endregion

            #region STEP 3.2: Positive Testing

            // STEP 3.2.1 - Test drive service, first page only
            folders = googleDriveManager.GetFolderList(driveServiceReadOnly, true);
            if (folders == null)
            {
                Console.WriteLine("******* ERROR: Cannot get the Root Folders (first page only) *******");
                Console.ReadKey();
                return;
            }
            foreach (var folder in folders)
            {
                Console.WriteLine(folder.Name);
            }

            // STEP 3.2.2 - Test drive service, all pages
            folders = googleDriveManager.GetFolderList(driveServiceReadOnly, false);
            if (folders == null)
            {
                Console.WriteLine("******* ERROR: Cannot get the Root Folders (all pages) *******");
                Console.ReadKey();
                return;
            }
            foreach (var folder in folders)
            {
                Console.WriteLine(folder.Name);
            }

            #endregion

            #endregion
        }
示例#17
0
        public ActionResult Settings(User account)
        {
            AccountManager manager = new AccountManager(database);
            string         exSep   = "|";
            string         inSep   = "^";

            string[] files = new string[3];

            // Загрузка логотипа

            var logoImage = Request.Form.Files["downl-logo"];

            if (logoImage != null && logoImage.Length > 0 && logoImage.ContentType.Contains("image"))
            {
                GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                account.Logo = driveClient.DriveUploadAndGetSrc(logoImage, DRIVE_FOLDER_NAME);
            }

            // Загрузка изображения в раздел "О нас"
            var aboutImage = Request.Form.Files["downl-about"];

            if (aboutImage != null && aboutImage.Length > 0 && aboutImage.ContentType.Contains("image"))
            {
                GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                account.AboutImage = driveClient.DriveUploadAndGetSrc(aboutImage, DRIVE_FOLDER_NAME);
            }

            // Телефоны
            List <string> phonesList = new List <string>();

            foreach (string field in Request.Form.Keys)
            {
                if (field.Contains("Phone"))
                {
                    phonesList.Add(Request.Form[field]);
                }
            }
            account.Phones = string.Join("|", phonesList);

            // Загрузка файлов на главной странице
            for (int i = 0; i < Request.Form.Files.Count - 2; i++)
            {
                string title = Request.Form["title" + i.ToString()];
                string link  = Request.Form["link" + i.ToString()];
                var    file  = Request.Form.Files["downl" + i];
                if (file != null && file.Length > 0)
                {
                    GoogleDriveManager driveClient = new GoogleDriveManager(hosting);
                    link = driveClient.DriveUploadAndGetSrc(file, DRIVE_FOLDER_NAME);
                }
                if (title != null && title.Length > 0 || link != null && link.Length > 0)
                {
                    files[i] = title + inSep + link;
                }
                else
                {
                    files[i] = "";
                }
            }
            account.Files = string.Join(exSep, files);

            account.Id = 1; /*стоит здесь, пока юзер в бд один*/
            if (account.Password == null || account.Password == string.Empty)
            {
                account.Password = Request.Form["oldPass"];
            }

            if (ModelState.IsValid)
            {
                manager.EditAccount(account);
            }
            return(Redirect("/Account/Settings"));
        }