public async Task CreateLotsOfAccounts(ForceClient forceClient)
        {
            var account = new Account { Name = "Test Account", Description = "New Account Description" };

            for (var i = 0; i < 1000; i++)
            {
                account.Name = "Test Account (" + i + ")";
                await forceClient.CreateAsync("Account", account);
            }
        }
예제 #2
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 + "%'");

        }
예제 #3
1
        // 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);
        }
예제 #5
0
        private bool HandleExpiredRequest(ForceClient forceClient, FileRequest fileRequest)
        {
            // Delete expired file requests
            bool isExpired = false;

            if (!string.IsNullOrEmpty(fileRequest.FileUrl__c))
            {
                System.Uri url         = new System.Uri(fileRequest.FileUrl__c);
                string     queryString = System.Net.WebUtility.UrlDecode(url.Query);
                string[]   queryParts  = queryString.Split('&');
                foreach (string queryPart in queryParts)
                {
                    if (queryPart.StartsWith("se="))
                    {
                        System.DateTime endDateTime = System.DateTime.Parse(queryPart.Replace("se=", ""));
                        if (endDateTime < System.DateTime.Now)
                        {
                            // Delete SalesForce record
                            isExpired = true;
                            bool isSuccess = forceClient.DeleteAsync("FileRequest__c", fileRequest.Id).Result;
                        }
                        break;
                    }
                }
            }
            return(isExpired);
        }
예제 #6
0
        public async Task<ActionResult> Edit(string Id, string SuppliedName, string Question, string Subject)
        {


            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();
            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            CaseModel1 caseModel = new CaseModel1() { Status = "Closed"};
            await client.UpdateAsync("Case", Id, caseModel);
            //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 WHERE id='" + Id + "'");
            QuestionDBContext db = new LegendaryQuestion.Models.QuestionDBContext();
            List<int> list = new List<int>();
            try
            {
                var I = db.Queries.Where(c => c.Name == SuppliedName && c.Question == Question && c.Subject == Subject).Select(c => c.ID);
                foreach (var x in I)
                {
                    list.Add(x);
                }
                Query query = db.Queries.Find(list[0]);
                db.Queries.Remove(query);
                db.SaveChanges();
            }
            catch { }
            return RedirectToAction("Index");
        }
        public async void RunJob_NullObjectName_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.RunJobAsync(null, BulkConstants.OperationType.Insert, new List <ISObjectList <SObject> >());

            // expects exception
        }
예제 #8
0
        public static void AddLinkToSalesforce(ForceClient forceClient, SharepointFile fileInfo, string url)
        {
            ImageLink__c linkToAdd = new ImageLink__c()
            {
                Name = fileInfo.FileName, Contact__c = fileInfo.ParentId, File_Name__c = fileInfo.FileName, URL__c = url
            };

            // Wait synchronously for the result
            // TODO: maybe offer async option in an overload
            Task <SuccessResponse> response = forceClient.CreateAsync("ImageLink__c", linkToAdd);

            response.Wait();
            SuccessResponse result = response.Result;

            if (result.Success)
            {
                Log("uploaded link successfully to salesforce:\n ID: " + result.Id + " \n filename: " + fileInfo.FileName + " \n ContactID: " + fileInfo.ParentId);
            }
            else
            {
                log.Error("Error inserting link: " + fileInfo.FileName + " for: " + fileInfo.ParentId);
                log.Error(result.Errors.ToString());
                //TODO maybe throw exception
            }
        }
        public async void CreateJobBatchAsync_NullJobId_ArgumentNullException()
        {
            IForceClient client = new ForceClient("test", "test", "v32");
            await client.CreateJobBatchAsync((string)null, new SObjectList <SObject>());

            // expects exception
        }
예제 #10
0
        public async Task <ActionResult> Update(OpportunityLineItem input)
        {
            if (ModelState.IsValid)
            {
                SalesForceResponse sfResponse = new SalesForceResponse();
                ForceClient        client     = await _client.CreateForceClient();

                // Need to provide opporunity line item id seperately
                string opportunityLineItemId = input.Id;
                input.Id = null;
                string opportunityId = input.OpportunityId;
                input.OpportunityId = null;

                // Updating the opportunity line item
                sfResponse = await _repository.UpdateOpportunityLineItem(client, opportunityLineItemId, input);

                // Managing Notification based on update operation response
                TempData["NotificationType"] = sfResponse.IsSuccess
                    ? NotificationType.Success.ToString()
                    : NotificationType.Error.ToString();
                TempData["Notification"] = sfResponse.Details;

                return(RedirectToAction("Index", "OpportunityLineitems", new { opportunityId = opportunityId }));
            }

            // Case when model has invalid data
            TempData["NotificationType"] = NotificationType.Error.ToString();
            TempData["Notification"]     = GlobalHelper.GetErrorListFromModelState(ModelState);

            return(View(input));
        }
        public async void GetBatchResultAsync_NullBatchInfo_ArgumentNullException()
        {
            IForceClient client = new ForceClient("test", "test", "v32");
            await client.GetBatchResultAsync(null);

            // expects exception
        }
        public async void PollJobAsync_NullJobId_ArgumentNullException()
        {
            IForceClient client = new ForceClient("test", "test", "v32");
            await client.PollJobAsync((string)null);

            // expects exception
        }
