示例#1
1
        public void Index(string searchString)
        {
            var accessToken = "00D61000000daFJ!AQgAQINgYkYKPlij4ZjYzU3Wbc67901dau4ZHO6HtChRL_aF_KVv.nkmiuDh8PvajhnbWPP2TsaGr8rMf8YTAwZItIW334mk";
            var apiVersion = "v32.0";
            var instanceUrl = "https://na34.salesforce.com";

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var accounts = client.QueryAsync<AccountViewModel>("SELECT id, name, BillingStreet, BillingCity, BillingState, BillingPostalCode FROM Account WHERE name LIKE '%" + searchString + "%'");

        }
        // GET: /Accounts/
        public async Task<ActionResult> Index()
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var accounts = await client.QueryAsync<AccountViewModel>("SELECT id, name, description FROM Account");

            return View(accounts.records);
        }
        public async Task<ActionResult> IndexFromAccount(string accountId)
        {

            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var contacts = await client.QueryAsync<SalesForceContactViewModel>("SELECT Id, FirstName, LastName, Title, Phone, Email From Contact WHERE AccountId= '" + accountId + "'");

            return View(contacts.records);
        }
        /// <summary>
        /// Getting all current existing Products
        /// </summary>
        /// <param name="client"></param>
        /// <param name="opportunityPriceBookID"></param>
        /// <returns></returns>
        public async Task <Products> GetProductDetails(ForceClient client, string opportunityPriceBookID)
        {
            Products products     = new Products();
            var      productsInfo = await client.QueryAsync <Product>("SELECT Name From Product2 ORDER BY Name ASC");

            if (productsInfo.Records.Any())
            {
                foreach (Product product in productsInfo.Records)
                {
                    string queryPart = "";
                    if (!string.IsNullOrWhiteSpace(opportunityPriceBookID))
                    {
                        queryPart = " AND Pricebook2Id='" + opportunityPriceBookID + "'";
                    }
                    // Getting each product details
                    var productDetails = await client.QueryAsync <Product>("SELECT Id, Pricebook2Id, Product2Id, UnitPrice, Name From PricebookEntry WHERE Name='" + product.Name + "'" + queryPart + " ORDER BY Name ASC");

                    if (productDetails.Records.Any())
                    {
                        // Getting only first, as it will have all required info which we need
                        products.AllProducts.Add(productDetails.Records[0]);
                    }
                }
            }
            return(products);
        }
示例#5
0
        public IActionResult RequestFile()
        {
            var auth = new AuthenticationClient();

            auth.UsernamePasswordAsync(_configuration.GetValue <string>("SFConsumerKey"), _configuration.GetValue <string>("SFConsumerSecret"), _configuration.GetValue <string>("SFUserName"), _configuration.GetValue <string>("SFPassword")).Wait();

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

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);

            // Get list of files available for download from SalesForce
            List <FileRequest> files = new List <FileRequest>();
            var availableFiles       = client.QueryAsync <AvailableFile>(string.Format("SELECT id, FileName__c FROM AvailableFile__c ORDER BY FileName__c")).Result;

            if (availableFiles.Records.Count > 0)
            {
                for (int i = 0; i < availableFiles.Records.Count; i++)
                {
                    files.Add(new FileRequest()
                    {
                        FileName__c = availableFiles.Records[i].FileName__c, UserName__c = User.Identity.Name
                    });
                }
            }

            // Check for existing file requests by this user
            var fileRequests = client.QueryAsync <FileRequest>(string.Format("SELECT id, FileName__c, UserName__c, Status__c, FileUrl__c FROM FileRequest__c WHERE UserName__c = '{0}'", User.Identity.Name)).Result;

            if (fileRequests.Records.Count > 0)
            {
                ViewBag.Refresh = true;
                for (int i = 0; i < fileRequests.Records.Count; i++)
                {
                    foreach (FileRequest file in files)
                    {
                        if (file.FileName__c == fileRequests.Records[i].FileName__c)
                        {
                            bool isExpired = HandleExpiredRequest(client, fileRequests.Records[i]);
                            if (!isExpired)
                            {
                                file.Id         = fileRequests.Records[0].Id;
                                file.Status__c  = fileRequests.Records[i].Status__c;
                                file.FileUrl__c = fileRequests.Records[i].FileUrl__c;
                            }
                        }
                    }
                }
            }

            ViewBag.User      = User.Identity.Name;
            ViewBag.IPAddress = Request.HttpContext.Connection.RemoteIpAddress;
            ViewBag.Files     = files;
            return(View());
        }
