public SilentWebUiRequest(AuthenticationRequestParameters authenticationRequestParameters, UserCredential userCredential)
            : base(authenticationRequestParameters)
        {
            if (userCredential == null)
            {
                throw new ArgumentNullException("userCredential");
            }

            this.userCredential = userCredential;
        }
 public async Task<int> CreateUserCredential(IDbConnection db, UserCredential userCredential)
 {
     string sqlQuery = @"INSERT INTO user_credential
         (user_id, game_id, username, session)
         VALUES
         (@user_id, @game_id, @username, @session)
         RETURNING id";
     var obj = await db.QueryAsync<int>(sqlQuery, userCredential);
     return obj.FirstOrDefault();
 }
 /// <summary>
 /// Update username and session only
 /// </summary>
 /// <param name="db"></param>
 /// <param name="userCredential"></param>
 /// <returns></returns>
 public async Task<bool> UpdateUserCredential(IDbConnection db, UserCredential userCredential)
 {
     string sqlQuery = @"UPDATE user_credential 
         SET
             username = @username,
             session = @session
         WHERE
             user_id = @user_id
         AND game_id = @game_id";
     return 1 == await db.ExecuteAsync(sqlQuery, userCredential);
 }
        public static async Task<WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            HttpClientWrapper request = new HttpClientWrapper(wsTrustAddress.Uri.AbsoluteUri, callState);
            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters = new StringRequestParameters(messageBuilder);
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);
                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream, wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (MsalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new MsalServiceException(
                    MsalError.FederatedServiceReturnedError,
                    string.Format(MsalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                    null,
                    ex);
            }

            return wstResponse;
        }
        private void PublishInCrmCallback(object sender, EventArgs e)
        {
            _myStopwatch = new Stopwatch();
            _myStopwatch.Start();

            _outputWindow = new OutputWindow();
            _outputWindow.Show();

            var selectedFilePath = GetSelectedFilePath();
            if (!CheckFileExtension(selectedFilePath))
            {
                AddErrorLineToOutputWindow("Error : Selected file extension is not valid.");
                return;
            }

            var solutionPath = GetSolutionPath();
            var connectionString = GetConnectionString(solutionPath);
            if (connectionString == string.Empty)
            {
                AddErrorLineToOutputWindow("Error : Connection string is not found.");

                var userCredential = new UserCredential();
                userCredential.ShowDialog();

                if (string.IsNullOrEmpty(userCredential.ConnectionString))
                {
                    AddErrorLineToOutputWindow("Error : Connection failed.");
                    return;
                }

                connectionString = userCredential.ConnectionString;

                WriteConnectionStringToFile(Path.GetFileNameWithoutExtension(solutionPath), connectionString, Path.GetDirectoryName(solutionPath));

            }

            AddLineToOutputWindow(string.Format("Publishig the {0} in Crm..", Path.GetFileName(selectedFilePath)));

            //Start the thread for updating and publishing the webresource.
            var thread =
                new Thread(o => UpdateTheWebresource(selectedFilePath, connectionString));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
        /// <summary>
        /// Creates the token.
        /// </summary>
        /// <param name="userDetails">The user details.</param>
        /// <param name="developerId">The developer unique identifier.</param>
        /// <returns>
        /// Returns Token.
        /// </returns>
        private static string CreateToken(UserCredential userDetails, int developerId)
        {
            var time = string.Format(CultureInfo.InvariantCulture, TokenDateFormat, DateTime.UtcNow);
            time = time + "-" + developerId.ToString(CultureInfo.CurrentCulture);
            if (!string.IsNullOrEmpty(userDetails.DeviceId))
            {
                time = time + "-" + userDetails.DeviceId;
            }

            return Crypto.EncryptData(time, Key, Salt);
        }
        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <param name="userDetails">The user.</param>
        /// <returns>
        /// returns index get
        /// </returns>
        public HttpResponseMessage PostAuthentication(UserCredential userDetails)
        {
            if (userDetails != null && this.developerService != null)
            {
                DeveloperListItem developer = this.developerService.RetrieveByUserNameAndPassword(userDetails.Username, userDetails.Password.GetHash(), null);
                if (developer != null)
                {
                    var time = DateTime.UtcNow.ToString();
                    time = time + "-" + developer.DeveloperID.ToString(CultureInfo.CurrentCulture);
                    string token = Crypto.EncryptData(time, Key, Salt);
                    User user = new User { UserId = developer.DeveloperID, Username = developer.DeveloperName, Token = token, TokenType = Bearer, Designation = developer.DesignationName };
                    return Request.CreateResponse(HttpStatusCode.OK, user);
                }
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
Beispiel #8
0
        /// <summary>
        /// Creates the new user session.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="connectionId">The connection identifier.</param>
        private void CreateNewUserSession(string userId, string connectionId)
        {
            UserCredential curCred = new UserCredential
                {
                    ConnectionStatus = ConnectionStatus.Connected,
                    UserId = userId
                };

            curCred.Sessions.Add(new ConnectionSession
                {
                    ConnectionId = connectionId,
                    ConnectedTime = DateTime.Now.Ticks,
                    DisconnectedTime = 0L
                });

            _connections.Add(userId, curCred);
        }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GmailApi"/> class.
 /// </summary>
 public GmailApi()
 {
     _credential = GetCredential(@"C:\Users\Ashie\AppData\Roaming\ADHDmail\GmailOAuth.json");
     PopulateService();
 }
Beispiel #10
0
        public static IConfigurableHttpClientInitializer Authenticate(
            BaseConfig config, string scope)
        {
            String[] scopes = new[] { scope };

            try
            {
                GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
                Console.WriteLine("Using Application Default Credentials.");
                return(credential.CreateScoped(scopes));
            }
            catch (AggregateException)
            {
                // Do nothing, we'll just let it slide and check the others.
            }

            if (config.ConfigDir == null)
            {
                throw new ArgumentException(
                          "Must use Google Application Default Credentials when running without a "
                          + "configuration directory");
            }

            String oauthFilePath      = Path.Combine(config.ConfigDir, "client-secrets.json");
            String serviceAccountPath = Path.Combine(config.ConfigDir, "service-account.json");

            if (File.Exists(serviceAccountPath))
            {
                Console.WriteLine("Loading service account credentials from " + serviceAccountPath);
                using (FileStream stream = new FileStream(
                           serviceAccountPath, FileMode.Open, FileAccess.Read))
                {
                    GoogleCredential credential = GoogleCredential.FromStream(stream);
                    return(credential.CreateScoped(scopes));
                }
            }
            else if (File.Exists(oauthFilePath))
            {
                Console.WriteLine("Loading OAuth2 credentials from " + oauthFilePath);
                using (FileStream oauthFile =
                           File.Open(oauthFilePath, FileMode.Open, FileAccess.Read))
                {
                    var           clientSecrets = GoogleClientSecrets.Load(oauthFile).Secrets;
                    var           userId        = "unused";
                    TokenResponse token         = LoadToken(config, scope);
                    if (token != null)
                    {
                        Console.WriteLine("Loading old access token.");
                        try
                        {
                            var init = new GoogleAuthorizationCodeFlow.Initializer()
                            {
                                ClientSecrets = clientSecrets,
                                Scopes        = scopes
                            };
                            var            flow       = new GoogleAuthorizationCodeFlow(init);
                            UserCredential storedCred = new UserCredential(flow, userId, token);
                            // Want to try and test and make sure we'll actually be able to
                            // use these credentials.
                            if (!storedCred.RefreshTokenAsync(CancellationToken.None).Result)
                            {
                                throw new InvalidDataException();
                            }
                            return(storedCred);
                        }
                        catch (InvalidDataException)
                        {
                            Console.WriteLine("Failed to load old access token.");
                            // Ignore, we'll just reauthenticate below.
                        }
                    }
                    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        clientSecrets, scopes, userId, CancellationToken.None).Result;
                    StoreToken(config, credential.Token);
                    return(credential);
                }
            }
            Console.WriteLine("Could not find authentication credentials. Checked:");
            Console.WriteLine(" - Google Application Default Credentials");
            Console.WriteLine(" - " + serviceAccountPath);
            Console.WriteLine(" - " + oauthFilePath);
            Console.WriteLine("Please read the included README for instructions.");
            return(null);
        }
        /// <summary>
        /// Begins publishing a video.
        /// </summary>
        /// <param name="filePath">Physical path of the video file.</param>
        /// <param name="parameters">RPC parameters.</param>
        /// <returns></returns>
        public override async Task <VideoPublishResult> PublishAsync(string filePath, IDictionary <string, string> parameters)
        {
            VideoPublishResult ret = null;

            Log.Info(string.Format("Sending {0} to YouTube...", filePath));

            if (System.IO.File.Exists(filePath) && parameters != null)
            {
                var credential = new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
                {
                    ClientSecrets = new ClientSecrets()
                    {
                        ClientId     = "732432655752-sc8rnb18i0os9s6gg9ru3fnvbdghc6mf.apps.googleusercontent.com",
                        ClientSecret = "rK7K4jw-5InCOPmPzoE8iLIM"
                    },
                    Scopes = new string[] { "https://www.googleapis.com/auth/youtube.upload" }
                }), parameters["UserId"], new Google.Apis.Auth.OAuth2.Responses.TokenResponse()
                {
                    AccessToken      = parameters["AccessToken"],
                    Issued           = DateTime.UtcNow,
                    ExpiresInSeconds = 300,
                    Scope            = "https://www.googleapis.com/auth/youtube.upload"
                });

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet       = new VideoSnippet();
                video.Snippet.Title = parameters["Title"];

                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "unlisted";

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");

                    videosInsertRequest.ProgressChanged += p =>
                    {
                        switch (p.Status)
                        {
                        case UploadStatus.Failed:
                            Log.Error(string.Format("Error uploading {0} to YouTube.", filePath), p.Exception);
                            break;

                        case UploadStatus.Completed:
                            Log.Info(string.Format("Successfully uploaded {0} bytes to YouTube for {1}.", p.BytesSent, filePath));
                            break;
                        }
                    };

                    videosInsertRequest.ResponseReceived += v =>
                    {
                        if (!string.IsNullOrEmpty(v.Id))
                        {
                            Log.Info(string.Format("Upload to YouTube of {0} is finished.", filePath));

                            ret = new VideoPublishResult()
                            {
                                Url = "https://www.youtube.com/my_videos"
                            };
                        }
                    };

                    await videosInsertRequest.UploadAsync();
                }
            }

            return(ret);
        }