예제 #13
0
        public async Task GetBatchResultAsync_NullBatchId_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.GetBatchResultAsync(null, "test");

            // expects exception
        }
예제 #14
0
        public async Task <ActionResult> Add(OpportunityLineItem input)
        {
            if (ModelState.IsValid)
            {
                SalesForceResponse sfResponse = new SalesForceResponse();
                ForceClient        client     = await _client.CreateForceClient();

                // Creating the Opportunity Line item
                sfResponse = await _repository.CreateOpportunityLineItem(client, input);

                // Managing the Notification
                TempData["NotificationType"] = sfResponse.IsSuccess
                    ? NotificationType.Success.ToString()
                    : NotificationType.Error.ToString();

                TempData["Notification"] = sfResponse.Details;
                return(RedirectToAction("Index", "OpportunityLineitems", new { opportunityId = input.OpportunityId }));
            }

            // In case the model has no valid data
            TempData["NotificationType"] = NotificationType.Error.ToString();
            TempData["Notification"]     = GlobalHelper.GetErrorListFromModelState(ModelState);

            return(View(input));
        }
        public async void CreateJobBatchAsync_NullObjectList_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.CreateJobBatchAsync <SObjectList <SObject> >("testId", null);

            // expects exception
        }
        public async void CreateJobBatchAsync_NullJobInfo_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.CreateJobBatchAsync((JobInfoResult)null, new SObjectList <SObject>());

            // expects exception
        }
예제 #17
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);
        }
예제 #18
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);
        }
예제 #19
0
 private async Task ExecuteClient(Func <ForceClient, Task> useClient)
 {
     using (var client = new ForceClient(InstanceUrl, AccessToken, _apiVersion))
     {
         await useClient(client);
     }
 }
예제 #20
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);
        }
예제 #21
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);
        }
        public async void PollJobAsync_NullJobInfo_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.PollJobAsync((JobInfoResult)null);

            // expects exception
        }
예제 #23
0
        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);
        }
예제 #24
0
        internal async Task <ForceClient> GetClientForApp()
        {
            var gatewayUrl = ConfigurationManager.AppSettings["emA_RuntimeUrl"];


            AppServiceClient appServiceClient = new AppServiceClient(gatewayUrl);

            appServiceClient.SetCurrentUser(this.UserId, this.ZumoToken);
            var gateway = appServiceClient.CreateApiAppClient(new System.Uri(gatewayUrl));
            var result  = await gateway.GetAsync(String.Format("/api/tokens?api-version=2015-01-14&tokenName={0}", "salesforce"));

            var jsonString = await result.Content.ReadAsStringAsync();

            JToken json = JToken.Parse(jsonString);

            if (json["Properties"] == null)
            {
                return(null);
            }

            var accessToken = json["Properties"]["AccessToken"].ToString();
            var instanceUrl = json["Properties"]["InstanceUrl"].ToString();
            var apiVersion  = "v32.0"; //need to get dynamically

            Debug.WriteLine("App Service Token:" + jsonString);


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

            Console.WriteLine("Connected to Salesforce, apiVersion:" + apiVersion);

            return(client);
        }
예제 #25
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);
        }
예제 #26
0
        public async Task PollBatchAsync_NullJobId_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.PollBatchAsync("test", null);

            // expects exception
        }
        public async void RunJob_NullBatchList_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.RunJobAsync <List <ISObjectList <SObject> > >("Account", BulkConstants.OperationType.Insert, null);

            // expects exception
        }
        public async void CreateJobAsync_NullObjectName_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.CreateJobAsync(null, BulkConstants.OperationType.Insert);

            // expects exception
        }
        public void Init()
        {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
        public async void GetBatchResultAsync_NullJobId_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.GetBatchResultAsync("test", null);

            // expects exception
        }
        public async void PollBatchAsync_NullBatchId_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.PollBatchAsync(null, "test");

            // expects exception
        }