示例#6
0
        public async Task <List <TEntity> > Get(string sfObject, params string[] includedFields)
        {
            var query = new StringBuilder();

            query.Append("SELECT Id,");
            for (int i = 0; i < includedFields.Length; i++)
            {
                query.Append(includedFields[i] + ",");
            }
            query.Remove(query.Length - 1, 1);
            query.AppendFormat(" FROM {0}", sfObject);
            var result = await _client.QueryAsync <TEntity>(query.ToString());

            return(result.Records);
        }
        // GET: /Accounts/
        public ActionResult Index(string searchString)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var allModels = new Tuple<List<AccountViewModel>,
    List<AccountViewModel1>>
    (client.QueryAsync<AccountViewModel>("SELECT id, name, BillingStreet, BillingCity, BillingState, BillingPostalCode FROM Account WHERE name LIKE '%" + searchString + "%'").Result.records, client.QueryAsync<AccountViewModel1>("SELECT id, name, BillingStreet, BillingCity, BillingState, BillingPostalCode FROM Account").Result.records) { };
            //var allAccounts = await client.QueryAsync<AccountViewModel1>("SELECT id, name, BillingStreet, BillingCity, BillingState, BillingPostalCode FROM Account");
            //var accounts = await client.QueryAsync<AccountViewModel>("SELECT id, name, BillingStreet, BillingCity, BillingState, BillingPostalCode FROM Account WHERE name LIKE '%" + searchString + "%'");

            return View(allModels);
        }
示例#8
0
        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.Token,
                        ConsumerKey,
                        CallbackUrl,
                        DisplayTypes.Touch);

                AuthBrowser.Navigate(new Uri(url));

                return;
            }

            var client   = new ForceClient(_instanceUrl, _accessToken, ApiVersion);
            var accounts = await client.QueryAsync <Account>("SELECT id, name, description FROM Account");

            OrganizationsList.ItemsSource = accounts.records;

            OrganizationsList.Visibility = Visibility.Visible;
            AuthBrowser.Visibility       = Visibility.Collapsed;
        }
        public async Task <SalesForceModels.OpportunitiesViewModel> GetOpportunities(ForceClient client)
        {
            var allOpportunities = new SalesForceModels.OpportunitiesViewModel();
            var opportunities    = await client.QueryAsync <SalesForceModels.OpportunityModel>("SELECT ID, Name, CloseDate, StageName, Type, Amount, LeadSource,Probability From Opportunity ORDER BY Name ASC");

            if (opportunities.Records.Any())
            {
                foreach (var opportunity in opportunities.Records)
                {
                    allOpportunities.Opportunities.Add(new SalesForceModels.OpportunityModel
                    {
                        Id          = opportunity.Id,
                        Name        = opportunity.Name,
                        CloseDate   = opportunity.CloseDate,
                        StageName   = opportunity.StageName,
                        Type        = opportunity.Type,
                        Amount      = opportunity.Amount,
                        LeadSource  = opportunity.LeadSource,
                        Probability = opportunity.Probability,
                        //Account = opportunity.Account
                    });
                }
            }
            return(allOpportunities);
        }
示例#10
0
        public Class1()
        {
            var auth = new AuthenticationClient("v44.0");

            var account = new Account()
            {
                Name = "New Name", Description = "New Description"
            };

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

            var client     = new ForceClient(instanceUrl, accessToken, apiVersion);
            var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);

            var id = await client.CreateAsync("Account", account);

            var accounts = await client.QueryAsync <Account>("SELECT id, name, description FROM Account");

            foreach (var account in accounts.records)
            {
                Console.WriteLine(account.Name);
            }
        }
        private async Task <dynamic> GetAccounts()
        {
            var client   = new ForceClient(_token.InstanceUrl, _token.AccessToken, "v29.0");
            var accounts = await client.QueryAsync <Account>("SELECT id, name, description FROM Account");

            return(accounts.records);
        }
        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.Token,
                        ConsumerKey,
                        CallbackUrl,
                        DisplayTypes.Touch);

                AuthBrowser.Navigate(new Uri(url));

                return;
            }

            var client = new ForceClient(_instanceUrl, _accessToken, ApiVersion);
            var accounts = await client.QueryAsync<Account>("SELECT id, name, description FROM Account");

            OrganizationsList.ItemsSource = accounts.records;

            OrganizationsList.Visibility = Visibility.Visible;
            AuthBrowser.Visibility = Visibility.Collapsed;
        }