Beispiel #12
0
        public void syncTasks(List <TaskData> tasks)
        {
            // List for user info
            List <string> eventsCreated = new List <string>();

            // bool to check if calendaritem exists
            bool itemExists = false;

            // Authorize API call
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
            {
                ClientId     = "173158901438-pcogjsudrgr4lk4pitlnc1dgdn2d3qm8.apps.googleusercontent.com",
                ClientSecret = "22rAjXySpj21xzFjU8AWYOlY"
            },
                new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None).Result;

            // Create the service
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Project Manager",
            });

            // Get already registered events
            var events = service.Events.List("primary").Execute();

            // Add a new calendar item to the google calendar, unless it already exists
            foreach (TaskData r in tasks)
            {
                for (int i = 0; i < events.Items.Count(); i++)
                {
                    if (r.Name == events.Items.ElementAt(i).Summary)
                    {
                        itemExists = true;
                        break;
                    }
                }
                if (itemExists)
                {
                    // Put it back to false for next loop instance
                    itemExists = false;

                    continue;
                }
                else
                {
                    // Creates an event object
                    Event newEvent = new Event()
                    {
                        Summary     = r.Name,
                        Description = r.Details,
                        Start       = new EventDateTime()
                        {
                            DateTime = DateTime.Now,
                            TimeZone = "Europe/Amsterdam",
                        },
                        End = new EventDateTime()
                        {
                            DateTime = DateTime.Parse(r.Deadline),
                            TimeZone = "Europe/Amsterdam",
                        }
                    };

                    string calendarId = "primary";
                    EventsResource.InsertRequest req = service.Events.Insert(newEvent, calendarId);
                    Event createdEvent = req.Execute();
                    eventsCreated.Add("Event has been created, link to the event: " + createdEvent.HtmlLink);
                }
            }

            var    message  = string.Join(Environment.NewLine, eventsCreated);
            string filepath = @"C:\Users\Tobias\source\repos\FUN12 Project\Killerapp-FUN12\ProjectManager\AppInfo\AddedEvents.txt";

            // Finally, display created events
            if (message == "")
            {
                MessageBox.Show("No new events were added. Existing events already synced to calendar.");
            }
            else
            {
                // Write events to txt file
                using (TextWriter tw = new StreamWriter(filepath))
                {
                    foreach (String s in eventsCreated)
                    {
                        tw.WriteLine(s);
                    }
                }

                // User info
                MessageBox.Show("All events are written to the info file at: " + filepath);
            }
        }