예제 #32
0
        public async Task <ForceClient> GetApiClient()
        {
            ISalesforceConfig config = MIFConfig.Instance as ISalesforceConfig;

            if (config is null)
            {
                throw new NotImplementedException($"{nameof(MIFConfig)} must implement {nameof(ISalesforceConfig)}.");
            }

            using AuthenticationClient auth = new AuthenticationClient
                  {
                      InstanceUrl = "https://ap16.salesforce.com"
                  };
            await auth.TokenRefreshAsync(config.SalesforceConsumerKey, config.SalesforceRefreshToken, config.SalesforceConsumerSecret);

            ForceClient client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            FieldInfo   jsonHttpClientField = client.GetType().GetField("_jsonHttpClient", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            JsonHttpClient jsonHttpClient = jsonHttpClientField.GetValue(client) as JsonHttpClient;

            FieldInfo httpClientField = jsonHttpClient.GetType().GetField("HttpClient", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            HttpClient httpClient = httpClientField.GetValue(jsonHttpClient) as HttpClient;

            HttpClientHandler handler = typeof(HttpMessageInvoker).GetField("_handler", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(httpClient) as HttpClientHandler;

            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.None;

            return(client);
        }
        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;
        }
예제 #34
0
        public async Task <ActionResult> Edit(string Id, string SuppliedName, string Question, string Subject)
        {
            var        accessToken = Session["AccessToken"].ToString();
            var        apiVersion  = Session["ApiVersion"].ToString();
            var        instanceUrl = Session["InstanceUrl"].ToString();
            var        client      = new ForceClient(instanceUrl, accessToken, apiVersion);
            CaseModel1 caseModel   = new CaseModel1()
            {
                Status = "Closed"
            };
            await client.UpdateAsync("Case", Id, caseModel);

            //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 WHERE id='" + Id + "'");
            QuestionDBContext db   = new LegendaryQuestion.Models.QuestionDBContext();
            List <int>        list = new List <int>();

            try
            {
                var I = db.Queries.Where(c => c.Name == SuppliedName && c.Question == Question && c.Subject == Subject).Select(c => c.ID);
                foreach (var x in I)
                {
                    list.Add(x);
                }
                Query query = db.Queries.Find(list[0]);
                db.Queries.Remove(query);
                db.SaveChanges();
            }
            catch { }
            return(RedirectToAction("Index"));
        }
예제 #35
0
        public void Init()
        {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
        public async void CreateJobBatchAsync_NullJobInfo_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.CreateJobBatchAsync((JobInfoResult)null, new SObjectList<SObject>());

            // expects exception
        }
        /// <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);
        }
        public async void CreateJobAsync_NullObjectName_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.CreateJobAsync(null, BulkConstants.OperationType.Insert);

            // expects exception
        }
        public async void RunJob_NullBatchList_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.RunJobAsync<List<ISObjectList<SObject>>>("Account", BulkConstants.OperationType.Insert, null);

            // expects exception
        }
        public async void RunJob_NullObjectName_ArgumentNullException()
        {
            var client = new ForceClient("test", "test", "v32");
            await client.RunJobAsync(null, BulkConstants.OperationType.Insert, new List<ISObjectList<SObject>>());

            // expects exception
        }
예제 #41
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!");
                }
            }
        }
        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 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.Query<object>(query);
            var response = JsonConvert.SerializeObject(queryResults);

            return response;
        }
        public async Task GetBasicInformationAsync_EmptyObjectName_ThrowsException()
        {
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new JsonContent(new {})};
            var httpClient = new HttpClient(new FakeHttpRequestHandler(expectedResponse));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", ApiVersion, httpClient);

            Action<ArgumentNullException> asserts = exception => Assert.That(exception.Message, Is.Not.Null);
            await AssertEx.ThrowsAsync(() => forceClient.BasicInformationAsync<object>(""), asserts);
        }
        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<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 async void GetBasicInformationAsync_EmptyObjectName_ThrowsException()
        {
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new JsonContent(new {})};
            var httpClient = new HttpClient(new FakeHttpRequestHandler(expectedResponse));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", "v29", httpClient);

            await forceClient.BasicInformationAsync<object>("");

            // expects exception
        }
        // 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);
        }
예제 #49
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);
        }
예제 #50
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
           {
           }
        }
 public async Task<IForceClient> LoginAndGetForceApi()
 {
     IForceClient forceclient = null;
     try
     {
         await Login();
         forceclient = new ForceClient(this.auth.InstanceUrl, this.auth.AccessToken, this.auth.ApiVersion);
     }
     catch (Exception ex)
     {
         throw new Exception("Can not login and get force api", ex);
     }
     return forceclient;
 }
        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)
           {
           }
        }
        public async void GetBasicInformationAsync_ValidObjectName_ReturnsParsedResponse()
        {
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = JsonContent.FromFile("KnownGoodContent/UserObjectDescribeMetadata.json")
            };
            var httpClient = new HttpClient(new FakeHttpRequestHandler(expectedResponse));
            var forceClient = new ForceClient("http://localhost:1899", "accessToken", "v29", httpClient);

            var result = await forceClient.BasicInformationAsync<ObjectDescribeMetadata>("ValidObjectName");

            Assert.IsNotNullOrEmpty(result.Name);
            Assert.AreEqual("User", result.Name);
        }
예제 #55
0
        public async Task<ActionResult> Create([Bind(Include = "CaseNumber, Type, Subject, Description")] CaseModel caseModel)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            if (caseModel.Status == null && caseModel.Subject == null)
            {
                return View(caseModel);
            }
            await client.CreateAsync("Case", caseModel);
            return RedirectToAction("Index");
            
        }
예제 #56
0
        // 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);
        }
        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);
        }
        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;

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

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

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

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
예제 #60
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");
            }

        }