示例#13
0
        public async Task QueryAsyncEnumeratorLarge()
        {
            ForceClient client = await forceClientFixture.GetForceClient();

            var enumerable = client.QueryAsync <SfContact>("SELECT Id FROM Contact");

            int count = 0;

            using (var enumerator = enumerable.GetEnumerator())
            {
                while (await enumerator.MoveNext())
                {
                    var currentItem = enumerator.Current;
                    count++;
#if DEBUG
                    if (count % 1000 == 0)
                    {
                        Console.WriteLine("QueryAsyncEnumeratorLarge: processed {0} records", count.ToString());
                    }
#endif
                }
            }

            Assert.True(count > 0);
        }
示例#14
0
        public static async Task <List <Account> > GetSalesforceAccounts(AuthenticationClient auth)
        {
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // retrieve all accounts
            var accts   = new List <Account>();
            var results = await client.QueryAsync <Account>(ACCOUNT_QUERY);

            var totalSize = results.totalSize;

            accts.AddRange(results.records);
            var nextRecordsUrl = results.nextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync <Account>(nextRecordsUrl);

                    totalSize = continuationResults.totalSize;

                    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;
                }
            }

            return(accts);
        }
示例#15
0
        public async Task QueryAsyncEnumeratorSmallBatch()
        {
            ForceClient client = await forceClientFixture.GetForceClient();

            var contactsEnumerable = client.QueryAsync <SfContact>("SELECT Id FROM Contact LIMIT 1000", batchSize: 200);

            int       count   = 0;
            SfContact contact = null;

            using (IAsyncEnumerator <SfContact> contactsEnumerator = contactsEnumerable.GetEnumerator())
            {
                // Assert.NotNull(contactsEnumerator);

                while (await contactsEnumerator.MoveNext())
                {
                    contact = contactsEnumerator.Current;
                    count++;
#if DEBUG
                    if (count % 200 == 0)
                    {
                        Console.WriteLine("QueryAsyncEnumeratorSmallBatch: processed {0} records", count.ToString());
                    }
#endif
                }
            }

            // recordcount needs be greater than 200 to ensure that more than one batch was retrieved
            // and that the async retrieval occurred.
            Assert.True(count > 200);
            Assert.NotNull(contact.Id);
        }
示例#16
0
        private List <ContratoSalesObject> ObterContratosSalesForce(ForceClient client)
        {
            var    now           = DateTime.Now;
            var    dataFiltrar   = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
            string queryContrato = "SELECT Id, " +
                                   "AccountId, " +
                                   "StartDate, " +
                                   "EndDate, " +
                                   "ContractTerm, " +
                                   "OwnerId, " +
                                   "Status, " +
                                   "ActivatedById, " +
                                   "ActivatedDate, " +
                                   "StatusCode, " +
                                   "Description, " +
                                   "IsDeleted, " +
                                   "ContractNumber, " +
                                   "LastApprovedDate, " +
                                   "CreatedDate, " +
                                   "CreatedById, " +
                                   "LastModifiedDate, " +
                                   "LastModifiedById, " +
                                   "SystemModstamp, " +
                                   "LastActivityDate, " +
                                   "LastViewedDate, " +
                                   "LastReferencedDate, " +
                                   "N_mero_contrato_interno__c " +
                                   "FROM Contract " +
                                   "Where LastModifiedDate > " + dataFiltrar.ToString("yyyy-MM-ddTHH:mm:ssZ");
            var results   = client.QueryAsync <ContratoSalesObject>(queryContrato).Result;
            var totalSize = results.totalSize;

            return(results.records);
        }