Beispiel #13
0
        private AuthenticationResult DoAcquireToken(
            AdalConfiguration config,
            PromptBehavior promptBehavior,
            Action <string> promptAction,
            string userId,
            SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(
                Resources.UPNAcquireTokenContextTrace,
                context.Authority,
                context.CorrelationId,
                context.ValidateAuthority);
            TracingAdapter.Information(
                Resources.UPNAcquireTokenConfigTrace,
                config.AdDomain,
                config.AdEndpoint,
                config.ClientId,
                config.ClientRedirectUri);
            if (string.IsNullOrEmpty(userId))
            {
                if (promptBehavior != PromptBehavior.Never)
                {
                    AdalTokenCache.ClearCookies();
                }

                Guid tempGuid = Guid.Empty;
                if (!string.Equals(config.AdDomain, "Common", StringComparison.OrdinalIgnoreCase) && !Guid.TryParse(config.AdDomain, out tempGuid))
                {
                    var tempResult = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        UserIdentifier.AnyUser,
                        AdalConfiguration.EnableEbdMagicCookie);
                    config.AdDomain = tempResult.TenantId;
                    context         = CreateContext(config);
                    promptBehavior  = PromptBehavior.Never;
                }

                result = context.AcquireToken(
                    config.ResourceClientUri,
                    config.ClientId,
                    config.ClientRedirectUri,
                    promptBehavior,
                    UserIdentifier.AnyUser,
                    AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                if (password == null)
                {
                    result = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return(result);
        }
Beispiel #14
0
 private static SheetsService GetSheetsService(UserCredential userCredential) => new SheetsService(new BaseClientService.Initializer
 {
     HttpClientInitializer = userCredential,
     ApplicationName       = ApplicationName
 });
Beispiel #15
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            HttpClientWrapper request = new HttpClientWrapper(wsTrustAddress.Uri.AbsoluteUri, callState);

            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder   messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters = new StringRequestParameters(messageBuilder);
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);

                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream, wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (MsalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new MsalServiceException(
                          MsalError.FederatedServiceReturnedError,
                          string.Format(MsalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args)
        {
            Console.WriteLine("This application generates an OAuth2 refresh token for use with " +
                              "the Google Ads API .NET client library. To use this application\n" +
                              "1) Follow the instructions on https://developers.google.com/adwords/api/docs/" +
                              "guides/authentication#create_a_client_id_and_client_secret to generate a new " +
                              "client ID and secret.\n2) Enter the client ID and client Secret when prompted.\n" +
                              "3) Once the output is generated, copy its contents into your " +
                              "App.config file.\n\n");

            // Accept the client ID from user.
            Console.Write("Enter the client ID: ");
            string clientId = Console.ReadLine();

            // Accept the client ID from user.
            Console.Write("Enter the client secret: ");
            string clientSecret = Console.ReadLine();

            // Should API scopes include AdWords API?
            string useAdWordsApiScope = AcceptInputWithLimitedOptions(
                "Authenticate for AdWords API?", new string[]
            {
                "yes",
                "no"
            });

            // Should API scopes include AdWords API?
            string useAdManagerApiScope =
                AcceptInputWithLimitedOptions("Authenticate for Ad Manager API?",
                                              new string[]
            {
                "yes",
                "no"
            });

            // Accept any additional scopes.
            Console.Write("Enter additional OAuth2 scopes to authenticate for (space separated): ");
            string additionalScopes = Console.ReadLine();

            List <string> scopes = new List <string>();

            if (useAdWordsApiScope.ToLower().Trim() == "yes")
            {
                scopes.Add(ADWORDS_API_SCOPE);
            }

            if (useAdManagerApiScope.ToLower().Trim() == "yes")
            {
                scopes.Add(AD_MANAGER_API_SCOPE);
            }

            scopes.AddRange(additionalScopes.Split(' ').Select(s => s.Trim())
                            .Where(s => !string.IsNullOrEmpty(s)));

            // Load the JSON secrets.
            ClientSecrets secrets = new ClientSecrets()
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            };

            try
            {
                // Authorize the user using installed application flow.
                Task <UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets,
                                                                                         scopes, String.Empty, CancellationToken.None, new NullDataStore());
                task.Wait();
                UserCredential credential = task.Result;

                Console.WriteLine("\nCopy the following content into your App.config file.\n\n" +
                                  $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" +
                                  $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" +
                                  $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" +
                                  $"<add key = 'OAuth2RefreshToken' " +
                                  $"value = '{credential.Token.RefreshToken}' />\n");

                Console.WriteLine("Press <Enter> to continue...");
                Console.ReadLine();
            }
            catch (AggregateException)
            {
                Console.WriteLine("An error occured while authorizing the user.");
            }
        }
Beispiel #17
0
        public async Task <bool> SignIn()
        {
            this.tcs = new TaskCompletionSource <bool>();
            // Add application settings before work for good UX
            try
            {
                //Uri clientSecretsUri = new Uri("/Utilities/google_secret.json",UriKind.Relative);
                //new ClientSecrets
                //    {
                //        ClientId = GOOGLE_DRIVE_CLIENT_ID,
                //        ClientSecret = GOOGLE_DRIVE_CLIENT_SECRET
                //    }
                this.Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new Uri("ms-appx:///Assets/client_secret.json"),
                    new[] { DriveService.Scope.Drive },
                    this._GetUserSession(),
                    CancellationToken.None
                    );

                this.Service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = this.Credential,
                    ApplicationName       = "athere",
                });
                AboutResource aboutResource = this.Service.About;
                About         about         = await aboutResource.Get().ExecuteAsync();

                this.User = about.User;

                string name = this.User.DisplayName;
                string id   = about.PermissionId;

                // Register account
                StorageAccount account = await App.AccountManager.GetStorageAccountAsync(id);

                if (account == null)
                {
                    account = new StorageAccount(id, StorageAccount.StorageAccountType.GOOGLE_DRIVE, name, 0.0);
                    await App.AccountManager.CreateStorageAccountAsync(account);
                }
                this.CurrentAccount = account;

                // Save sign in setting.
                App.ApplicationSettings[GOOGLE_DRIVE_SIGN_IN_KEY] = true;
                App.ApplicationSettings.Save();
                TaskHelper.AddTask(TaskHelper.STORAGE_EXPLORER_SYNC + this.GetStorageName(), StorageExplorer.Synchronize(this.GetStorageName()));
                tcs.SetResult(true);
            }
            catch (Google.GoogleApiException e)
            {
                Debug.WriteLine(e.ToString());
                System.Diagnostics.Debugger.Break();
                tcs.SetResult(false);
            }
            catch (System.Threading.Tasks.TaskCanceledException)
            {
                tcs.SetResult(false);
                System.Diagnostics.Debugger.Break();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                tcs.SetResult(false);
                System.Diagnostics.Debugger.Break();
            }

            return(tcs.Task.Result);
        }
        public Tuple <bool, string> Connect(ICredential credential)
        {
            Credential = credential;

            string message;

            if (Credential.Type == Authentication.AuthenticationType.Studio)
            {
                //IsSignedIn = IsValidStudioCredential(out message);
                var signInResult = StudioSignIn();

                IsSignedIn          = !string.IsNullOrEmpty(signInResult.Item1?.AccessToken);
                Credential.Token    = signInResult.Item1?.AccessToken;
                Credential.ValidTo  = GetTokenValidTo(Credential.Token);
                Credential.Name     = signInResult.Item1?.Email;
                Credential.Password = null;
                message             = signInResult.Item2;

                if (IsSignedIn)
                {
                    var userDetailsResult =
                        Task.Run(async() => await GetUserDetails(Credential.Token, Constants.MTCloudUriResourceUserDetails)).Result;
                    IsSignedIn           = userDetailsResult.Item1 != null;
                    Credential.AccountId = userDetailsResult.Item1?.AccountId.ToString();
                    message = userDetailsResult.Item2;
                }
            }
            else
            {
                IsSignedIn = IsValidCredential(out message);
                if (!IsSignedIn)
                {
                    if (Credential.Type == Authentication.AuthenticationType.User)
                    {
                        var credentials = new UserCredential
                        {
                            UserName = Credential.Name,
                            Password = Credential.Password
                        };

                        var content = JsonConvert.SerializeObject(credentials);

                        var signInResult = Task.Run(async() => await SignIn(Constants.MTCloudUriResourceUserToken, content)).Result;
                        IsSignedIn         = !string.IsNullOrEmpty(signInResult.Item1?.AccessToken);
                        Credential.Token   = signInResult.Item1?.AccessToken;
                        Credential.ValidTo = GetTokenValidTo(Credential.Token);
                        message            = signInResult.Item2;

                        if (IsSignedIn)
                        {
                            var userDetailsResult = Task.Run(async() => await GetUserDetails(Credential.Token, Constants.MTCloudUriResourceUserDetails)).Result;
                            IsSignedIn           = userDetailsResult.Item1 != null;
                            Credential.AccountId = userDetailsResult.Item1?.AccountId.ToString();
                            message = userDetailsResult.Item2;
                        }
                    }
                    else if (Credential.Type == Authentication.AuthenticationType.Client)
                    {
                        var credentials = new ClientCredential
                        {
                            ClientId     = Credential.Name,
                            ClientSecret = Credential.Password
                        };

                        var content = JsonConvert.SerializeObject(credentials);

                        var signInResult = Task.Run(async() => await SignIn(Constants.MTCloudUriResourceClientToken, content)).Result;
                        IsSignedIn         = !string.IsNullOrEmpty(signInResult.Item1?.AccessToken);
                        Credential.Token   = signInResult.Item1?.AccessToken;
                        Credential.ValidTo = GetTokenValidTo(Credential.Token);

                        message = signInResult.Item2;

                        if (IsSignedIn)
                        {
                            var userDetailsResult = Task.Run(async() => await GetUserDetails(Credential.Token, Constants.MTCloudUriResourceClientDetails)).Result;
                            IsSignedIn           = userDetailsResult.Item1 != null;
                            Credential.AccountId = userDetailsResult.Item1?.AccountId.ToString();
                            message = userDetailsResult.Item2;
                        }
                    }
                }
            }

            return(new Tuple <bool, string>(IsSignedIn, message));
        }
        public async Task<object> ThirdPartyRegister(Game game, string token, HttpRequest request)
        {
            string service = GetService(request.Params["ttype"]);

            string oauthAccountID = !string.IsNullOrEmpty(request.Params["onlyid"])
                ? request.Params["onlyid"] : request.Params["onlyID"];
            string username = request.Params["username"];
            string password = request.Params["password"];

            StringBuilder tokenBuilder = new StringBuilder();
            tokenBuilder.Append(game.id.ToString());
            tokenBuilder.Append(request.Params["action"]);
            tokenBuilder.Append(username);
            tokenBuilder.Append(oauthAccountID);
            tokenBuilder.Append(game.guid);
            tokenBuilder.Append(request.Params["tstamp"]);

            string generatedToken = Helper.CalculateMD5Hash(tokenBuilder.ToString());
            if (string.Compare(token, generatedToken, true) != 0)
                return FailResult(ErrorCodes.INVALID_TOKEN.ToErrorCode());

            ResultResponse result;
            var api = ProxyApi.Instance;
            if (!string.IsNullOrEmpty(password))
            {
                result = await GoplayService.Instance.SendAPIRequest<ResultResponse>(new Dictionary<string, string>()
                {   {ConstantValues.S_USERNAME, username},
                    {ConstantValues.S_PASSWORD, password},
                    {ConstantValues.S_GAME_ID, game.guid},
                    {ConstantValues.S_IP_ADDRESS, request.UserHostAddress}
                }, EGoPlayAction.Login, true);
            }
            else
            {
                password = Guid.NewGuid().ToString("d").ToUpper().Substring(0, 6);
                string nickname = !string.IsNullOrEmpty(request.Params["nickname"])
                    ? request.Params["nickname"] : request.Params["Nickname"];

                string email = request.Params["email"];
                string referralCode = request.Params["recommend"];

                result = await GoplayService.Instance.SendAPIRequest<ResultResponse>(new Dictionary<string, string>()
                {
                    {ConstantValues.S_USERNAME, username},
                    {ConstantValues.S_PASSWORD, password},
                    {ConstantValues.S_EMAIL, email},
                    {ConstantValues.S_NICKNAME, email},//don't know why?
                    {ConstantValues.S_REFERRAL_CODE, referralCode},
                    {ConstantValues.S_GAME_ID, game.guid},
                    {ConstantValues.S_IP_ADDRESS, request.UserHostAddress}
                }, EGoPlayAction.Register, true);

                if (result != null && result.profile != null && !string.IsNullOrEmpty(result.session))
                {
                    UserCredential userCredential = (await api.GetUserCredential(result.profile.uid, game.id)).Data;
                    if (userCredential == null)
                    {
                        userCredential = new UserCredential()
                        {
                            user_id = result.profile.uid,
                            game_id = game.id,
                            username = result.profile.account,
                            session = result.session,
                        };
                        await api.CreateUserCredential(userCredential);
                    }
                    else
                    {
                        userCredential.username = result.profile.account;
                        userCredential.session = result.session;
                        await api.UpdateUserCredential(userCredential);
                    }
                }
            }
            if (result == null || !result.success)
                return FailResult(ErrorCodes.INVALID_SESSION.ToErrorCode());

            string session = result.session;
            var oauthAccessToken = (await api.GetOauthAccessToken(service, oauthAccountID, game.id)).Data;
            if (oauthAccessToken == null)
                return FailResult("OAuth Account access token was not saved in previous steps");

            result = await GoplayService.Instance.SendAPIRequest<ResultResponse>(new Dictionary<string, string>()
                {
                    {ConstantValues.S_SESSION, session},
                    {ConstantValues.S_SERVICE, service},
                    {ConstantValues.S_TOKEN, oauthAccessToken.access_token},
                    {ConstantValues.S_GAME_ID, game.guid},
                    {ConstantValues.S_IP_ADDRESS, request.UserHostAddress}
                }, EGoPlayAction.ConnectOauth, true);
            return result;
        }
