public void Execute_UnicodeCharacters()
        {
            var handler = new TestBodyMessageHnalder()
            {
                GZipEnabled    = false,
                ResponseObject = new MockResponse {
                    Id = 100, Name = @"مرحبا العالم"
                },
                ExpectedRequestObject = new MockRequest {
                    Name = @"مرحبا العالم! 您好,世界!"
                }
            };
            var initializer = new BaseClientService.Initializer()
            {
                GZipEnabled       = false,
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                handler.Serializer = service.Serializer;

                var request  = new TestClientServiceRequest(service, "GET", handler.ExpectedRequestObject);
                var response = request.Execute();
                Assert.That(handler.Calls, Is.EqualTo(1));
                // the returned response should contain ETag, check that the service add the right ETag property on
                // the response
                handler.ResponseObject.ETag = handler.ResponseETag;
                Assert.That(response, Is.EqualTo(handler.ResponseObject));
            }
        }
Exemplo n.º 2
0
        public static void Resolve()
        {
            RefreshSettings();

            UserCredential credential;

            using (var stream =
                       new FileStream(settings.AuthPath, FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

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

            ClassroomData.Service     = new ClassroomService(initializer);
            DriveHandler.driveService = new DriveService(initializer);
            ClassroomData.Update(settings.DefaultNotificatons);
        }
        private async Task<string> ResizeDisk()
        {
            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(ServiceAccountEmail)
               {
                   Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform }
               }.FromPrivateKey(PrivateKey));

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

            var t = new ComputeService(cs);

            var drr = new DisksResizeRequest
            {
                SizeGb = long.Parse(NewSize)
            };

            var request = t.Disks.Resize(drr, Project, Region + "-" + Zone, DiskName);

            var response = request.Execute();

            if (response.HttpErrorStatusCode != null)
            {
                var errorStr = new StringBuilder();
                foreach (var error in response.Error.Errors)
                    errorStr.AppendLine(error.Code + " - " + error.Message);
                return errorStr.ToString();
            }
            else return "Success";
        }
        public void ExecuteAsync_NoCallback_Test()
        {
            var handler     = new BatchMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer, "http://sample.com"))
            {
                var responses = new List <Tuple <MockResponse, RequestError, HttpResponseMessage> >();
                var batch     = new BatchRequest(service);
                var request1  = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });
                var request2 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"200\"",
                    Name = "Name1-1"
                });
                batch.Queue <MockResponse>(request1, null);
                batch.Queue <MockResponse>(request2, null);
                batch.ExecuteAsync().Wait();
            }
        }
        /// <summary>
        /// A subtest for testing async execute when an exception is thrown during sending the request, with or without
        /// back-off handler. If back-off handler is attached to the service's message handler, there are going to be
        /// several retries (up to 2 minutes).
        /// </summary>
        /// <param name="backOff">Indicates if back-off handler is attached to the service.</param>
        private void SubtestExecuteAsync_ThrowException(bool backOff)
        {
            var handler     = new MockMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            // by default back-off is used, so disable it in case backOff is false
            if (!backOff)
            {
                initializer.DefaultExponentialBackOffPolicy = BaseClientService.ExponentialBackOffPolicy.None;
            }

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var task    = request.ExecuteAsync();
                try
                {
                    var result = task.Result;
                    Assert.Fail("Exception should be thrown");
                }
                catch (AggregateException ex)
                {
                    Assert.That(ex.InnerException, Is.AssignableFrom(typeof(InvalidOperationMockException)));
                }

                // if back-off is enabled, we use 2 minutes maximum wait time for a request, so we should make lg(120)
                // + 1 calls
                int calls = backOff ? (int)Math.Ceiling(Math.Log(120, 2) + 1) : 1;
                Assert.That(handler.Calls, Is.EqualTo(calls));
            }
        }
Exemplo n.º 6
0
        //
        // GET: /oauth2callback
        public ActionResult OAuth2Callback(String code)
        {
            var provider = GetProvider();
            try
            {
                var state = provider.ProcessUserAuthorization(code, GetAuthorizationState());
                var initializer = new BaseClientService.Initializer()
                {
                    Authenticator = Utils.GetAuthenticatorFromState(state)
                };

                Oauth2Service userService = new Oauth2Service(initializer);
                String userId = userService.Userinfo.Get().Fetch().Id;

                Utils.StoreCredentials(userId, state);
                Session["userId"] = userId;

                BootstrapUser(new MirrorService(initializer), userId);
            }
            catch (ProtocolException)
            {
                // TODO(alainv): handle error.
            }
            return Redirect(Url.Action("Index", "Main"));
        }
        public async Task <IActionResult> GoogleAuthentication(string code)
        {
            var request = new AuthorizationCodeTokenRequest
            {
                Code         = code,
                ClientSecret = _googleAuthOptions.ClientSecret,
                ClientId     = _googleAuthOptions.ClientId,
                GrantType    = "authorization_code",
                RedirectUri  = "http://localhost:3000"
            };
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://www.googleapis.com/oauth2/v4/")
            };
            var tokenResponse = await request.ExecuteAsync(httpClient, "token", CancellationToken.None, SystemClock.Default);

            var credentials = GoogleCredential.FromAccessToken(tokenResponse.AccessToken);
            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials
            };
            var userInfoService = new Oauth2Service(initializer);
            var userInfo        = await userInfoService.Userinfo.Get().ExecuteAsync();

            await _usersService.CreateUserAsync(new UserCreationDto
            {
                Email    = userInfo.Email,
                Password = "******",  //TODO: Add password generator
                IsFromExternalService = true,
                Name = userInfo.Email
            });

            return(Ok());
        }
 internal static void AddGoogleServices(this IServiceCollection services,
     BaseClientService.Initializer googleInitializer)
 {
     services.AddSingleton(new SheetsService(googleInitializer));
     services.AddSingleton(new GmailService(googleInitializer));
     services.AddSingleton<GoogleSheetsService>();
 }