示例#17
0
        /// <summary>
        /// Demonstrates creating an Apex class in a client's Salesforce instance.
        /// </summary>
        private async Task CreateWebhookClassAsync(WebhookModel webhookModel, ForceClient client)
        {
            // First check if a class with this name already exists
            var existingWebhookClass = await client.QueryAsync <ApexClass>("SELECT Id FROM ApexClass WHERE Name = 'ActionRelayWebhook'");

            // If the class does not exist
            if (!existingWebhookClass.Records.Any())
            {
                var classBody = GetApexCode("SalesforceIntegration.ApexTemplates.WebhookTemplate.txt");

                var apexClass = new ApexClass
                {
                    ApiVersion = _apiVersion.TrimStart('v'),
                    Body       = classBody,
                    Name       = "ActionRelayWebhook"
                };

                var success = await client.CreateAsync("ApexClass", apexClass);

                if (!success.Success)
                {
                    throw new HttpException((int)HttpStatusCode.InternalServerError, "Create Failed!");
                }
            }
        }
示例#18
0
        private List <AccountSalesObject> ObterClienteSalesForce(ForceClient client)
        {
            string queryCliente   = "SELECT Id, Name, Type, ParentId, Phone, Fax, Website, Industry, Description, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, LastActivityDate, LastViewedDate, LastReferencedDate, AccountSource, SicDesc, Setor_Old__c, CNPJ__c, NomeFantasia__c, RazaoSocial__c, RamoOld__c, InscricaoEstadual__c, InscricaoMunicipal__c, Descricao__c, TipoDeEndereco__c, Logradouro__c, NumeroEndereco__c, ComplementoEndereco__c, BairroEndereco__c, CEPEndereco__c, PaisDoProprietario__c, Quantidade_de_oportunidades__c, CidadeEstado__c, PaisConta__c, Neg_cios_Fechados_este_ano__c, EstadoConta__c, Ramo__c, StatusConta__c, DonoDaConta__c, Quantidade_de_Oportunidades_Ganhas__c, de_fechamento__c, TipoDeConta__c, SAP__c, OLD_ID__c, Conta_Global__c, Target__c, Regi_o__c, Grupo_Global__c, CSM__c, E_mail__c, Data_Origem__c, E_mail_do_propriet_rio__c, Account_Status__c, Governo__c, eAcessoId__c, Company_Size__c, Or_amento_anual_de_TI__c, DSCORGPKG__Conflict__c, DSCORGPKG__DeletedFromDiscoverOrg__c,Foco_Global__c, planejamento_account__c, Possui_Account_Planning__c, Nome_Fantasia_Global__c, UniqueEntry__Account_Dupes_Ignored__c, Situa_o_cadastral__c, Propriet_rio_do_registro__c, Parental_ID__c, CNPJ_Bairro__c, CNPJ_CEP__c, CNPJ_Cidade__c, CNPJ_Complemento__c, CNPJ_Endereco_Numero__c, CNPJ_Estado__c, CNPJ_Logradouro__c, CNPJ_Situacao__c, Phone_2__c, Soma_de_todas_oportunidades__c FROM Account";
            var    resultsCliente = client.QueryAsync <AccountSalesObject>(queryCliente).Result;

            return(resultsCliente.records);
        }
        public async Task<string> Get([FromUri] string instanceUrl, [FromUri] string accessToken, [FromUri] string apiVersion, [FromUri] string query)
        {
            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var queryResults = await client.QueryAsync<object>(query);
            var response = JsonConvert.SerializeObject(queryResults);

            return response;
        }
示例#20
0
    public async Task <List <T> > QueryRecords <T>(string query)
    {
        List <T> recordList  = new List <T>();
        var      recordQuery = await Client.QueryAsync <T>(query);

        recordList.AddRange(recordQuery.Records);
        while (!string.IsNullOrEmpty(recordQuery.NextRecordsUrl))
        {
            //add a small delay
            await Task.Delay(100);

            recordQuery = await Client.QueryContinuationAsync <T>(recordQuery.NextRecordsUrl);

            recordList.AddRange(recordQuery.Records);
        }
        return(recordList);
    }