Beispiel #20
0
        public static bool VerifyPasswords(UserCredential userCreds, string password)
        {
            var result = HashPassword(password, userCreds.GetKey());

            return(result.HashedPassword == userCreds.Password);
        }
Beispiel #21
0
        /// <summary>
        /// Creates an MS tag for a given URL.
        /// </summary>
        /// <param name="credential">The API credential.</param>
        /// <param name="category">The tag category.</param>
        /// <param name="link">The link to encode in the tag.</param>
        /// <returns>The tag image.</returns>
        private BitmapSource CreateTag(UserCredential credential, string category, Uri link)
        {
            // Hash the URL for use in the title, because if the URL is too long, the tag service gets angry.
            string hash = GetMD5Hash(link.OriginalString);

            // Define the range for which the tag is valid.
            DateTime tagStartDate = DateTime.UtcNow.AddDays(-1);
            DateTime tagEndDate = DateTime.UtcNow.AddDays(90);

            MIBPContractClient client = new MIBPContractClient();
            Tag tag = null;

            try
            {
                // See if this tag already exists.
                tag = client.GetTagByTagName(credential, category, hash);

                if (tag.UTCEndDate > tagEndDate)
                {
                    // If the tag is expired, change the end date so that it will work again.
                    tag.UTCStartDate = tagStartDate;
                    tag.UTCEndDate = tagEndDate;

                    try
                    {
                        client.UpdateTag(credential, category, hash, tag);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch
            {
                // The tag wasn't found, so create a new one.
                tag = new URITag
                {
                    MedFiUrl = link.OriginalString,
                    Title = hash,
                    UTCStartDate = tagStartDate,
                    UTCEndDate = tagEndDate,
                };

                try
                {
                    client.CreateTag(credential, category, tag);
                }
                catch
                {
                    return null;
                }
            }

            try
            {
                byte[] barcode = client.GetBarcode(credential, category, hash, ImageTypes.png, .8f, DecorationType.HCCBRP_DECORATION_NONE, false);
                BitmapSource bmp = new PngBitmapDecoder(new MemoryStream(barcode), BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];
                return bmp;
            }
            catch
            {
                return null;
            }
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            const string aadInstance = "https://login.windows.net/{0}";
            const string tenant      = "genrt.onmicrosoft.com";

            var authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            var tokenCache  = new LocalFileTokenCache();
            var authContext = new AuthenticationContext(authority, tokenCache);

            //const string targetAppIdUri = "https://genrt.onmicrosoft.com/rtservices";
            const string targetAppIdUri = "http://*****:*****@genrt.onmicrosoft.com", "1dentity!2");
             *      result = authContext.AcquireToken(targetAppIdUri, clientId, uc);
             *      //result = authContext.AcquireToken(targetAppIdUri, clientId, redirectUri, PromptBehavior.Never);
             * }
             * catch (AdalException e)
             * {
             *      if (e.ErrorCode == "user_interaction_required" || e.ErrorCode == "invalid_grant")
             *      {
             *              needsSignIn = true;
             *      }
             *      else
             *      {
             *              Console.WriteLine(e);
             *              throw;
             *      }
             * }*/

            //if (needsSignIn)
            {
                try
                {
                    Console.WriteLine("Username?");
                    var username = Console.ReadLine();
                    Console.WriteLine("Password?");
                    var password = Console.ReadLine();
                    var uc       = new UserCredential(username, password);
                    result = authContext.AcquireToken(targetAppIdUri, clientId, uc);
                    //result = authContext.AcquireToken(targetAppIdUri, clientId, redirectUri, PromptBehavior.Always);
                }
                catch (AdalException e)
                {
                    if (e.ErrorCode == "authentication_canceled")
                    {
                        Console.WriteLine("Sign in was canceled by the user");
                    }
                    else
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }

                var httpClient = new HttpClient();

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                //const string targetServiceUri = "https://genrtentitydata.azurewebsites.net/api/plants";
                const string targetServiceUri = "http://localhost:50926/api/values";


                var response = httpClient.GetAsync(targetServiceUri).Result;

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Response: " + response);
                    var content = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine("Content: " + content);
                }
                else
                {
                    Console.WriteLine("An error occurred: " + response.ReasonPhrase);
                }
            }

            ClearCookies();
            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();
        }
Beispiel #23
0
			public void ReadXml (XmlReader reader)
			{
				// FIXME: do we need different versions?
				address = EndpointAddress.ReadFrom (AddressingVersion.WSAddressing10, reader);
				reader.MoveToContent ();
				// FIXME: create custom serializer
				credential = new XmlSerializer (typeof (UserCredential)).Deserialize (reader) as UserCredential;
			}
 public GoogleDriveApi(UserCredential userCredential)
 {
     _userCredential = userCredential;
 }
        private void VerifyAndRefreshCredentials(TransientCredentials tc)
        {
            var userCredential = tc.Token as UserCredential;
            var token          = userCredential?.Token;

            if (IsValidToken(token))
            {
                // We already have a valid OAuth token.
                return;
            }

            if (userCredential == null)
            {
                // Attempt to load a cached OAuth token.
                var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecretsStream = ClientSecretsStream,
                    DataStore           = GetCredentialsDataStoreForBlog(tc.Username),
                    Scopes = new List <string>()
                    {
                        BloggerServiceScope, PicasaServiceScope
                    },
                });

                var loadTokenTask = flow.LoadTokenAsync(tc.Username, CancellationToken.None);
                loadTokenTask.Wait();
                if (loadTokenTask.IsCompleted)
                {
                    // We were able re-create the user credentials from the cache.
                    userCredential = new UserCredential(flow, tc.Username, loadTokenTask.Result);
                    token          = loadTokenTask.Result;
                }
            }

            if (!IsValidToken(token))
            {
                // The token is invalid, so we need to login again. This likely includes popping out a new browser window.
                if (BlogClientUIContext.SilentModeForCurrentThread)
                {
                    // If we're in silent mode where prompting isn't allowed, throw the verification exception
                    throw new BlogClientAuthenticationException(String.Empty, String.Empty);
                }

                // Start an OAuth flow to renew the credentials.
                var authorizationTask = GetOAuth2AuthorizationAsync(tc.Username, CancellationToken.None);
                authorizationTask.Wait();
                if (authorizationTask.IsCompleted)
                {
                    userCredential = authorizationTask.Result;
                    token          = userCredential?.Token;
                }
            }

            if (!IsValidToken(token))
            {
                // The token is still invalid after all of our attempts to refresh it. The user did not complete the
                // authorization flow, so we interpret that as a cancellation.
                throw new BlogClientOperationCancelledException();
            }

            // Stash the valid user credentials.
            tc.Token = userCredential;
        }