Exemplo n.º 9
0
        private DriveService CreateDriveService(GoogleCredentials googleCredentials)
        {
            var authorizationCodeFlowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = googleCredentials.ClientId,
                    ClientSecret = googleCredentials.ClientSecret
                }
            };
            var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(authorizationCodeFlowInitializer);
            var token = new TokenResponse {
                RefreshToken = googleCredentials.RefreshToken
            };
            var credentials = new UserCredential(googleAuthorizationCodeFlow, "user", token);

            var initializer = new BaseClientService.Initializer
            {
                ApplicationName       = "Emby",
                HttpClientInitializer = credentials
            };

            return(new DriveService(initializer)
            {
                HttpClient = { Timeout = TimeSpan.FromHours(1) }
            });
        }
Exemplo n.º 10
0
        private string AddUser()
        {
            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       = "GSuiteAddUser"
            };

            var t = new DirectoryService(cs);

            var request = t.Users.Insert(new User
            {
                PrimaryEmail = UserEmail,
                Password     = Password,
                Name         = new UserName {
                    GivenName = GivenName, FamilyName = FamilyName
                },
                Emails = new List <UserEmail> {
                    new UserEmail {
                        Primary = true, Address = SecondaryEmail
                    }
                }
            });

            var user = request.Execute();

            return(user.Id);
        }
Exemplo n.º 11
0
        private string CopyFile()
        {
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                User   = UserId,
                Scopes = new[] { DriveService.Scope.Drive }
            }.FromPrivateKey(PrivateKey));

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

            var t = new DriveService(cs);

            var request = t.Files.Copy(new Google.Apis.Drive.v3.Data.File()
            {
                Name    = Name,
                Parents = new List <string> {
                    ParentID
                }
            }, FileId);

            var prog = request.Execute();

            return("Success");
        }
        //
        // GET: /oauth2callback

        public ActionResult OAuth2Callback(String code)
        {
            var provider = GetProvider();

            try
            {
                var state       = provider.ProcessUserAuthorization(code, GetAuthorizationState());
                var initializer = new BaseClientService.Initializer()
                {
                    Authenticator = Utils.GetAuthenticatorFromState(state)
                };

                Oauth2Service userService = new Oauth2Service(initializer);
                String        userId      = userService.Userinfo.Get().Fetch().Id;

                Utils.StoreCredentials(userId, state);
                Session["userId"] = userId;

                BootstrapUser(new MirrorService(initializer), userId);
            }
            catch (ProtocolException)
            {
                // TODO(alainv): handle error.
            }
            return(Redirect(Url.Action("Index", "Main")));
        }
Exemplo n.º 13
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");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Send a request to the UserInfo API to retrieve the user's information.
        /// </summary>
        /// <param name="credentials">OAuth 2.0 credentials to authorize the request.</param>
        /// <returns>User's information.</returns>
        /// <exception cref="NoUserIdException">An error occurred.</exception>
        static Userinfo GetUserInfo(IAuthorizationState credentials)
        {
            // create base client service initializer
            BaseClientService.Initializer baseClientService = new BaseClientService.Initializer()
            {
                Authenticator = GetAuthenticatorFromState(credentials)
            };

            Oauth2Service userInfoService = new Oauth2Service(baseClientService);
            Userinfo      userInfo        = null;

            try
            {
                userInfo = userInfoService.Userinfo.Get().Fetch();
            }
            catch (GoogleApiRequestException e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }
            if (userInfo != null && !String.IsNullOrEmpty(userInfo.Id))
            {
                return(userInfo);
            }
            else
            {
                throw new NoUserIdException();
            }
        }
Exemplo n.º 15
0
    public string[] NewsFocus(string[] topics)
    {
        for (int j = 0; j < topics.Length; j++)
        {
            if (String.IsNullOrEmpty(query))
            {
                query = topics[j] + " ";
            }
            else
            {
                query += topics[j] + " ";
            }
        }

        string apiKey = "AIzaSyAdGYEvLJhlTZQ-Uxo_9IcoPuxwvbOcKV4";
        string cseKey = "018422199925324649720:fcnzsnkhzhu";
        var    bcsi   = new BaseClientService.Initializer {
            ApiKey = apiKey
        };
        var css         = new Google.Apis.Customsearch.v1.CustomsearchService(bcsi);
        var listRequest = css.Cse.List(query);

        listRequest.Cx = cseKey;
        var search = listRequest.Execute();

        for (int k = 0; k < 10; k++)
        {
            i[k] = search.Items[k].Link;
        }
        return(i);
    }