示例#21
0
        public IEnumerable <T> Get <T>(string query) where T : SystemObject
        {
            var    typeName = ((DisplayNameAttribute)typeof(T).GetCustomAttribute(typeof(DisplayNameAttribute))).DisplayName;
            string nextRecordsUrl;

            global::Salesforce.Common.Models.Json.QueryResult <T> results;

            try
            {
                var qry = string.Empty;
                if (_jobData.LastCrawlFinishTime > DateTimeOffset.MinValue)
                {
                    qry = string.Format("SELECT {0} FROM " + query + " WHERE SystemModStamp >= {1}", GetObjectFieldsSelectList(typeName), _jobData.LastCrawlFinishTime.AddDays(-2).ToString("o"));
                }
                else
                {
                    qry = string.Format("SELECT {0} FROM " + query, GetObjectFieldsSelectList(typeName)); //ToDo: Husk at fjerne LIMIT 10, dette er kun til testformål for at begrænse datasættet og dermed performance
                }

                results        = salesforceClient.QueryAsync <T>(qry).Result;
                nextRecordsUrl = results.NextRecordsUrl;
            }
            catch (Exception ex)
            {
                _log.LogError("Could not fetch Salesforce Data", ex);
                yield break;
            }

            foreach (var result in results.Records)
            {
                yield return(result);
            }

            while (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                try
                {
                    results = salesforceClient.QueryContinuationAsync <T>(nextRecordsUrl).Result;
                }
                catch (Exception ex)
                {
                    _log.LogError("Could not fetch Salesforce Data", ex);
                    yield break;
                }
                foreach (var item in results.Records)
                {
                    yield return(item);
                }

                if (string.IsNullOrEmpty(results.NextRecordsUrl))
                {
                    yield break;
                }

                //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                nextRecordsUrl = results.NextRecordsUrl;
            }
        }
示例#22
0
        public async Task <ExpandoObject> GetObjectByIdentifier(string objectName, string id)
        {
            string query = GetObjectQuery(objectName).Result + " WHERE Id = '" + id + "'";
            QueryResult <ExpandoObject> results = await _client.QueryAsync <ExpandoObject>(query);

            return(results.TotalSize > 0 ? results.Records[0] : null);
        }
示例#23
0
        private List <ContratoSalesObject> ObterTodosContratosSalesForce(ForceClient client)
        {
            var    now           = DateTime.Now;
            var    dataFiltrar   = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
            string queryContrato = "SELECT Id, AccountId, StartDate, EndDate, ContractTerm, OwnerId, Status, ActivatedById, ActivatedDate, StatusCode, Description, IsDeleted, ContractNumber, LastApprovedDate, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastActivityDate, LastViewedDate, LastReferencedDate, N_mero_contrato_interno__c FROM Contract ";
            var    results       = client.QueryAsync <ContratoSalesObject>(queryContrato).Result;

            return(results.records);
        }
示例#24
0
        public async Task QueryAsyncToList()
        {
            ForceClient client = await forceClientFixture.GetForceClient();

            List <SfContact> contacts = await client.QueryAsync <SfContact>("SELECT Id FROM Contact LIMIT 1000", batchSize : 200).ToList();

            Assert.NotNull(contacts);
            Assert.NotEmpty(contacts);
        }
        public async Task <string> Get([FromUri] string instanceUrl, [FromUri] string accessToken, [FromUri] string apiVersion, [FromUri] string query)
        {
            var client       = new ForceClient(instanceUrl, accessToken, apiVersion);
            var queryResults = await client.QueryAsync <object>(query);

            var response = JsonConvert.SerializeObject(queryResults);

            return(response);
        }
示例#26
0
        public async Task Query_Accounts_IsNotNull()
        {
            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_clientId, _clientSecret, _username, _password);

            var client  = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            var results = await client.QueryAsync <dynamic>("SELECT Id, Name, Description FROM Account");

            Assert.IsNotNull(results.records);
        }
        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>");
            }
        }
        // GET: SalesForce Leads
        public async Task<ActionResult> Leads()
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var accounts = await client.QueryAsync<LeadsViewModels>("SELECT name, email, country, state, city, description FROM Lead");

            return View(accounts.Records);
        }