Beispiel #26
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args)
        {
            Console.WriteLine("This application generates an OAuth2 refresh token for use with " +
                              "the Google Ads API .NET client library. To use this application\n" +
                              "1) Follow the instructions on " +
                              "https://developers.google.com/adwords/api/docs/guides/authentication#create_a_client_id_and_client_secret " +
                              "to generate a new client ID and secret.\n" + "2) Enter the client ID and client Secret " +
                              "when prompted.\n" +
                              "3) Once the output is generated, copy its contents into your App.config file.\n\n");

            // Accept the client ID from user.
            Console.Write("Enter the client ID: ");
            string clientId = Console.ReadLine();

            // Accept the client ID from user.
            Console.Write("Enter the client secret: ");
            string clientSecret = Console.ReadLine();

            // Load the JSON secrets.
            ClientSecrets secrets = new ClientSecrets()
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            };

            try
            {
                // Authorize the user using installed application flow.
                Task <UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets,
                    new string[] { GOOGLE_ADS_API_SCOPE },
                    String.Empty,
                    CancellationToken.None,
                    new NullDataStore()
                    );
                UserCredential credential = task.Result;

                Console.WriteLine("\nCopy the following content into your App.config file.\n\n" +
                                  $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" +
                                  $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" +
                                  $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" +
                                  $"<add key = 'OAuth2RefreshToken' value = " +
                                  $"'{credential.Token.RefreshToken}' />\n");

                Console.WriteLine("/n" +
                                  "<!-- Required for manager accounts only: Specify the login customer -->\n" +
                                  "<!-- ID used to authenticate API calls. This will be the customer ID -->\n" +
                                  "<!-- of the authenticated manager account. It should be set without -->\n" +
                                  "<!-- dashes, for example: 1234567890 instead of 123-456-7890. You can -->\n" +
                                  "<!-- also specify this later in code if your application uses -->\n" +
                                  "<!-- multiple manager account OAuth pairs. -->\n" +
                                  "<add key = 'LoginCustomerId' value = INSERT_LOGIN_CUSTOMER_ID_HERE />/n/n");

                Console.WriteLine("Press <Enter> to continue...");
                Console.ReadLine();
            }
            catch (AggregateException)
            {
                Console.WriteLine("An error occured while authorizing the user.");
            }
        }
        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <param name="userDetails">The user.</param>
        /// <returns>
        /// returns index get
        /// </returns>
        public HttpResponseMessage PostAuthenticateUser(UserCredential userDetails)
        {
            if (userDetails != null && this.developerService != null)
            {
                DeveloperListItem developer = this.developerService.AuthenticateDeveloper(userDetails.Username, userDetails.Password.GetHash(), null);

                if (developer != null)
                {
                    var token = CreateToken(userDetails, developer.DeveloperID);
                    User user = new User { UserId = developer.DeveloperID, Username = developer.DeveloperName, Token = token, TokenType = Bearer, Designation = developer.DesignationName };
                    var leaveBalance = this.leaveService.GetLeaveBalance(developer.DeveloperID);
                    var totalTimesheetHours = this.timesheetService.RetrieveTimesheetHours(developer.DeveloperID, DateTime.Now);
                    var applicableDate = this.timesheetService.RetrieveApplicableDate(true, DateTime.Now, Convert.ToInt32(developer.DeveloperID, CultureInfo.CurrentCulture));
                    ////var releaseItems = this.releaseService.RetrieveListForDate(DateTime.Now, null, null, developer.DeveloperID, true);
                    var releaseItems = this.lookupService.RetrieveReleaseTypes(developer.DeveloperID);
                    var projectList = this.AssignProjectReleaseTypes(releaseItems, developer.DeveloperID);
                    user.UserDashboard = new UserDashboard { LeaveBalance = Convert.ToDouble(leaveBalance), TotalTimesheetHours = totalTimesheetHours, TimesheetApplicableDate = applicableDate, ProjectReleases = projectList };

                    return Request.CreateResponse(HttpStatusCode.OK, user);
                }
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
Beispiel #28
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState, string cloudAudience)
        {
            IHttpClient request = new HttpClientWrapper(wsTrustAddress.Uri.AbsoluteUri, callState);

            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            if (string.IsNullOrEmpty(cloudAudience))
            {
                cloudAudience = defaultAppliesTo;
            }

            StringBuilder messageBuilder = BuildMessage(cloudAudience, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters        = new StringRequestParameters(messageBuilder);
                request.Headers["SOAPAction"] = soapAction;
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);

                wstResponse = WsTrustResponse.CreateFromResponse(EncodingHelper.GenerateStreamFromString(response.ResponseString), wsTrustAddress.Version);
            }
            catch (HttpRequestWrapperException ex)
            {
                string errorMessage;

                try
                {
                    using (Stream stream = EncodingHelper.GenerateStreamFromString(ex.WebResponse.ResponseString))
                    {
                        XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(stream);
                        errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                    }
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(CultureInfo.CurrentCulture, AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
Beispiel #29
0
 YouTubeService BuildService(UserCredential Credential) =>
 new YouTubeService(new BaseClientService.Initializer()
 {
     HttpClientInitializer = Credential,
     ApplicationName       = Assembly.GetExecutingAssembly().GetName().Name
 });
 internal void Dispose()
 {
     Credential        = null;
     YoutubeVideoId    = "";
     YoutubeLiveChatId = "";
 }
Beispiel #31
0
        private async void SubscribeButton_Click(object sender, RoutedEventArgs e)
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId     = "957928808020-pa0lopl3crh565k6jd4djaj36rm1d9i5.apps.googleusercontent.com",
                ClientSecret = "oB9U6yWFndnBqLKIRSA0nYGm"
            }, new[] { YouTubeService.Scope.Youtube }, "user", System.Threading.CancellationToken.None);

            // Create the service.
            var service = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Youtube Viewer",
            });

            if (isSubscribed == true)
            {
                SubscribeButton.Content = "Subscribe " + YoutubeItemMethodsStatic.ViewCountShortner(channel.Statistics.SubscriberCount);

                var getSubscription = service.Subscriptions.List("snippet");
                getSubscription.Mine = true;
                var subscriptions = await getSubscription.ExecuteAsync();

                Subscription subscription = new Subscription();

                Constants.MainPageRef.LoadSubscriptions();
                try
                {
                    var sub = Constants.MainPageRef.subscriptionsList.Single(x => x.Id == Constants.activeChannelID);
                    try
                    {
                        var unsubscribe = service.Subscriptions.Delete(sub.SubscriptionID);
                        await unsubscribe.ExecuteAsync();

                        isSubscribed = false;
                    }
                    catch
                    {
                        //Fires if subscription could not be removed for whatever reason.
                        SubscribeButton.Content = "Subscribed " + YoutubeItemMethodsStatic.ViewCountShortner(channel.Statistics.SubscriberCount + 1);
                    }
                }
                catch
                {
                    //Fires if subscription doesn't exist.
                    SubscribeButton.Content = "Subscribe " + YoutubeItemMethodsStatic.ViewCountShortner(channel.Statistics.SubscriberCount);
                    isSubscribed            = false;
                }
            }
            else
            {
                Subscription        subscription = new Subscription();
                SubscriptionSnippet snippet      = new SubscriptionSnippet();
                ResourceId          resourceId   = new ResourceId {
                    ChannelId = Constants.activeChannelID, Kind = "youtube#channel"
                };

                snippet.ResourceId   = resourceId;
                subscription.Snippet = snippet;

                var subscribe = service.Subscriptions.Insert(subscription, "snippet");
                subscribe.Execute();

                SubscribeButton.Content = "Subscribed " + YoutubeItemMethodsStatic.ViewCountShortner(channel.Statistics.SubscriberCount + 1);

                isSubscribed = true;
            }
        }