Exemplo n.º 16
0
        public async Task <bool> Login()
        {
            var clientSecretUri = new Uri("ms-appx:///Resources/client_secret.json", UriKind.Absolute);

            try
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecretUri, Scopes, "user", CancellationToken.None);

                await credential.RefreshTokenAsync(CancellationToken.None);
            }
            catch (TokenResponseException e)
            {
                await credential.GetAccessTokenForRequestAsync();
            }
            catch (Exception e)
            {
                return(false);
            }

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

            accessToken = credential.Token.AccessToken;

            Oauth2Service = new Oauth2Service(initializer);
            DriveService  = new DriveService(initializer);

            return(true);
        }
        /// <summary>
        /// A subtest for testing execute when an exception is thrown during sending the request, with or without
        /// back-off. If back-off handler is attached to the service's message handler, there are going to be several
        /// retries (up to 2 minutes).
        /// </summary>
        /// <param name="backOff">Indicates if back-off handler is attached to the service.</param>
        private void SubtestExecute_ThrowException(bool backOff)
        {
            var handler     = new MockMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            // by default back-off is used, so disable it in case backOff is false
            if (!backOff)
            {
                initializer.DefaultExponentialBackOffPolicy = BaseClientService.ExponentialBackOffPolicy.None;
            }

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws <InvalidOperationMockException>(() => request.Execute());

                // if back-off is enabled, we use 2 minutes maximum wait time for a request, so we should make lg(120)
                // + 1 calls
                int calls = backOff ? (int)Math.Ceiling(Math.Log(120, 2) + 1) : 1;
                Assert.That(handler.Calls, Is.EqualTo(calls));
            }
        }
Exemplo n.º 18
0
        public async Task <BaseClientService.Initializer> SetLoginCredencial()
        {
            UserCredential cred;

            using (var stream = new FileStream("../../Resources/GoogleLoginCookie.json", FileMode.Open, FileAccess.Read))
            {
                cred = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.Youtube },
                    "*****@*****.**", CancellationToken.None);
            }

            /*
             * var UserInfo = await GoogleWebAuthorizationBroker.AuthorizeAsync
             *  (new ClientSecrets { ClientId = LoginID, ClientSecret = LoginPw },
             *      new[] { YouTubeService.Scope.Youtube },
             *      "MakiseKurisu",
             *      CancellationToken.None);
             */
            var GoogleYoutube = new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred,
                ApplicationName       = "YOUTUBE GUI",
                ApiKey = "AIzaSyDBDHd7KZ3hkzARnkrxAFHZzw6vDMLX72Q",
            };

            if (GoogleYoutube == null)
            {
                throw new Exception("youtube API Login Failed!!\n");
            }
            return(GoogleYoutube);
        }
Exemplo n.º 19
0
 public ShoppingContentServiceWithBaseUri(
     BaseClientService.Initializer init, Uri u)
     : base(init)
 {
     this.baseUri  = u.AbsoluteUri;
     this.basePath = u.AbsolutePath;
 }
Exemplo n.º 20
0
        private async Task Run()
        {
            UserCredential credential;
            string         clientSecretsPath = CredentialsManager.GetClientSecretsLocation();

            using (FileStream stream = new FileStream(clientSecretsPath, FileMode.Open, FileAccess.Read))
            {
                // This OAuth 2.0 access scope allows for read-only access to the authenticated
                // user's account, but not other types of account access.
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(GetType().ToString())
                    );
            }

            BaseClientService.Initializer baseClientServiceInitializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = GetType().ToString()
            };
            YouTubeService youtubeService = new YouTubeService(baseClientServiceInitializer);

            ChannelsResource.ListRequest channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            ChannelListResponse channelsListResponse = await channelsListRequest.ExecuteAsync();

            foreach (Channel channel in channelsListResponse.Items)
            {
                // From the API response, extract the playlist ID that identifies the list
                // of videos uploaded to the authenticated user's channel.
                string uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                Console.WriteLine("Videos in list {0}", uploadsListId);

                string nextPageToken = "";
                while (nextPageToken != null)
                {
                    PlaylistItemsResource.ListRequest playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = uploadsListId;
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken  = nextPageToken;

                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    PlaylistItemListResponse playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                    foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
                    {
                        // Print information about each video.
                        Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }
            }
        }
Exemplo n.º 21
0
        public static BaseClientService.Initializer ForMtlsEndpoint(
            ICredential credential,
            IDeviceEnrollment enrollment,
            string baseUri)
        {
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = Globals.UserAgent.ToApplicationName()
            };

            if (enrollment?.Certificate != null &&
                HttpClientHandlerExtensions.IsClientCertificateSupported)
            {
                TraceSources.IapDesktop.TraceInformation(
                    "Enabling MTLS for {0}",
                    baseUri);

                // Switch to mTLS endpoint.
                initializer.BaseUri = baseUri;

                // Add client certificate.
                initializer.HttpClientFactory = new MtlsHttpClientFactory(enrollment.Certificate);
            }

            return(initializer);
        }
Exemplo n.º 22
0
        private async Task <string> GetInstance()
        {
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(ServiceAccountEmail)
                {
                    Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform }
                }.FromPrivateKey(PrivateKey));

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

                var t = new ComputeService(cs);

                var zoneRegion = Region + "-" + Zone;

                InstancesResource.GetRequest request = t.Instances.Get(Project, zoneRegion, InstanceName);

                Google.Apis.Compute.v1.Data.Instance response = await request.ExecuteAsync();

                return(JsonConvert.SerializeObject(response));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 23
0
        private string AddGroup()
        {
            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       = "GSuiteAddGroup"
            };

            var t = new DirectoryService(cs);

            var request = t.Groups.Insert(new Group
            {
                Email = GroupEmail,
                Name  = GroupName
            });

            var group = request.Execute();

            return(group.Id);
        }
