async private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AccessToken))
            {
                OrganizationsList.Visibility = Visibility.Collapsed;
                AuthBrowser.Visibility = Visibility.Visible;

                var url =
                    Common.FormatAuthUrl(
                        AuthorizationEndpointUrl,
                        ResponseTypes.Code,
                        ConsumerKey,
                        CallbackUrl,
                        DisplayTypes.Touch);

                AuthBrowser.Navigate(new Uri(url));

                return;
            }

            var auth = new AuthenticationClient();
            await auth.WebServer(ConsumerKey, ConsumerSecret, CallbackUrl, AccessToken);

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            var accounts = await client.Query<Account>("SELECT id, name, description FROM Account");

            OrganizationsList.Visibility = Visibility.Visible;
            AuthBrowser.Visibility = Visibility.Collapsed;

            OrganizationsList.ItemsSource = accounts;
        }
        public void Init()
        {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
        public async Task<ForceClient> GetForceClient(HttpClient httpClient)
        {
            _auth = new AuthenticationClient(httpClient);
            await _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password);

            var client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion, httpClient);
            return client;
        }
        public void Init()
        {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, TokenRequestEndpointUrl).Wait();

            const string apiVersion = "v34.0";
            _chatterClient = new ChatterClient(_auth.InstanceUrl, _auth.AccessToken, apiVersion);
        }
        public void Init()
        {
            _userAgent = "chatter-toolkit-dotnet";
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, _userAgent, TokenRequestEndpointUrl).Wait();

            _chatterClient = new ChatterClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
        public async Task<ForceClient> GetForceClient(HttpClient httpClient)
        {
            const string userAgent = "forcedotcom-toolkit-dotnet";
            var auth = new AuthenticationClient(httpClient);

            await auth.UsernamePassword(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion, httpClient);
            return client;
        }
        public SalesforceService()
        {
            _accountId = ConfigurationManager.AppSettings["Salesforce:AccountId"];
            _consumerKey = ConfigurationManager.AppSettings["Salesforce:ConsumerKey"];
            _consumerSecret = ConfigurationManager.AppSettings["Salesforce:ConsumerSecret"];
            _username = ConfigurationManager.AppSettings["Salesforce:Username"];
            _password = ConfigurationManager.AppSettings["Salesforce:Password"];

            _authenticationClient = new AuthenticationClient(new HttpClient());
        }
        private async Task<ForceClient> GetForceClient()
        {
            var auth = new AuthenticationClient();
            var url = _appSetting.IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? _appSetting.ProdUrl : _appSetting.SandboxUrl;

            await auth.UsernamePasswordAsync(_appSetting.ConsumerKey, _appSetting.ConsumerSecret, _appSetting.Username, _appSetting.Password, url);
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            return client;
        }
        public async Task<ChatterClient> GetChatterClient()
        {
            const string userAgent = "chatter-toolkit-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var client = new ChatterClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            return client;
        }
        public async Task<ActionResult> Callback(string display, string code)
        {
            var auth = new AuthenticationClient();
            await auth.WebServerAsync(_consumerKey, _consumerSecret, _callbackUrl, code);

            Session["ApiVersion"] = auth.ApiVersion;
            Session["AccessToken"] = auth.AccessToken;
            Session["InstanceUrl"] = auth.InstanceUrl;

            return RedirectToAction("Index", "SalesForce");
        }