Beispiel #32
0
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Redirect base path to signin.
            if (context.Request.Path.EndsWith("/"))
            {
                context.Response.RedirectPermanent("signin.ashx");
            }


            // This is reached when the root document is passed. Return HTML
            // using index.html as a template.
            if (context.Request.Path.EndsWith("/signin.ashx"))
            {
                String state = (String)context.Session["state"];

                // Store a random string in the session for verifying
                // the responses in our OAuth2 flow.
                if (state == null)
                {
                    Random        random  = new Random((int)DateTime.Now.Ticks);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.Append(Convert.ToChar(
                                           Convert.ToInt32(Math.Floor(
                                                               26 * random.NextDouble() + 65))));
                    }
                    state = builder.ToString();
                    context.Session["state"] = state;
                }

                // Render the templated HTML.
                String templatedHTML = File.ReadAllText(
                    context.Server.MapPath("index.html"));
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId);
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*STATE\\s*[}]{2}", state);

                context.Response.ContentType = "text/html";
                context.Response.Write(templatedHTML);
                return;
            }

            if (context.Session["authState"] == null)
            {
                // The connect action exchanges a code from the sign-in button,
                // verifies it, and creates OAuth2 credentials.
                if (context.Request.Path.Contains("/connect"))
                {
                    // Get the code from the request POST body.
                    StreamReader sr = new StreamReader(
                        context.Request.InputStream);
                    string code = sr.ReadToEnd();

                    string state = context.Request["state"];

                    // Test that the request state matches the session state.
                    if (!state.Equals(context.Session["state"]))
                    {
                        context.Response.StatusCode = 401;
                        return;
                    }

                    // Use the code exchange flow to get an access and refresh token.
                    IAuthorizationCodeFlow flow =
                        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = secrets,
                        Scopes        = SCOPES
                    });

                    token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
                                                           CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                        new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = token.AccessToken;

                    Tokeninfo info = request.Execute();

                    string gplus_id = info.UserId;
                }
                else
                {
                    // No cached state and we are not connecting.
                    context.Response.StatusCode = 400;
                    return;
                }
            }
            else if (context.Request.Path.Contains("/connect"))
            {
                // The user is already connected and credentials are cached.
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = 200;
                context.Response.Write(JsonConvert.SerializeObject("Current user is already connected."));
                return;
            }
            else
            {
                // Register the authenticator and construct the Plus service
                // for performing API calls on behalf of the user.
                token = (TokenResponse)context.Session["authState"];
                IAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = secrets,
                    Scopes        = SCOPES
                });

                UserCredential credential = new UserCredential(flow, "me", token);
                bool           success    = credential.RefreshTokenAsync(CancellationToken.None).Result;

                token = credential.Token;
                ps    = new PlusService(
                    new Google.Apis.Services.BaseClientService.Initializer()
                {
                    ApplicationName       = ".NET Quickstart",
                    HttpClientInitializer = credential
                });
            }

            // Perform an authenticated API request to retrieve the list of
            // people that the user has made visible to the app.
            if (context.Request.Path.Contains("/people"))
            {
                // Get the PeopleFeed for the currently authenticated user.
                PeopleFeed pf = ps.People.List("me",
                                               PeopleResource.ListRequest.CollectionEnum.Visible).Execute();

                // This JSON, representing the people feed, will later be
                // parsed by the JavaScript client.
                string jsonContent =
                    Newtonsoft.Json.JsonConvert.SerializeObject(pf);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonContent);
                return;
            }

            // Disconnect the user from the application by revoking the tokens
            // and removing all locally stored data associated with the user.
            if (context.Request.Path.Contains("/disconnect"))
            {
                // Perform a get request to the token endpoint to revoke the
                // refresh token.
                token = (TokenResponse)context.Session["authState"];
                string tokenToRevoke = (token.RefreshToken != null) ?
                                       token.RefreshToken : token.AccessToken;

                WebRequest request = WebRequest.Create(
                    "https://accounts.google.com/o/oauth2/revoke?token=" +
                    token);

                WebResponse response = request.GetResponse();

                // Remove the cached credentials.
                context.Session["authState"] = null;

                // You could reset the state in the session but you must also
                // reset the state on the client.
                // context.Session["state"] = null;
                context.Response.Write(
                    response.GetResponseStream().ToString().ToCharArray());
                return;
            }
        }
Beispiel #33
0
 public async Task RevokeRealToken()
 {
     UserCredential cred = await GoogleWebAuthorizationBroker.AuthorizeAsync(
         Helper.GetClientSecretStream(), new string[] { "email" },
         "user", default, new NullDataStore());
Beispiel #34
0
        static void PostToGoogle(string[] args)
        {
            string         udpate     = args[0];
            UserCredential credential = null;

            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);

            credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
            string fn = @"C:\Users\scott\Documents\.credentials\sheets.googleapis.com-dotnet-quickstart.json\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user";

            if (DateTime.Now - File.GetCreationTime(fn) > new TimeSpan(0, 30, 0))
            {
                File.Delete(fn);
                using (var stream =
                           new FileStream(@"c:\src\client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    //ClientSecrets secrets = GoogleClientSecrets.Load(stream).Secrets;
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        writeScope,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }
            }
            string     tf  = File.ReadAllText(fn);
            string     tok = tf.Split(',')[0].Split(':')[1].Split('"')[1];
            HttpClient cl  = new HttpClient();

            cl.DefaultRequestHeaders.Add("Authorization", $"Bearer {tok}");
            //string url = "https://sheets.googleapis.com/v4/spreadsheets/14CoUxe6E12rGMzn6pic7ZmFPRZr1Tqvo7voSOhk7MDg/values/sheet1!a1:a2?valueInputOption=USER_ENTERED";
            string        url       = "https://sheets.googleapis.com/v4/spreadsheets/14CoUxe6E12rGMzn6pic7ZmFPRZr1Tqvo7voSOhk7MDg/values/sheet1!a1:e255?valueInputOption=USER_ENTERED";
            string        updatereq = File.ReadAllText(@"c:\src\googleUpdate.txt");
            StringBuilder sb        = new StringBuilder();

            string[] lines = File.ReadAllLines(@"c:\src\m.txt");
            sb.Append("{\"values\": [");
            for (int i = 0; i < lines.Length; i++)
            {
                string   l    = lines[i];
                string[] toks = l.Split(',');
                //if(toks.Length == 1) sb.Append($"[\"{toks[0]}\"],");
                if (i < lines.Length - 1)
                {
                    if (toks.Length == 1)
                    {
                        sb.Append($"[\"{toks[0]}\"],");
                    }
                    else
                    {
                        sb.Append($"[\"{toks[0]}\",{toks[1]},{toks[2]},{toks[3]},{toks[4]}],");
                    }
                }
                else
                {
                    if (toks.Length == 1)
                    {
                        sb.Append($"[\"{toks[0]}\"]");
                    }
                    else
                    {
                        sb.Append($"[\"{toks[0]}\",{toks[1]},{toks[2]},{toks[3]},{toks[4]}]");
                    }
                }
            }
            sb.Append("]}");
            File.WriteAllText(@"c:\src\res.txt", sb.ToString());

            HttpContent         content = new ByteArrayContent(ASCIIEncoding.ASCII.GetBytes(sb.ToString()));
            HttpResponseMessage resp    = cl.PutAsync(url, content).Result;
        }
        /// <summary>
        /// Sync the current database with Google Drive. Create a new file if it does not already exists
        /// </summary>
        private void syncWithGoogle(SyncCommand syncCommand, bool autoSync)
        {
            if (!m_host.Database.IsOpen)
            {
                ShowMessage("You first need to open a database.");
                return;
            }
            else if (!m_host.Database.IOConnectionInfo.IsLocalFile())
            {
                ShowMessage("Only databases stored locally or on a network share are supported.\n" +
                            "Save your database locally or on a network share and try again.");
                return;
            }

            string status = "Please wait ...";

            try
            {
                m_host.MainWindow.FileSaved  -= OnFileSaved;                // disable to not trigger when saving ourselves
                m_host.MainWindow.FileOpened -= OnFileOpened;               // disable to not trigger when opening ourselves
                ShowMessage(status, true);
                m_host.MainWindow.Enabled = false;

                // abort when user cancelled or didn't provide config
                if (!GetConfiguration())
                {
                    throw new PlgxException(Defs.ProductName() + " aborted!");
                }

                // Get Access Token / Authorization
                // Invoke async method GetAuthorization from thread pool to have no context to marshal back to
                // and thus making this call synchroneous without running into potential deadlocks.
                // Needed so that KeePass can't close the db or lock the workspace before we are done syncing
                UserCredential myCredential = Task.Run(() => GetAuthorization()).Result;

                // Create a new Google Drive API Service
                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = myCredential,
                    ApplicationName       = Defs.ProductName()
                });

                string filePath    = m_host.Database.IOConnectionInfo.Path;
                string contentType = "application/x-keepass2";

                File file = getFile(service, filePath);
                if (file == null)
                {
                    if (syncCommand == SyncCommand.DOWNLOAD)
                    {
                        status = "File name not found on Google Drive. Please upload or sync with Google Drive first.";
                    }
                    else                     // upload
                    {
                        if (!autoSync)
                        {
                            m_host.Database.Save(new NullStatusLogger());
                        }
                        status = uploadFile(service, "KeePass Password Safe Database", string.Empty, contentType, filePath);
                    }
                }
                else
                {
                    if (syncCommand == SyncCommand.UPLOAD)
                    {
                        if (!autoSync)
                        {
                            m_host.Database.Save(new NullStatusLogger());
                        }
                        status = updateFile(service, file, filePath, contentType);
                    }
                    else
                    {
                        string downloadFilePath = downloadFile(service, file, filePath);
                        if (!String.IsNullOrEmpty(downloadFilePath))
                        {
                            if (syncCommand == SyncCommand.DOWNLOAD)
                            {
                                status = replaceDatabase(filePath, downloadFilePath);
                            }
                            else                             // sync
                            {
                                status = String.Format("{0} {1}",
                                                       syncFile(downloadFilePath),
                                                       updateFile(service, file, filePath, contentType));
                            }
                        }
                        else
                        {
                            status = "File could not be downloaded.";
                        }
                    }
                }
            }
            catch (TokenResponseException ex)
            {
                string msg = string.Empty;
                switch (ex.Error.Error)
                {
                case "access_denied":
                    msg = "Access authorization request denied.";
                    break;

                case "invalid_request":
                    msg = "Either Client ID or Client Secret is missing.";
                    break;

                case "invalid_client":
                    msg = "Either Client ID or Client Secret is invalid.";
                    break;

                case "invalid_grant":
                    msg = "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.";
                    break;

                case "unauthorized_client":
                    msg = "The authenticated client is not authorized to use this authorization grant type.";
                    break;

                case "unsupported_grant_type":
                    msg = "The authorization grant type is not supported by the authorization server.";
                    break;

                case "invalid_scope":
                    msg = "The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.";
                    break;

                default:
                    msg = ex.Message;
                    break;
                }

                status = "ERROR";
                ShowMessage(msg);
            }
            catch (Exception ex)
            {
                status = "ERROR";
                ShowMessage(ex.Message);
            }

            m_host.MainWindow.UpdateUI(false, null, true, null, true, null, false);
            ShowMessage(status, true);
            m_host.MainWindow.Enabled     = true;
            m_host.MainWindow.FileSaved  += OnFileSaved;
            m_host.MainWindow.FileOpened += OnFileOpened;
        }