Exemplo n.º 24
0
        public static async Task <YouTubeService> CreateAsync()
        {
            var(clientId, clientSecret) = YouTubeKeyStore.GetApiKey();

            var secrets = new ClientSecrets()
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            };

            var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                secrets,
                // This OAuth 2.0 access scope allows for full read/write access to the
                // authenticated user's account.
                new[] {
                YouTubeService.Scope.Youtube,
                YouTubeService.Scope.YoutubeForceSsl
            },
                "user",
                CancellationToken.None
                );

            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credential
            };

            return(new YouTubeService(initializer));
        }
        private string RemovePermission()
        {
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                User   = UserId,
                Scopes = new[] { DriveService.Scope.Drive }
            }.FromPrivateKey(PrivateKey));

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

            var t = new DriveService(cs);

            var listReq = t.Permissions.List(FileId);

            listReq.Fields = "permissions(id,emailAddress)";
            var permissionList = listReq.Execute();
            var perm           = permissionList.Permissions.First(p => p.EmailAddress == PermissionId);

            var request = t.Permissions.Delete(FileId, perm.Id);

            var prog = request.Execute();

            return("Success");
        }
Exemplo n.º 26
0
        private async Task AuthenticateAsync()
        {
            if (_service != null)
            {
                return;
            }
            
            FileStream stream = new FileStream(SecretFileName, FileMode.Open, FileAccess.Read);

            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(20));
            CancellationToken ct = cts.Token;

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { BloggerService.Scope.Blogger },
                "user",
                ct
                );

            BaseClientService.Initializer initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = ApplicationName
            };

            _service = new BloggerService(initializer);
        }
Exemplo n.º 27
0
        public void Initialize()
        {
            //string path = Files.GetFullPath("AsmodatBot.json");

            /*using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
             * {
             *  Credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
             *      new[] { GmailService.Scope.GmailReadonly },
             *      Name, CancellationToken.None).Result;
             * }*/

            X509Certificate2 Certificate = new X509Certificate2(OAuth2ID, OAuth2Secret, X509KeyStorageFlags.Exportable);

            ServiceAccountCredential.Initializer SACInitializer = new ServiceAccountCredential.Initializer(OAuth2ID);
            SACInitializer.Scopes = new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailSend };
            SACInitializer.User   = this.User;

            ServiceAccountCredential SACCredentials = new ServiceAccountCredential(SACInitializer.FromCertificate(Certificate));

            //ServiceAccountCredential SACredentials = new ServiceAccountCredential(new ServiceAccountCredential.Initializer)



            //GmailService.Scope.GmailSend,


            Initializer = new BaseClientService.Initializer();
            Initializer.HttpClientInitializer = Credentials;
            Initializer.ApplicationName       = Name;


            Service = new GmailService(Initializer);
        }
        private async Task <string> DeleteNetwork()
        {
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform }
            }.FromPrivateKey(PrivateKey));

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

            var t = new ComputeService(cs);

            var request = t.Networks.Delete(Project, NetworkName);

            var response = request.Execute();

            if (response.HttpErrorStatusCode != null)
            {
                var errorStr = new StringBuilder();
                foreach (var error in response.Error.Errors)
                {
                    errorStr.AppendLine(error.Code + " - " + error.Message);
                }
                return(errorStr.ToString());
            }
            else
            {
                return("Success");
            }
        }
 public ManufacturerCenterServiceWithBaseUri(
     BaseClientService.Initializer init, Uri u)
     : base(init)
 {
     this.baseUri  = u.AbsoluteUri;
     this.basePath = u.AbsolutePath;
 }
        public void ExecuteAsync_Error()
        {
            var handler     = new ErrorMessageHanlder();
            var initializer = new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                var            request    = new TestClientServiceRequest(service, "GET", null);
                AutoResetEvent resetEvent = new AutoResetEvent(false);
                var            task       = request.ExecuteAsync();
                var            error      = string.Empty;
                task.ContinueWith(t =>
                {
                    // should not ENTER this code, the task should fail
                    resetEvent.Set();
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
                task.ContinueWith(t =>
                {
                    // catch the error
                    error = t.Exception.InnerException.ToString();
                    resetEvent.Set();
                }, TaskContinuationOptions.NotOnRanToCompletion);
                resetEvent.WaitOne();
                Assert.True(error.Contains(handler.ExpectedError), "Error message is invalid");
                Assert.That(handler.Calls, Is.EqualTo(1));
            }
        }
        /// <summary>
        /// Creates the google client service implementation for the given google user ID asynchronous.
        /// </summary>
        /// <param name="authCode">The authentication code.</param>
        /// <returns>
        /// A Google Client Service instance.
        /// </returns>
        public async Task <IGoogleClientService> CreateGoogleClientServiceForUserAsync(string authCode)
        {
            // TODO make use of data store after testing
            var dataStore = new GoogleEntityDataStore(_context);

            using IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                      new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId     = _options.ClientId,
                    ClientSecret = _options.ClientSecret
                },
                Scopes = _options.Scopes,

                // TODO use entityDataStore
                DataStore = new FileDataStore("GoogleTokens")
            });

            TokenResponse token = await flow.ExchangeCodeForTokenAsync("USER_ID",
                                                                       authCode, _options.RedirectUri, CancellationToken.None);

            UserCredential credential = new UserCredential(flow, Environment.UserName, token);

            // Create service initializer
            BaseClientService.Initializer initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = _options.ApplicationName
            };

            return(new GoogleClientService(_logger, initializer));
        }
        // GET: /Calendar/UpcomingEvents
        public async Task<ActionResult> UpcomingEvents()
        {
            const int MaxEventsPerCalendar = 20;
            const int MaxEventsOverall = 50;

            var model = new UpcomingEventsViewModel();

            var credential = await GetCredentialForApiAsync();

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "ASP.NET MVC5 Calendar Sample",
            };
            var service = new CalendarService(initializer);

            // Fetch the list of calendars.
            var calendars = await service.CalendarList.List().ExecuteAsync();

            // Fetch some events from each calendar.
            var fetchTasks = new List<Task<Google.Apis.Calendar.v3.Data.Events>>(calendars.Items.Count);
            foreach (var calendar in calendars.Items)
            {
                var request = service.Events.List(calendar.Id);
                request.MaxResults = MaxEventsPerCalendar;
                request.SingleEvents = true;
                request.TimeMin = DateTime.Now;
                fetchTasks.Add(request.ExecuteAsync());
            }
            var fetchResults = await Task.WhenAll(fetchTasks);

            // Sort the events and put them in the model.
            var upcomingEvents = from result in fetchResults
                                 from evt in result.Items
                                 where evt.Start != null
                                 let date = evt.Start.DateTime.HasValue ?
                                     evt.Start.DateTime.Value.Date :
                                     DateTime.ParseExact(evt.Start.Date, "yyyy-MM-dd", null)
                                 let sortKey = evt.Start.DateTimeRaw ?? evt.Start.Date
                                 orderby sortKey
                                 select new { evt, date };
            var eventsByDate = from result in upcomingEvents.Take(MaxEventsOverall)
                               group result.evt by result.date into g
                               orderby g.Key
                               select g;

            var eventGroups = new List<CalendarEventGroup>();
            foreach (var grouping in eventsByDate)
            {
                eventGroups.Add(new CalendarEventGroup
                {
                    GroupTitle = grouping.Key.ToLongDateString(),
                    Events = grouping,
                });
            }

            model.EventGroups = eventGroups;
            return View(model);
        }