示例#29
0
        // GET: /Accounts/  (SALES FORCE)

        public async Task <ActionResult> Index(string searchString)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion  = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client   = new ForceClient(instanceUrl, accessToken, apiVersion);
            var accounts = await client.QueryAsync <SalesForceAccountViewModel>("SELECT id, name, description FROM Account WHERE name = '" + searchString + "'");

            return(View(accounts.records));
        }
示例#30
0
        // GET: /Accounts/
        public async Task<ActionResult> Index()
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var contacts = await client.QueryAsync<ContactViewModel>("SELECT id, name, account.name, title, phone, email FROM Contact");

            return View(contacts.records);
        }
示例#31
0
        public async Task <ActionResult> IndexFromAccount(string accountId)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion  = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client   = new ForceClient(instanceUrl, accessToken, apiVersion);
            var contacts = await client.QueryAsync <SalesForceContactViewModel>("SELECT Id, FirstName, LastName, Title, Phone, Email From Contact WHERE AccountId= '" + accountId + "'");

            return(View(contacts.records));
        }
示例#32
0
        public async Task <ActionResult> Index()
        {
            var claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
            var accessToken    = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "urn:tokens:salesforce:accesstoken").Value.ToString();
            var instanceUrl    = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "urn:tokens:salesforce:instance_url").Value.ToString();

            var client   = new ForceClient(instanceUrl, accessToken, "v32.0");
            var contacts = await client.QueryAsync <Contact>("SELECT Id, FirstName, LastName From Contact");

            return(View(contacts.records));
        }
        /// <summary>
        /// Getting all opportunities
        /// </summary>
        /// <param name="client">Force client instance</param>
        /// <returns>List of all opportunities</returns>
        public async Task <Opportunities> GetOpportunities(ForceClient client)
        {
            Opportunities opportunities      = new Opportunities();
            var           opportunityDetails = await client.QueryAsync <Opportunity>("SELECT ID, Name, CloseDate, StageName, Type, Amount, Probability, Pricebook2Id From Opportunity ORDER BY Name ASC");

            if (opportunityDetails.Records.Any())
            {
                opportunities.AllOpportunities = opportunityDetails.Records;
            }
            return(opportunities);
        }
示例#34
0
        public async Task Query_Accounts_Continuation()
        {
            var accounts = await _client.QueryAsync <Account>("SELECT count() FROM Account");

            if (accounts.TotalSize < 1000)
            {
                await CreateLotsOfAccounts(_client);
            }

            var contacts = await _client.QueryAsync <dynamic>("SELECT Id, Name, Description FROM Account");

            var nextRecordsUrl = contacts.NextRecordsUrl;
            var nextContacts   = await _client.QueryContinuationAsync <dynamic>(nextRecordsUrl);

            Assert.IsNotNull(nextContacts);
            Assert.AreNotEqual(contacts, nextContacts);
        }
示例#35
0
        static void Main(string[] args)
        {
            var auth = new AuthenticationClient();

            auth.UsernamePasswordAsync(_clientId, _clientSecret, _username, _password).Wait();

            var client  = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            var results = client.QueryAsync <dynamic>("SELECT Id, Name, Description FROM Account");

            results.Wait();

            Console.WriteLine(results.Result.records.Count);
        }
示例#36
0
        private static async Task <List <Account> > GetAccounts()
        {
            var          client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            const string qry    = "SELECT ID, Name FROM Account";


            var results = await client.QueryAsync <Account>(qry);

            var acaunts = new List <Account>();

            acaunts.AddRange(results.Records);
            return(acaunts);
        }
示例#37
0
        public ActionResult Contact()
        {
            try
            {
                var accessToken = Session["AccessToken"].ToString();
                var apiVersion  = Session["ApiVersion"].ToString();
                var internalURI = Session["InstanceUrl"].ToString();

                var client = new ForceClient(internalURI, accessToken, apiVersion);

                EmailFormObjects model = new EmailFormObjects();

                model.VendorInfo       = client.QueryAsync <Vendor>("SELECT Name, Title, Email FROM Contact WHERE Title ='Account Executive'").Result.Records;
                model.InventoryManager = client.QueryAsync <InventoryManager>("SELECT Id, Name, CostPrice__c, OwnedPrice__c, RetailCost__c, CurrentInventory__c, InventoryOnOrder__c, SampleInHouse__c, ProductPicture__c FROM Inventory__c Where SampleInHouse__c = False").Result.Records;

                return(View(model));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Index", "InventoryManager"));
            }
        }