示例#11
0
        private static async Task<ForceClient> GetSalesforceAPIClient(string consumerKey, string consumerSecret,
            string username, string password)
        {
            var authenticationClient = new AuthenticationClient();
            await authenticationClient.UsernamePasswordAsync(consumerKey, consumerSecret, username, password);

            var instanceUrl = authenticationClient.InstanceUrl;
            var accessToken = authenticationClient.AccessToken;
            var apiVersion = authenticationClient.ApiVersion;

            return new ForceClient(instanceUrl, accessToken, apiVersion);
        }
        public async Task<HttpResponseMessage> Get(string display, string code)
        {
            var auth = new AuthenticationClient();
            await auth.WebServerAsync(_consumerKey, _consumerSecret, _callbackUrl, code, UserAgent, _tokenRequestEndpointUrl);

            var url = string.Format("/?token={0}&api={1}&instance_url={2}", auth.AccessToken, auth.ApiVersion,
                auth.InstanceUrl);

            var response = new HttpResponseMessage(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri(url, UriKind.Relative);

            return response;
        }
        public async Task<ActionResult> GetRefreshToken(string refreshToken)
        {
            var auth = new AuthenticationClient();
            await auth.TokenRefreshAsync(_consumerKey, refreshToken, _consumerSecret);

            ViewBag.Token = auth.AccessToken;
            ViewBag.ApiVersion = auth.ApiVersion;
            ViewBag.InstanceUrl = auth.InstanceUrl;
            ViewBag.RefreshToken = auth.RefreshToken;
            
            ViewBag.LoggedIn = true;

            return View("Index");
        }
        public static async Task<IForceClient> CreateAuthenticationClient()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce           
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";
            
            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

            Client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            return Client;
        }
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password))
            {
                _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username = Environment.GetEnvironmentVariable("Username");
                _password = Environment.GetEnvironmentVariable("Password");
            }

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, TokenRequestEndpointUrl).Wait();

            const string apiVersion = "v34.0";
            _chatterClient = new ChatterClient(_auth.InstanceUrl, _auth.AccessToken, apiVersion);
        }
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password) && string.IsNullOrEmpty(_organizationId))
            {
                _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username = Environment.GetEnvironmentVariable("Username");
                _password = Environment.GetEnvironmentVariable("Password");
                _organizationId = Environment.GetEnvironmentVariable("OrganizationId");
            }

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
        private async void btnRefreshToken_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var auth = new AuthenticationClient();
                await auth.TokenRefreshAsync(ConsumerKey, _token.RefreshToken);

                var message = string.Format("Token Refresh Successful:\n\nAccess Token: {0}\n\nInstance URL: {1}",
                        auth.AccessToken, auth.InstanceUrl);

                lblOutput.Text = message;
            }
            catch (ForceException ex)
            {
                lblOutput.Text = ex.Message;
            }
        }
        internal async Task<ForceClient> GetClientForWebJob()
        {

            var consumerkey = ConfigurationManager.AppSettings["ConsumerKey"];
            var consumersecret = ConfigurationManager.AppSettings["ConsumerSecret"];
            var user = ConfigurationManager.AppSettings["User"];
            var password = ConfigurationManager.AppSettings["Password"];
            
            
            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(consumerkey, consumersecret, user, password);
            
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            Console.WriteLine("Connected to Salesforce, apiVersion:" + auth.ApiVersion);

            return client;

        }
示例#19
0
        private void initialize_helper()
        {
            var securityToken = "";
            var consumerKey = "";
            var consumerSecret = "";
            var username = "";
            var password = "";//password + securityToken;

            var auth = new AuthenticationClient();

            var url = "https://login.salesforce.com/services/oauth2/token";

            auth.UsernamePasswordAsync(consumerKey, consumerSecret, username, password, url).Wait();
            inner_sf_client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            inner_http_client = new HttpClient();
            inner_http_client.DefaultRequestHeaders.Add("Authorization", "Bearer " + auth.AccessToken);
        }
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password))
            {
                _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username = Environment.GetEnvironmentVariable("Username");
                _password = Environment.GetEnvironmentVariable("Password");
            }

            // Use TLS 1.2 (instead of defaulting to 1.0)
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, TokenRequestEndpointUrl).Wait();
            
            _chatterClient = new ChatterClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