Exemplo n.º 33
0
        public void Custom_initializer_returns_project_id_and_initializer()
        {
            var initializer = new BaseClientService.Initializer();
            var customInitializer = new CustomInitializer("ProjectId", initializer);

            Assert.Equal("ProjectId", customInitializer.GetProjectId());
            Assert.Equal(initializer, customInitializer.GetInitializer());
        }
Exemplo n.º 34
0
 private async Task<StorageService> CreateServiceAsync()
 {
     GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
     var serviceInitializer = new BaseClientService.Initializer()
     {
         ApplicationName = "Storage Sample",
         HttpClientInitializer = credential
     };
     service = new StorageService(serviceInitializer);
     return service;
 }
Exemplo n.º 35
0
        private async Task Run()
        {

            var ics = new BaseClientService.Initializer
            {
                ApiKey = "AIzaSyD9pT1ig_V3DrzF-9xTUENXyS3Nf7reWAk",
                ApplicationName = "Test",
            };
           
            var youtubeService = new YouTubeService(ics);


      /*      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyB5VEzoWa9suKGKl6NNW6Hc_M-og0Wn2Xw",
                ApplicationName = this.GetType().ToString()
            });
       * */

            var searchListRequest = youtubeService.Search.List("snippet");
            searchListRequest.Q = "Jurasic Park"; // Replace with your search term.
            searchListRequest.MaxResults = 5;

            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = await searchListRequest.ExecuteAsync();

            List<string> videos = new List<string>();
            List<string> channels = new List<string>();
            List<string> playlists = new List<string>();

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                    case "youtube#video":
                        videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                        break;

                    case "youtube#channel":
                        channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                        break;

                    case "youtube#playlist":
                        playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                        break;
                }
            }

            Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
            Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
            Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
        }
Exemplo n.º 36
0
        public void Cloud_auth_object_returns_initializer()
        {
            var initializer = new BaseClientService.Initializer();
            var mockContext = new MockContext<CloudAuthenticator>();
            mockContext.Arrange(f => f.GetInitializer()).Returns(initializer);

            var cloudAuthMock = new CloudAuthenticatorMock(mockContext);
            var result = cloudAuthMock.GetInitializer();

            mockContext.Assert(f => f.GetInitializer(), Invoked.Once);
            Assert.Equal(initializer, result);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // If we did not construct the service so far, do it now.
            if (service == null)
            {
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                // You can enter your developer key for services requiring a developer key.
                /* initializer.ApiKey = "<Insert Developer Key here>"; */
                service = new UrlshortenerService(initializer);

            }
        }
Exemplo n.º 38
0
        public GoogleApiService()
        {
            var bcs = new BaseClientService.Initializer
            {
                ApplicationName = "Nadeko Bot",
                ApiKey = NadekoBot.Credentials.GoogleApiKey
            };

            _log = LogManager.GetCurrentClassLogger();

            yt = new YouTubeService(bcs);
            sh = new UrlshortenerService(bcs);
        }
        private static YouTubeService CreateYouTubeService(IKernel kernel)
        {
            var configRetriever = kernel.Resolve<IGetEnvironmentConfiguration>();
            string apiKey = configRetriever.GetSetting(YouTubeApiKey);
            kernel.ReleaseComponent(configRetriever);

            // Create client for YouTube API
            var youTubeInit = new BaseClientService.Initializer
            {
                ApiKey = apiKey,
                ApplicationName = "KillrVideo.SampleData.Worker"
            };
            return new YouTubeService(youTubeInit);
        }
Exemplo n.º 40
0
        public void Authenticate()
        {
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            }, scopes, userName, CancellationToken.None).Result;
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
        public void CreatePredictionService(string authJsonFile)
        {
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authJsonFile);
            var credentials = Google.Apis.Auth.OAuth2.GoogleCredential.GetApplicationDefaultAsync().Result;
            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(PredictionService.Scope.DevstorageFullControl, PredictionService.Scope.Prediction);
            }
            var serviceInitializer = new BaseClientService.Initializer()
            {
                ApplicationName = "Prediction Sample",
                HttpClientInitializer = credentials
            };

            PredictionService = new PredictionService(serviceInitializer);
        }