Beispiel #36
0
        public static async Task <string> AcquireToken(Dictionary <string, string> input)
        {
            Dictionary <string, object> res = new Dictionary <string, object>();
            AuthenticationContext       ctx = new AuthenticationContext(input["authority"]);

            try
            {
                AuthenticationResult result = null;

                if (!input.ContainsKey("redirect_uri"))
                {
                    UserCredential userCred = new UserCredential();
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], userCred).ConfigureAwait(false);
                }
                else if (input.ContainsKey("user_identifier") && input.ContainsKey("password"))
                {
                    UserPasswordCredential user = new UserPasswordCredential(input["user_identifier"], input["password"]);
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], user).ConfigureAwait(false);
                }
                else if (input.ContainsKey("user_identifier") && input.ContainsKey("user_identifier_type"))
                {
                    // user identifier type defaults to RequiredDisplayableId
                    UserIdentifierType userIdentifierType = UserIdentifierType.RequiredDisplayableId;
                    if (string.Equals(input["user_identifier_type"], "unique_id",
                                      StringComparison.InvariantCultureIgnoreCase))
                    {
                        userIdentifierType = UserIdentifierType.UniqueId;
                    }
                    else if (string.Equals(input["user_identifier_type"], "optional_displayable",
                                           StringComparison.InvariantCultureIgnoreCase))
                    {
                        userIdentifierType = UserIdentifierType.OptionalDisplayableId;
                    }
                    else if (string.Equals(input["user_identifier_type"], "required_displayable",
                                           StringComparison.InvariantCultureIgnoreCase))
                    {
                        userIdentifierType = UserIdentifierType.RequiredDisplayableId;
                    }

                    string prompt = input.ContainsKey("prompt_behavior") ? input["prompt_behavior"] : null;

                    if (input.ContainsKey("claims"))
                    {
                        result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]),
                                                             GetPlatformParametersInstance(prompt),
                                                             new UserIdentifier(input["user_identifier"], userIdentifierType), null, input["claims"])
                                 .ConfigureAwait(false);
                    }
                    else
                    {
                        result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]),
                                                             GetPlatformParametersInstance(prompt),
                                                             new UserIdentifier(input["user_identifier"], userIdentifierType))
                                 .ConfigureAwait(false);
                    }
                }
                else
                {
                    string prompt = input.ContainsKey("prompt_behavior") ? input["prompt_behavior"] : null;
                    result = await ctx.AcquireTokenAsync(input["resource"], input["client_id"], new Uri(input["redirect_uri"]),
                                                         GetPlatformParametersInstance(prompt)).ConfigureAwait(false);
                }
                res = ProcessResult(result, input);
            }
            catch (Exception exc)
            {
                res.Add("error", exc.Message);
            }
            return(FromDictionaryToJson(res));
        }
        public async Task<object> OriginalAPI()
        {
            var request = HttpContext.Current.Request;
            var api = ProxyApi.Instance;
            string token = !string.IsNullOrEmpty(request.Params["token"]) ? request.Params["token"] : string.Empty;
            string action = !string.IsNullOrEmpty(request.Params["action"]) ? request.Params["action"].ToLower() : string.Empty;
            Game game = null;
            ErrorCodes? error = null;
            ResultResponse response = null;
            int gameId = 0;
            int.TryParse(request.Params["gid"], out gameId);
            int venviciGid = Convert.ToInt16(ConfigurationManager.AppSettings["VENVICI_GID"]);

            if (gameId == venviciGid)
            {
                //so confuse
                game = new Game();
                game.id = venviciGid;
                game.guid = ConfigurationManager.AppSettings["VENVICI_GUID"];
            }
            else
                game = api.GetGame(gameId).Data;

            if (game == null)
                error = ErrorCodes.INVALID_GAME_ID;
            else if (ConstantValues.LIST_PROXY_ACTION.ContainsKey(action))
            {
                MethodInfo theMethod = this.GetType().GetMethod(ConstantValues.LIST_PROXY_ACTION[action]);
                var apiResponse = await (Task<object>)theMethod.Invoke(this, new object[] { game, token, request });
                response = apiResponse.CastObject<ResultResponse>();
            }
            else
                error = ErrorCodes.NON_EXISTING_API;

            if (error != null || response == null)
            {
                response = new ResultResponse
                {
                    success = false,
                    message = (error != null) ? error.ToErrorMessage() : ErrorCodes.ServerError.ToErrorMessage()
                };
            }

            //Not implemented yet in python
            //api.LogApi();

            if (response.profile != null && !string.IsNullOrEmpty(response.session))
            {
                var userCredentialObj = await api.GetUserCredential(response.profile.uid, game.id);
                UserCredential userCredential = userCredentialObj.Data;
                if (userCredential == null)
                {
                    userCredential = new UserCredential
                    {
                        user_id = response.profile.uid,
                        game_id = game.id,
                        username = response.profile.account,
                        session = response.session
                    };
                    await api.CreateUserCredential(userCredential);
                }
                else
                {
                    userCredential.username = response.profile.account;
                    userCredential.session = response.session;
                    await api.UpdateUserCredential(userCredential);
                }
            }

            ResultResponse result = ResponseConverter(response);
            return result;
        }