示例#38
0
        static void Main(string[] args)
        {
            var auth = new AuthenticationClient();
            auth.UsernamePasswordAsync(_clientId, _clientSecret, _username, _password).Wait();

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

            var results = client.QueryAsync<dynamic>("SELECT Id, Name, Description FROM Account");
            results.Wait();

            var accounts = results.Result.records;

            Console.WriteLine(accounts.Count);
        }
        public async Task Requests_CheckHttpRequestMessage_UserAgent()
        {
            var httpClient = new HttpClient(new ServiceClientRouteHandler(r => Assert.AreEqual(r.Headers.UserAgent.ToString(), UserAgent + string.Format("/{0}", ApiVersion))));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", ApiVersion, httpClient);

           try
           {
               // suppress error; we only care about checking the header
               await forceClient.QueryAsync<object>("query");
           }
           catch
           {
           }
        }
示例#40
0
        public async void Requests_CheckHttpRequestMessage_UserAgent()
        {
            var httpClient  = new HttpClient(new ServiceClientRouteHandler(r => Assert.AreEqual(r.Headers.UserAgent.ToString(), "forcedotcom-toolkit-dotnet/v30")));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", "v30", httpClient);

            try
            {
                // suppress error; we only care about checking the header
                var query = await forceClient.QueryAsync <object>("query");
            }
            catch (Exception)
            {
            }
        }
        public async void Requests_CheckHttpRequestMessage_UserAgent()
        {
            var httpClient  = new HttpClient(new ServiceClientRouteHandler(r => Assert.AreEqual(r.Headers.UserAgent.ToString(), UserAgent + string.Format("/{0}", ApiVersion))));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", ApiVersion, httpClient);

            try
            {
                // suppress error; we only care about checking the header
                await forceClient.QueryAsync <object>("query");
            }
            catch
            {
            }
        }
        public async void Requests_CheckHttpRequestMessage_UserAgent()
        {
            var httpClient = new HttpClient(new ServiceClientRouteHandler(r => Assert.AreEqual(r.Headers.UserAgent.ToString(), "forcedotcom-toolkit-dotnet/v29")));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", "v29", httpClient);

           try
           {
               // suppress error; we only care about checking the header
               var query = await forceClient.QueryAsync<object>("query");
           }
           catch (Exception)
           {
           }
        }
示例#43
0
        public async Task<ActionResult> Index()
        {

            try
            {
                var accessToken = Session["AccessToken"].ToString();
                var apiVersion = Session["ApiVersion"].ToString();
                var instanceUrl = Session["InstanceUrl"].ToString();
                var client = new ForceClient(instanceUrl, accessToken, apiVersion);
                //var cases = await client.QueryAsync<CaseModel>("SELECT CaseNumber, Status, Subject, Description FROM Case WHERE CaseNumber='" + caseID + "'");
                var cases = await client.QueryAsync<CaseModel>("SELECT Id, CaseNumber, SuppliedName, Subject, Description, Status FROM Case ORDER BY CaseNumber");
                return View(cases.records);
            }
            catch
            {
                return RedirectToAction("Error");
            }

        }
        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.");

        }
        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.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.");
        }
示例#46
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");

            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.");

        }
示例#48
0
        public async Task<ActionResult> Chart()
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            var sales = await client.QueryAsync<SaleViewModel>("SELECT Name, Total__c FROM Sale__c");
            if (User.Identity.IsAuthenticated)
            {
                var user = User.Identity;
                ViewBag.Name = user.Name;

                ViewBag.isAdmin = "No";

                if (isAdminUser())
                {
                    ViewBag.isAdmin = "Yes";
                }
                return View(sales.records);
            }
            else
            {
                ViewBag.Name = "Not Logged IN";
            }
            return View();

        }