Exemplo n.º 42
0
        // [START create_storage_client]
        public StorageService CreateStorageClient()
        {
            var credentials = Google.Apis.Auth.OAuth2.GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[] { StorageService.Scope.DevstorageFullControl });
            }

            var serviceInitializer = new BaseClientService.Initializer()
            {
                ApplicationName = "Storage Sample",
                HttpClientInitializer = credentials
            };

            return new StorageService(serviceInitializer);
        }
Exemplo n.º 43
0
    public string CreateEvent(string Title, string Location, string SalesContact, string StartDate, string EndDate, string Comments, string ProductDescription, string OrderId, string RequiredDate, string ColorId)
    {
        // Add the calendar specific scope to the scopes list.
        scopes.Add(CalendarService.Scope.Calendar);

        UserCredential credential = default(UserCredential);

        using (FileStream stream = new FileStream(System.Configuration.ConfigurationSettings.AppSettings["Json"] + "client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, "ZZZZZZZZZZZZ", CancellationToken.None, null).Result;
        }
        String token = credential.Token.AccessToken;
        credential.Token.RefreshToken = token;
        // Create the calendar service using an initializer instance
        BaseClientService.Initializer initializer = new BaseClientService.Initializer();

        initializer.HttpClientInitializer = credential;
        initializer.ApplicationName = "DPI Google Calendar";
        service = new CalendarService(initializer);

        Event evnt = new Event();
        if (ColorId == "")
        { evnt.ColorId = "5"; }
        if (ColorId != "")
        { evnt.ColorId = ColorId; }
        evnt.Start = new EventDateTime
        {
            DateTime = Convert.ToDateTime(StartDate),
            TimeZone = "Australia/Melbourne"
        };
        evnt.End = new EventDateTime
        {
            DateTime = Convert.ToDateTime(EndDate),
            TimeZone = "Australia/Melbourne"
        };

        evnt.Description = "SalesContact : " + SalesContact + Environment.NewLine + Environment.NewLine + "Required On :" + Convert.ToDateTime(RequiredDate).ToShortDateString() + Environment.NewLine + Environment.NewLine + "Product Description :" + ProductDescription + Environment.NewLine + Environment.NewLine + "Supplier Instructions :" + Comments + Environment.NewLine + Environment.NewLine + "Order Item :" + OrderId;
        evnt.Summary = Title;
        evnt.Location = Location;
        service.Events.Insert(evnt, "*****@*****.**").Execute();
        //service.Events.Insert(evnt, "*****@*****.**").Execute();
        //  service.Events.Insert(evnt, "*****@*****.**").Execute();

        return "";
    }
Exemplo n.º 44
0
        public static async Task<DriveService> GetClient(TokenResponse token)
        {
            var credentials = new UserCredential(
               AuthFlow,
               null,
               token);

            var driveInitializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                HttpClientFactory = new GoogleDriveHttpClientFactory(),
                ApplicationName = "KeeAnywhere",
            };

            var client = new DriveService(driveInitializer);

            return client;
        }
Exemplo n.º 45
0
        public void SetCalendar(string clientKey, string secretKey,int orgId)
        {
            string refreshToken = string.Empty;
            try
            {
                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                DatabaseDataStore _fdsToken;
                if (!string.IsNullOrEmpty(refreshToken))
                {
                    StoredResponse storedResponse = new StoredResponse(refreshToken);
                    _fdsToken = new DatabaseDataStore(storedResponse, orgId);
                }
                else
                {
                    _fdsToken = new DatabaseDataStore(orgId,clientKey,secretKey);
                }
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = clientKey,
                      ClientSecret = secretKey,
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;

                credential.Token.RefreshToken = refreshToken;

                //credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {
                //string text = File.ReadAllText("C://Google.txt");
                //text = text + Environment.NewLine + ex.Message;
                //File.WriteAllText("C://Google.txt", text);
            }
        }
        private async Task AuthenticateAsync()
        {
            if (service != null)
                return;

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { BloggerService.Scope.BloggerReadonly },
                "user",
                CancellationToken.None);

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

            service = new BloggerService(initializer);
        }
Exemplo n.º 47
0
        public GoogleApiHelper(
            string p12Path,
            string serviceAccountEmail,
            string applicationName, 
            string calendarId,
            DateTime startCalendarQuery,
            DateTime endCalendarQuery)
        {
            try
            {
                var certificate = new X509Certificate2(p12Path, "notasecret", X509KeyStorageFlags.Exportable);

                var credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = new[] { CalendarService.Scope.Calendar }
                    }.FromCertificate
                    (certificate));

                var initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = applicationName;

                var service = new CalendarService(initializer);

                var queryStart = startCalendarQuery;
                var queryEnd = endCalendarQuery;

                var query = service.Events.List(calendarId);
                query.TimeMin = queryStart;
                query.TimeMax = queryEnd;

                var events = query.Execute().Items;

                _mEventList = events.Select(e => new GoogleCalendarEvent(DateTime.Parse(e.Start.Date), e.Summary)).ToList();

                _mEventList.Sort((e1, e2) => e1.Date.CompareTo(e2.Date));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Exception in GoogleAPIHelper constructor: {0}", e.Message));
            }
        }
Exemplo n.º 48
0
        private async Task AuthenticateAsync()
        {
            if (_service != null)
                return;

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { Oauth2Service.Scope.UserinfoEmail },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = "GoogleLogin",
            };

            _service = new Oauth2Service(initializer);

        }