Beispiel #38
0
 private void SetUser(UserCredential credential)
 {
     SetUser(credential?.User);
 }
        public static StringBuilder BuildMessage(string appliesTo, WsTrustAddress wsTrustAddress,
            UserCredential credential)
        {
            // securityHeader will be empty string for Kerberos.
            StringBuilder securityHeaderBuilder = new StringBuilder(MaxExpectedMessageSize);

            string guid = Guid.NewGuid().ToString();
            StringBuilder messageBuilder = new StringBuilder(MaxExpectedMessageSize);
            string schemaLocation = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
            string soapAction = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
            string rstTrustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
            string keyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
            string requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
                rstTrustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                keyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey";
                requestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
            }

            messageBuilder.AppendFormat(CultureInfo.InvariantCulture,WsTrustEnvelopeTemplate,
                schemaLocation, soapAction,
                                guid, wsTrustAddress.Uri, securityHeaderBuilder,
                                rstTrustNamespace, appliesTo, keyType,
                                requestType);
            securityHeaderBuilder.SecureClear();

            return messageBuilder;
        }
		private bool CheckSignature(UserCredential credential){

			return credential.Signature == this.ComputeSignature(credential);

		}
        private AuthenticationResult AquireToken(AdalConfiguration config, bool noPrompt, string userId, SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            if (string.IsNullOrEmpty(userId))
            {
                var promptBehavior = PromptBehavior.Always;
                if (noPrompt)
                {
                    promptBehavior = PromptBehavior.Never;
                }
                else
                {
                    ClearCookies();
                }

                result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                    config.ClientRedirectUri, promptBehavior);
            }
            else
            {
                var promptBehavior = PromptBehavior.Auto;
                if (noPrompt)
                {
                    promptBehavior = PromptBehavior.Never;
                }

                if (password == null)
                {
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                        config.ClientRedirectUri, promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.OptionalDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return result;
        }
 public int DeleteAnnotationByBookId(int bookId, UserCredential userCredential)
 {
     return(base.Execute(base.MainDbPath, deleteAnnotationByBookIdSql, userCredential.Email, userCredential.ServiceCode, bookId));
 }
Beispiel #43
0
        /// <summary>
        /// Expires the session.
        /// </summary>
        /// <param name="curCred">The current cred.</param>
        private static void ExpireSession(UserCredential curCred)
        {
            var curSession = curCred.Sessions.Find
                (s => s.DisconnectedTime == 0);

            if (curSession != null)
            {
                curSession.DisconnectedTime = DateTime.Now.Ticks;
            }
        }
 /// <summary>
 /// Loads the specified user credential.
 /// </summary>
 /// <param name="credential"></param>
 public void SetUserCredential(UserCredential credential)
 {
     UserManager.CurrentUser = credential;
 }
Beispiel #45
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UpdateUserCredentialRequest"/>
        /// class with the specified API Key credentials.
        /// </summary>
        /// <param name="username">The new username.</param>
        /// <param name="apiKey">The new API key.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="username"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="apiKey"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="username"/> is empty.
        /// <para>-or-</para>
        /// <para>If <paramref name="apiKey"/> is empty.</para>
        /// </exception>
        public UpdateUserCredentialRequest(string username, string apiKey)
        {
            if (username == null)
                throw new ArgumentNullException("username");
            if (apiKey == null)
                throw new ArgumentNullException("apiKey");
            if (string.IsNullOrEmpty(username))
                throw new ArgumentException("username cannot be empty");
            if (string.IsNullOrEmpty(apiKey))
                throw new ArgumentException("apiKey cannot be empty");

            UserCredential = new UserCredential(null, username, apiKey);
        }
Beispiel #46
0
        public override async Task <ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode, CancellationToken taskCancellationToken)
        {
            if (string.IsNullOrEmpty(authorizationCode.Code))
            {
                var errorResponse = new TokenErrorResponse(authorizationCode);
                Logger.Info("Received an error. The response is: {0}", errorResponse);

                return(OnTokenError(errorResponse));
            }

            Logger.Debug("Received \"{0}\" code", authorizationCode.Code);

            var returnUrl = Request.Url.ToString();

            returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));

            //Asynchronously exchanges code with a token.
            var token = await Flow.ExchangeCodeForTokenAsync(UserId, authorizationCode.Code, returnUrl,
                                                             taskCancellationToken).ConfigureAwait(false);

            //Constructs a new credential instance with access token
            var credential = new UserCredential(Flow, UserId, token);

            try
            {
                var peopleService = new PeopleServiceService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "< YOUR APP NAME >",
                });

                #region Contacts

                PeopleResource.ConnectionsResource.ListRequest peopleRequest =
                    peopleService.People.Connections.List("people/me");

                peopleRequest.PersonFields = "addresses,ageRanges,biographies,birthdays,calendarUrls," +
                                             "clientData,coverPhotos,emailAddresses,events,externalIds,genders,imClients," +
                                             "interests,locales,locations,memberships,metadata,miscKeywords,names,nicknames," +
                                             "occupations,organizations,phoneNumbers,photos,relations,sipAddresses,skills,urls,userDefined";

                peopleRequest.SortOrder = PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum.LASTMODIFIEDDESCENDING;
                peopleRequest.PageSize  = 1000;

                ListConnectionsResponse connectionsResponse = peopleRequest.Execute();

                List <Person> connections = connectionsResponse.Connections as List <Person>;

                // get all pages
                while (!string.IsNullOrEmpty(connectionsResponse.NextPageToken))
                {
                    peopleRequest.PageToken = connectionsResponse.NextPageToken;
                    connectionsResponse     = peopleRequest.Execute();
                    connections.AddRange(connectionsResponse.Connections);
                }

                #endregion

                var model = connections.Where(x => x.EmailAddresses != null && x.EmailAddresses.Any());

                return(View(model));
            }
            catch (Exception exp)
            {
                Logger.Info("Received an error. The response is: {0}", exp.Message);

                return(View("Error"));
            }
        }
        private void PublishInCrm(bool isFromSolutionExplorer)
        {
            _outputWindow = new OutputWindow();
            _outputWindow.Show();

            //getting selected files
            List<string> selectedFiles = GetSelectedFilesPath(isFromSolutionExplorer);

            //checking selected files extensions
            var inValidFiles = CheckFilesExtension(selectedFiles);
            if (inValidFiles.Count > 0)
            {
                AddErrorToOutputWindow(string.Format("Invalid file extensions : {0}", string.Join(", ", inValidFiles)));
                AddErrorLineToOutputWindow(string.Format("Error : Invalid file extensions : \n\t- {0}", string.Join("\n\t- ", inValidFiles)));
                return;
            }

            //getting connection string
            var solutionPath = GetSolutionPath();
            var connectionString = GetConnectionString(solutionPath);
            if (connectionString == string.Empty)
            {
                SetConnectionLabelText("Connection string is not found.", _error);
                AddErrorLineToOutputWindow("Error : Connection string is not found.");

                var userCredential = new UserCredential(solutionPath);
                userCredential.ShowDialog();

                if (string.IsNullOrEmpty(userCredential.ConnectionString))
                {
                    SetConnectionLabelText("Connection failed.", _error);
                    AddErrorLineToOutputWindow("Error : Connection failed.");
                    return;
                }
                connectionString = userCredential.ConnectionString;
            }

            //updating/creating files one by one
            var thread = new Thread(o => UpdateWebResources(connectionString, selectedFiles));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
Beispiel #48
0
        public void Error(string message, string stracktrace = "", string module = "", UserCredential user = null, string token = "", bool IsSkipNotification = false)
        {
            try
            {
                var u   = UserUtilities.GetUser();
                var log = new LogMessage();
                log.Message  = message;
                log.Level    = EnumLogLevel.Error.ToString();
                log.CreateBy = user != null ? user.UserId : "";
                log.Token    = token;
                log.Module   = module;

                log.StackTrace         = stracktrace;
                log.IsSkipNotification = IsSkipNotification;
                log.CreateDate         = DateTime.Now;
                if (u != null)
                {
                    log.CreateBy = u.UserId;
                    log.Token    = UserUtilities.GetToken();
                }

                using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
                {
                    _db.LogMessages.Add(log);
                    _db.SaveChanges();
                    scope.Complete();
                }
                _eventBus.Publish(log, "LogMessage");
            }
            catch (Exception e)
            {
                WriteLogLocal(message, stracktrace, module);
            }
        }