示例#21
0
        /// <summary>
        /// Gets a ForceClient that has been authenticated using the UserName, Password, and SecurityToken settings
        /// specified in the config file.
        /// </summary>
        /// <returns>The authenticated ForceClient.</returns>
        public static async Task<ForceClient> GetUserNamePasswordForceClientAsync()
        {
//#error Update the config file with the connected app's UserName, Password and SecurityToken. For more information, see the Next Steps section of the Getting Started documentation.

            using (AuthenticationClient authenticationClient = new AuthenticationClient())
            {
                await authenticationClient.UsernamePasswordAsync(
                    SalesforceService.GetAppSetting("Salesforce:ConsumerKey"),
                    SalesforceService.GetAppSetting("Salesforce:ConsumerSecret"),
                    SalesforceService.GetAppSetting("Salesforce:UserName"),
                    SalesforceService.GetAppSetting("Salesforce:Password") + SalesforceService.GetAppSetting("Salesforce:SecurityToken", true),
                    SalesforceService.GetAppSetting("Salesforce:Domain") + "/services/oauth2/token");

                return new ForceClient(
                    authenticationClient.InstanceUrl,
                    authenticationClient.AccessToken,
                    authenticationClient.ApiVersion);
            }
        }
        protected async void booking_btn_Click(object sender, EventArgs e)
        {
            try
            {
                Random rnd = new Random();
                var userName = "******";
                var password = "******";
                var passwordSecurityToken = "<passwordSecurityToken>";
                var consumerKey = "consumerKey";
                var consumerSecret = "<consumerSecret>";
                var auth = new AuthenticationClient();

                await auth.UsernamePasswordAsync(consumerKey, consumerSecret, userName, password + passwordSecurityToken);

                var forceClient = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                
                Wallet wc = new Wallet { Bank__c = bankName.Value, Card_Type__c = cardType.Value, Credit_Card_Number__c = CardNo.Value };
                string x = await forceClient.CreateAsync("Wallet__c", wc);
                
                Rider__c rc = new Rider__c { Email_id__c = email.Value, Name__c = name.Value, Phone_number__c = contact.Value, Wallet__c = x };
                string x2 = await forceClient.CreateAsync("Rider__c", rc);
                
                Salesforce.Common.Models.QueryResult<Location__c> d1 = await forceClient.QueryAsync<Location__c>("SELECT Name,Id FROM Location__c WHERE Area_Name__c='" + dest.Value.Trim() + "'");
                Booking__c bc = new Booking__c { Destination__c = d1.Records[0].Id, Pick_Up__c = "a0728000000qCRg", pick_up_time__c = "2015-07-21T20:21:00Z", Rider__c = x2 };
                
                string x3 = await forceClient.CreateAsync("Booking__c", bc);
                Salesforce.Common.Models.QueryResult<Driver__c> d = await forceClient.QueryAsync<Driver__c>("SELECT Id,Address__c,Age__c,License_Number__c,Name__c,Phone__c,Status__c,Vehicle__c FROM Driver__c WHERE Status__c='For Hire'");
                d.Records[0].Status__c = "Hired";
                string ii = d.Records[0].Id;
                d.Records[0].Id = null;
                
                await forceClient.UpdateAsync("Driver__c", ii, d.Records[0]);

                Journey__c jc = new Journey__c { Distance_kms__c = rnd.Next(10, 100).ToString(), Rider_c = x2, Driver_c = ii };
                string x4 = await forceClient.CreateAsync("Journey__c", jc);
                
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert(" + ex.Message + " - " + ex.InnerException + ")</script>");
            }
        }
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            AuthenticationClient authenticationClient = new AuthenticationClient();

            // Get the access and refresh tokens from the Salesforce authorization server, and store them
            // on the session object.
            await authenticationClient.WebServerAsync(
                SalesforceService.GetAppSetting("Salesforce:ConsumerKey"),
                SalesforceService.GetAppSetting("Salesforce:ConsumerSecret"),
                SalesforceOAuthRedirectHandler.GetAbsoluteRedirectUri(),
                context.Request.QueryString["code"],
                context.Request.Url.PathAndQuery,
                "common-libraries-dotnet",
                SalesforceService.GetAppSetting("Salesforce:Domain") + "/services/oauth2/token");

            context.Session["AccessToken"] = authenticationClient.AccessToken;
            context.Session["RefreshToken"] = authenticationClient.RefreshToken;
            context.Session["InstanceUrl"] = authenticationClient.InstanceUrl;

            context.Response.Redirect(HttpUtility.ParseQueryString(context.Request.Url.Query).Get("state"), false);
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!success)
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            success = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Press Enter to delete parent and child and continue");
            Console.Read();

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            success = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
示例#25
0
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);        
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            string sql = "SELECT Id, CaseNumber, Current_Version__c, Priority, Go_Live_Critical__c, Case.Account.name, " +
            "Case.Owner.name, Origin, Patch_Number__c, Subject, OwnerId, Type, Description, CreatedDate, " +
            "Case.createdBy.name, status, bzid__c, product__c, Customer__r.name, " +
            "( SELECT CommentBody, CaseComment.createdBy.name, CaseComment.lastModifiedBy.name, CreatedDate, LastModifiedDate FROM CaseComments ORDER BY CreatedDate DESC NULLS LAST LIMIT 1 ) " +
            "FROM Case WHERE Status ='Eng New' AND Case.product__c='Accela ACA' AND Case.Owner.name='Engineering'";

            //const string qry = "SELECT ID, Name FROM Account";
            var accts = new List<Account>();
            var results = await client.QueryAsync<Account>(sql);
            var totalSize = results.TotalSize;

            Console.WriteLine("Queried " + totalSize + " records.");

            accts.AddRange(results.Records);
            var nextRecordsUrl = results.NextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                Console.WriteLine("Found nextRecordsUrl.");

                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync<Account>(nextRecordsUrl);
                    totalSize = continuationResults.TotalSize;
                    Console.WriteLine("Queried an additional " + totalSize + " records.");

                    accts.AddRange(continuationResults.Records);
                    if (string.IsNullOrEmpty(continuationResults.NextRecordsUrl)) break;

                    //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                    nextRecordsUrl = continuationResults.NextRecordsUrl;
                }
            }
            Console.WriteLine("Retrieved accounts = " + accts.Count() + ", expected size = " + totalSize);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!string.IsNullOrEmpty(success.Errors.ToString()))
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.Records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            var deleted = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.Records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Deleting parent and child");

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            deleted = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);
            Console.WriteLine("Connected to Salesforce");

            // Get a bulk client
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Make a strongly typed Account list
            var stAccountsBatch = new SObjectList<Account>
            {
                new Account {Name = "TestStAccount1"},
                new Account {Name = "TestStAccount2"},
                new Account {Name = "TestStAccount3"}
            };

            // insert the accounts
            var results1 = await client.RunJobAndPollAsync("Account", BulkConstants.OperationType.Insert,
                    new List<SObjectList<Account>>{stAccountsBatch});
            // (one SObjectList<T> per batch, the example above uses one batch)

            Console.WriteLine("Strongly typed accounts created");

            // Make a dynamic typed Account list
            var dtAccountsBatch = new SObjectList<SObject>
            {
                new SObject{{"Name", "TestDtAccount1"}},
                new SObject{{"Name", "TestDtAccount2"}},
                new SObject{{"Name", "TestDtAccount3"}}
            };

            // insert the accounts
            var results2 = await client.RunJobAndPollAsync("Account", BulkConstants.OperationType.Insert,
                    new List<SObjectList<SObject>>{dtAccountsBatch});

            Console.WriteLine("Dynamically typed accounts created");

            // get the id of the first account created in the first batch
            var id = results2[0][0].Id;
            dtAccountsBatch = new SObjectList<SObject>
            {
                new SObject
                {
                    {"Id", id},
                    {"Name", "TestDtAccount1Renamed"}
                }
            };

             // update the first accounts name (dont really need bulk for this, just an example)
            var results3 = await client.RunJobAndPollAsync("Account", BulkConstants.OperationType.Update,
                    new List<SObjectList<SObject>>{dtAccountsBatch});

            Console.WriteLine("Account with ID {0} updated", id);

            // create an Id list for the original strongly typed accounts created
            var idBatch = new SObjectList<SObject>();
            idBatch.AddRange(results1[0].Select(result => new SObject {{"Id", result.Id}}));

            // delete all the strongly typed accounts
            var results4 = await client.RunJobAndPollAsync("Account", BulkConstants.OperationType.Delete,
                    new List<SObjectList<SObject>>{idBatch});

            Console.WriteLine("Accounts deleted");
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // retrieve all accounts
            Console.WriteLine("Get Accounts");

            const string qry = "SELECT ID, Name FROM Account";
            var accts = new List<Account>();
            var results = await client.QueryAsync<Account>(qry);
            var totalSize = results.TotalSize;

            Console.WriteLine("Queried " + totalSize + " records.");

            accts.AddRange(results.Records);
            var nextRecordsUrl = results.NextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                Console.WriteLine("Found nextRecordsUrl.");

                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync<Account>(nextRecordsUrl);
                    totalSize = continuationResults.TotalSize;
                    Console.WriteLine("Queried an additional " + totalSize + " records.");

                    accts.AddRange(continuationResults.Records);
                    if (string.IsNullOrEmpty(continuationResults.NextRecordsUrl)) break;

                    //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                    nextRecordsUrl = continuationResults.NextRecordsUrl;
                }
            }
            Console.WriteLine("Retrieved accounts = " + accts.Count() + ", expected size = " + totalSize);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            var response = await client.CreateAsync(Account.SObjectTypeName, account);
            if (!string.Equals(response.Success, "true", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!string.IsNullOrEmpty(success.Errors.ToString()))
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.Records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            var deleted = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.Records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Deleting parent and child");

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            deleted = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
示例#28
0
        public async Task RunSample()
        {
            string qry;

            ///// SALESFORCE Authentication
            var auth = new Salesforce.Common.AuthenticationClient();

            log.Info("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

            log.Info("Connected to Salesforce");

            ///// Create SALESFORCE Client
            var client = new Salesforce.Force.ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // retrieve all accounts
            log.Info("Get Tasks");

            // This SOQL gets the list of IDs with dupes
            qry = "SELECT Prosperworks_ID__c " +
                  "FROM Task GROUP BY Prosperworks_ID__c " +
                  "HAVING Prosperworks_ID__c != '' AND Count(ID) > 1";

            var filter = await client.QueryAsync <SFTask>(qry);

            var ids = string.Join(",", filter.Records.Select(f => f.Prosperworks_ID__c).ToList().ToArray());

            ids = ids.Substring(0, ids.Length);

            ids = string.Join(",", ids.Split(',').Where(id => id != "").Select(id => $"'{id}'"));

            if (ids.Length == 0)
            {
                log.Warn("No duplicates found, exiting!");
                return;
            }

            qry = "SELECT ID, Prosperworks_ID__c, ActivityDate, Description, Type, TaskSubtype " +
                  "FROM Task " +
                  "WHERE ProsperWorks_ID__c IN (" + ids + ")";

            log.Info(qry);

            var tasks   = new List <SFTask>();
            var results = await client.QueryAsync <SFTask>(qry);

            var totalSize    = results.TotalSize;
            var totalDeleted = 0;
            var totalFlagged = 0;

            log.Info("Retrieved " + totalSize + " tasks.");

            // if (totalSize > 258) {
            //     log.Error("Too many records, exiting!");
            //     return;
            // }

            tasks.AddRange(results.Records);

            foreach (var task in tasks)
            {
                tasks.Where(t => t.Prosperworks_ID__c == task.Prosperworks_ID__c
                            & !String.Equals(t.Id, task.Id)
                            & !task.IsMarkedForDeletion).ToList()
                .ForEach(item => item.IsMarkedForDeletion = true);
            }

            var isDeleteEnabled = false;

            int i = 0;

            foreach (var task in tasks)
            {
                i++;
                if (task.IsMarkedForDeletion && task.Prosperworks_ID__c != "")
                {
                    totalFlagged++;
                    log.Debug($"[{i}] Task flagged {task.Id} {task.Prosperworks_ID__c}");
                    var isDeleted = false;
                    if (isDeleteEnabled)
                    {
                        //isDeleted = await client.DeleteAsync(SFTask.SObjectTypeName, task.Id);
                    }
                    if (!isDeleted)
                    {
                        if (isDeleteEnabled)
                        {
                            log.Error($"[{i}] Task delete FAILED {task.Id} {task.Prosperworks_ID__c}!");
                        }
                    }
                    else
                    {
                        log.Warn($"[{i}] Task deleted {task.Id} {task.Prosperworks_ID__c}.");
                        totalDeleted++;
                    }
                }
                else
                {
                    log.Debug($"[{i}] Task retained {task.Id} {task.Prosperworks_ID__c}");
                }
            }

            log.Debug($"Retrieved tasks = {tasks.Count()}, flagged = {totalFlagged}, deleted = {totalDeleted}");
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);
            Console.WriteLine("Connected to Salesforce");

            // Get a bulk client
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // create a job
            var jobInfo = await client.CreateJobAsync("Account", BulkConstants.OperationType.Insert);
            Console.WriteLine("Created a Job");

            // Make a dynamic typed Account list
            var dtAccountsBatch1 = new SObjectList<SObject>
            {
                new SObject{{"Name", "TestDtAccount1"}},
                new SObject{{"Name", "TestDtAccount2"}},
                new SObject{{"MADEUPFIELD", "MADEUPVALUE"}},
                new SObject{{"Name", "TestDtAccount3"}}
            };

            // Make a dynamic typed Account list
            var dtAccountsBatch2 = new SObjectList<SObject>
            {
                new SObject{{"Name", "TestDtAccount4"}},
                new SObject{{"Name", "TestDtAccount5"}},
                new SObject{{"Name", "TestDtAccount6"}}
            };

            // Make a dynamic typed Account list
            var dtAccountsBatch3 = new SObjectList<SObject>
            {
                new SObject{{"MADEUPFIELD", "MADEUPVALUE"}},
                new SObject{{"Name", "TestDtAccount7"}},
                new SObject{{"Name", "TestDtAccount8"}},
                new SObject{{"Name", "TestDtAccount9"}}
            };

            // create the batches
            var batchInfoList = new List<BatchInfoResult>
            {
                await client.CreateJobBatchAsync(jobInfo, dtAccountsBatch1),
                await client.CreateJobBatchAsync(jobInfo, dtAccountsBatch2),
                await client.CreateJobBatchAsync(jobInfo, dtAccountsBatch3)
            };
            Console.WriteLine("Created Three Batches");

            // poll
            var pollStart = 1.0f;
            const float pollIncrease = 2.0f;
            var completeList = new List<BatchInfoResult>();
            while (batchInfoList.Count > 0)
            {
                var removeList = new List<BatchInfoResult>();
                foreach (var batchInfo in batchInfoList)
                {
                    var newBatchInfo = await client.PollBatchAsync(batchInfo);
                    if (newBatchInfo.State.Equals(BulkConstants.BatchState.Completed.Value()) ||
                        newBatchInfo.State.Equals(BulkConstants.BatchState.Failed.Value()) ||
                        newBatchInfo.State.Equals(BulkConstants.BatchState.NotProcessed.Value()))
                    {
                        completeList.Add(newBatchInfo);
                        removeList.Add(batchInfo);
                    }
                }
                foreach (var removeInfo in removeList)
                {
                    batchInfoList.Remove(removeInfo);
                }
                await Task.Delay((int) pollStart);
                pollStart *= pollIncrease;
            }

            // get results
            var results = new List<BatchResultList>();
            foreach (var completeBatch in completeList)
            {
                results.Add(await client.GetBatchResultAsync(completeBatch));
            }

            Console.WriteLine("All Batches Complete, \"var results\" contains the result objects (Each is a list containing a result for each record):");
            foreach (var result in results.SelectMany(resultList => resultList.Items))
            {
                Console.WriteLine("Id:{0}, Created:{1}, Success:{2}, Errors:{3}", result.Id, result.Created, result.Success, result.Errors != null);
                if (result.Errors != null)
                {
                    Console.WriteLine("\tErrors:");
                    var resultErrors = result.Errors;
                    foreach (var field in resultErrors.Fields)
                    {
                        Console.WriteLine("\tField:{0}", field);
                    }
                    Console.WriteLine("\t{0}", resultErrors.Message);
                    Console.WriteLine("\t{0}", resultErrors.StatusCode);
                }
            }
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            await auth.UsernamePassword(ConsumerKey, ConsumerSecret, Username, Password);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.Create(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.Update(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!success)
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryById<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.Query<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            success = await client.Delete(Account.SObjectTypeName, account.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");
        }