Exemplo n.º 49
0
        private async Task Run()
        {
            IDataStore credentialPersistanceStore = getPersistentCredentialStore();

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { "email" },
                    getUserId(), CancellationToken.None, getPersistentCredentialStore());
            }

            BaseClientService.Initializer initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "OutlookAddin"
            };
            
        }
Exemplo n.º 50
0
        public string Main()
        {
            string result = "";

            CalendarService calendarConnection;

            ClientSecrets secrets = new ClientSecrets
            {
                ClientId = "473177441662-h57ba7mlrtkcgkb15ivd4srfjb4fdps8.apps.googleusercontent.com",
                ClientSecret = "thRD95BupH7H1UZaqoZUHFk3",
            };

            try
            {
                result = "we starting ";
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets,
                    new string[]
                    {
                        CalendarService.Scope.Calendar
                    },
                    "user",
                    CancellationToken.None)
                    .Result;

                result = "we pass 1 thing ";

                var initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "Jassplan";
                calendarConnection = new CalendarService(initializer);

                result = "we are here after calendar connection";
            }
            catch (Exception ex)
            {
                result = result +  ex.Message;
            }

            return result;
        }
Exemplo n.º 51
0
        public ServiceAccountAuthenticator(string projectId, string serviceAccountEmail, string certificatePath, string secretKey)
        {
            if (string.IsNullOrWhiteSpace(serviceAccountEmail))
                throw new ArgumentException(nameof(serviceAccountEmail));

            if (string.IsNullOrWhiteSpace(certificatePath))
                throw new ArgumentException(nameof(certificatePath));

            if (string.IsNullOrWhiteSpace(secretKey))
                throw new ArgumentException(nameof(secretKey));

            if (string.IsNullOrWhiteSpace(projectId))
                throw new ArgumentException(nameof(projectId));

            // Service account email must be an email address. A lot of people use the client Id instead of email by accident,
            // so this simple check should save them some time.
            if (!serviceAccountEmail.Contains("@"))
                throw new InvalidOperationException("The `serviceAccountEmail` parameter must be an email address. (Did you use a client Id by accident?)");

            _projectId = projectId;

            var fullpath = UriExtensions.GetAbsoluteUri(certificatePath);
            var certificate = new X509Certificate2(fullpath, secretKey, X509KeyStorageFlags.Exportable);

            var credential = new Google.Apis.Auth.OAuth2.ServiceAccountCredential(
               new Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[]
                   {
                           DatastoreService.Scope.Datastore,
                           DatastoreService.Scope.UserinfoEmail,
                           StorageService.Scope.DevstorageReadWrite
                   }
               }.FromCertificate(certificate));

            _initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = projectId
            };
        }
        private async Task GetCalendars(string accessToken)
        {
            var initializer = new BaseClientService.Initializer();
            var interceptor = new WinRTMessageAuthenticationInterceptor(accessToken);
            initializer.HttpClientInitializer = interceptor;

            //var handler = new HttpClientHandler();
            //var httpClient = new ConfigurableHttpClient(new ConfigurableMessageHandler(handler));
            //interceptor.Initialize(httpClient);
            var calendarService = new CalendarService(initializer);
            var calendarsResource = calendarService.CalendarList.List().Execute();

            var entries = calendarsResource.Items;
            foreach (var entry in entries)
            {
                Debug.WriteLine(entry.Description);
            }
            //string address = "https://www.googleapis.com/oauth2/v1/use%rinfo?access_token=" + accessToken;
            ////var response = await httpClient.GetAsync(new Uri(address));
            ////var content = await response.Content.ReadAsStringAsync();
            ////return content;
            //return null;
        }
        private DriveService Initialize()
        {
            var secrets = new ClientSecrets { ClientId = ClientId, ClientSecret = ClientSecret };
            var scopes = new[] { DriveService.Scope.Drive };

            var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, "user", CancellationToken.None).Result;

            // Create the service.
            var initialiser = new BaseClientService.Initializer();
            initialiser.HttpClientInitializer = credential;
            initialiser.ApplicationName = "PhotoGallery";
            var service = new DriveService(initialiser);

            return service;
        }
Exemplo n.º 54
0
        void SetupCalendarForSubsription()
        {
            try
            {
                string CTFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"CT";

                string refreshToken = string.Empty;
                DirectoryInfo directory = new DirectoryInfo(CTFolderPath);
                if (directory.GetFiles().Count() > 0)
                {
                    string filename = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).FirstOrDefault().FullName;
                    string jsonText = File.ReadAllText(filename);
                    var googleToken = (GoogleToken)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText, typeof(GoogleToken));
                    //Dictionary<string, object> tokenOjbect = test.refresh_token;//(Dictionary<string, object>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText);////new JavaScriptSerializer().DeserializeObject(jsonText);
                    refreshToken = googleToken.refresh_token;//tokenOjbect["refresh_token"].ToString();
                }
                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                FileDataStore _fdsToken = new FileDataStore(CTFolderPath);
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                      ClientSecret = "DDO62gcKn5nYWm4XCXlJkngo",
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;
                credential.Token.RefreshToken = refreshToken;// "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
                credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {

            }
        }
Exemplo n.º 55
0
        public static void SetCalendar()
        {
            try
            {
                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                FileDataStore _fdsToken = new FileDataStore("CT");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                      ClientSecret = "DDO62gcKn5nYWm4XCXlJkngo",
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;
                credential.Token.RefreshToken = "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
                credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {

            }
        }
Exemplo n.º 56
0
            public Google.Apis.Drive.v2.DriveService Init(string applicationName,
                                                    string clientIdentifier,
                                                    string clientSecret,
                                                    string[] scope,
                                                    bool logout,
                                                    string refreshTokenFolder)
            {
                StatusForm.ShowDialog();

                try
                {
                  _refreshTokenFilePath = refreshTokenFolder;

                  string fileDataStorePath = _refreshTokenFilePath;
                  if (FileExists(fileDataStorePath))
                  {
                DateTime lastFileWriteTime = GetFileLastWriteTime(fileDataStorePath);

                if (lastFileWriteTime < new DateTime(2014, 8, 22))
                {
                  DeleteFile(fileDataStorePath);
                }
                  }

                  if (logout)
                  {
                try
                {
                  if (DirectoryExists(fileDataStorePath))
                  {
                string[] fileDataStoreFiles = System.IO.Directory.GetFiles(fileDataStorePath,
                                                                           "Google.Apis.Auth.OAuth2.Responses.*");

                foreach (string fileDataStoreFile in fileDataStoreFiles)
                {
                  DeleteFile(fileDataStoreFile);
                }
                  }

                  LoginForm.Logout();
                }
                catch (Exception exception)
                {
                  Log.Error(String.Format("Authenticator.Logout - Deleting token file. {0}",exception.Message));
                }
                  }

                  var clientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
                  {
                ClientId = clientIdentifier,
                ClientSecret = clientSecret
                  };

                  _fileDataStore = new EncryptedFileDataStore(refreshTokenFolder);

                  System.Threading.Tasks.Task<Google.Apis.Auth.OAuth2.UserCredential> task = null;

                  try
                  {
                task = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                                                                                       clientSecrets,
                                                                                       scope,
                                                                                       System.Environment.UserName,
                                                                                       System.Threading.CancellationToken.None,
                                                                                       _fileDataStore);

                task.Wait();
                  }
                  catch (Exception exception)
                  {
                throw new LogException("GoogleWebAuthorizationBroker.AuthorizeAsync - " + exception.Message, false, false);
                  }

                  _userCredential = task.Result;

                  var initializer = new BaseClientService.Initializer
                  {
                HttpClientInitializer = _userCredential,
                ApplicationName = applicationName
                  };

                  _driveService = new Google.Apis.Drive.v2.DriveService(initializer);

                  UpdateAboutData(_driveService);

                  return _driveService;
                }
                catch (Exception exception)
                {
                  Log.Error(exception);

                  return null;
                }
                finally
                {
                  StatusForm.CloseDialog();
                }
            }
Exemplo n.º 57
0
        public bool ConnectCalendar()
        {
            var secrets = new ClientSecrets
            {
                ClientId = "945058434822-kg3aivhus8fe562j7a1oar208jokclsl.apps.googleusercontent.com",
                ClientSecret = "i14Tm4YYq2XGXtpyIsk5geAl"
            };

            try
            {
                var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        secrets,
                        new [] { CalendarService.Scope.Calendar },
                        "user",
                        CancellationToken.None)
                .Result;

                var initializer = new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Discount Work Schedule"
                };
                CalendarConnection = new CalendarService(initializer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }
Exemplo n.º 58
0
        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <returns></returns>
        private static async Task<CalendarService> GetClient()
        {
            if ((s_credential == null) || !HasCredentialsStored())
            {
                GetCredentialsPath(true);
                await LogOn(true);
            }

            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = s_credential,
                ApplicationName = EveMonClient.FileVersionInfo.ProductName,
            };

            return new CalendarService(initializer);
        }
Exemplo n.º 59
0
        //Dev SetCalendar
        public void SetCalendar(int orgId, bool isSubscription = false)
        {
            string clientKey = string.Empty;
            string secretKey = string.Empty;
            string refreshToken = string.Empty;
            string name = "GoogleCalendar";
            if (isSubscription)
            {
                name = "SubscribeGoogleCalendar";

            }
            try
            {
                var dt = SelectClientCredentials(name, orgId);
                if (dt != null)
                {
                    if (dt.Rows[0][0] != null)
                        clientKey = dt.Rows[0][0].ToString();
                    if (dt.Rows[0][1] != null)
                        secretKey = dt.Rows[0][1].ToString();
                    if (dt.Rows[0][2] != null)
                        refreshToken = dt.Rows[0][2].ToString();
                }

                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                DatabaseDataStore _fdsToken;
                if (!string.IsNullOrEmpty(refreshToken))
                {
                    StoredResponse storedResponse = new StoredResponse(refreshToken);
                    _fdsToken = new DatabaseDataStore(storedResponse, orgId);
                }
                else
                {
                    _fdsToken = new DatabaseDataStore(orgId);
                }
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = clientKey,// "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                      ClientSecret = secretKey,//"DDO62gcKn5nYWm4XCXlJkngo",
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;

                credential.Token.RefreshToken = refreshToken;

                //credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {
                string text = File.ReadAllText("C://Google.txt");
                text = text + Environment.NewLine + ex.Message;
                File.WriteAllText("C://Google.txt", text);
            }
        }
        private DriveService CreateDriveService(GoogleCredentials googleCredentials)
        {
            var authorizationCodeFlowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = googleCredentials.ClientId,
                    ClientSecret = googleCredentials.ClientSecret
                }
            };
            var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(authorizationCodeFlowInitializer);
            var token = new TokenResponse { RefreshToken = googleCredentials.RefreshToken };
            var credentials = new UserCredential(googleAuthorizationCodeFlow, "user", token);

            var initializer = new BaseClientService.Initializer
            {
                ApplicationName = "Emby",
                HttpClientInitializer = credentials
            };

            return new DriveService(initializer)
            {
                HttpClient = { Timeout = TimeSpan.FromHours(1) }
            };
        }