示例#1
0
        public static async Task <JsonObject> DescribeAsync(this SalesforceClient self, string type)
        {
            var request = new ReadRequest {
                Resource = new SObject {
                    Id = "describe", ResourceName = type
                }
            };

            Response response;

            try {
                response = await self.ProcessAsync(request);
            } catch (AggregateException ex) {
                throw ex.Flatten().InnerException;
            }

            var result    = response.GetResponseText();
            var jsonValue = JsonValue.Parse(result);

            if (jsonValue == null)
            {
                throw new Exception("Could not parse Json data");
            }

            return((JsonObject)jsonValue);
        }
示例#2
0
		public void Setup ()
		{
			var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab";

			var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback"); // TODO: Move oauth redirect to constant or config
			var secret = "5754078534436456018";

			Client = new SalesforceClient (key, secret, redirectUrl);


			var users = Client.LoadUsers ();
			ISalesforceUser user;

			if (users.SingleOrDefault() == null)
			{
				user = new SalesforceUser {
					Username = "******",					
				};
				user.Properties ["instance_url"] = @"https://na15.salesforce.com/";
				user.Properties ["access_token"] = @"00Di0000000bhOg!ARYAQLWetbW6H_Lw78K0SlJ3IU7bBCeOMEhtlP8hTvaWALsYNuxfkikbC5tbAfgdNvxjSkZJ6wHVr8A5qIKM7.KeBmGnoIlg";

				Client.Save (user);
			}
			else
			{
				user = users.FirstOrDefault ();
			}

			Client.CurrentUser = user;
		}
示例#3
0
        public async static Task <IEnumerable <SearchResult> > SearchAsync(this SalesforceClient self, string search)
        {
            var request = new ReadRequest {
                Resource = new Search {
                    QueryText = search
                }
            };

            Response response;

            try {
                response = await self.ProcessAsync(request);
            } catch (AggregateException ex) {
                throw ex.Flatten().InnerException;
            }

            if (response == null)
            {
                return(null);
            }

            var result    = response.GetResponseText();
            var jsonValue = (JsonArray)JsonValue.Parse(result);

            if (jsonValue == null)
            {
                throw new Exception("Could not parse Json data");
            }

            var returnVal = jsonValue.Select(jv => new SearchResult(jv)).ToArray();

            return(returnVal);
        }
示例#4
0
		readonly Uri redirectUrl = new Uri ("com.sample.salesforce:/oauth2Callback"); // Replace with your custom callback.

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			Client = new SalesforceClient (Key, Secret, redirectUrl);
			Client.AuthenticationComplete += (sender, e) => OnAuthenticationCompleted (e);

			var users = Client.LoadUsers ();

			if (!users.Any()) {
				var intent = Client.GetLoginInterface () as Intent;
				StartActivityForResult (intent, 42);
			} else {
				LoadAccounts ();
			}

			ListView.ItemClick += (sender,e) => {
				var t = ((DataAdapter)ListAdapter)[e.Position];

				System.Diagnostics.Debug.WriteLine("Clicked on " + t.ToString());

				var intent = new Intent();
				intent.SetClass(this, typeof(DetailActivity));
				intent.PutExtra("JsonItem", "{\"attributes\": {\"type\": \"Account\", \"url\": \"/services/data/v28.0/sobjects/Account/\"}, " + 
					string.Format ("\"Id\": \"{0}\", \"Name\": \"{1}\", \"AccountNumber\": \"{2}\", \"Phone\": \"{3}\", \"Website\": \"{4}\", \"Industry\": \"{5}\"", t.Id, t.Name, t.AccountNumber, t.Phone, t.Website, t.Industry) + "}");

				StartActivity(intent);
			};
		}
示例#5
0
        static void Sync()
        {
            SalesforceClient client = new SalesforceClient(true);
            Task<IEnumerable<Case>> task = client.GetActiveCases(null);
            task.Wait();
            IEnumerable<Case> cases = task.Result;

            JobDbContext db = new JobDbContext();
            var caseNumbers = new List<string>();

            foreach (Case c in cases)
            {
                string customer = c.Contact.Name;
                string caseNumber = c.CaseNumber.Substring(4);
                string title = c.Subject;
                string status = SalesforceClient.MapStatus(c.Status);
                caseNumbers.Add(caseNumber);

                Job job = db.JobsDbSet.Where(j => j.JobNumber == caseNumber).FirstOrDefault();

                if (job == null)
                {
                    db.JobsDbSet.Add(
                        new Job()
                        {
                            Id = Guid.NewGuid().ToString(),
                            JobNumber = caseNumber,
                            AgentId = "2",
                            CustomerName = customer,
                            CustomerAddress = "One Microsoft Way, Redmond",
                            CustomerPhoneNumber = "1-206-888-8888",
                            Status = status,
                            Title = title,
                            StartTime = "13:00",
                            EndTime = "14:00"
                        });
                }
                else
                {
                    job.Title = title;
                    job.Status = status;
                    job.CustomerName = customer;
                }
            }

            db.SaveChanges();

            // handle deletions
            foreach (Job job in db.JobsDbSet)
            {
                if (caseNumbers.Contains(job.JobNumber) == false)
                {
                    db.Entry(job).Entity.Deleted = true;
                }
            }

            db.SaveChanges();

            Console.WriteLine("WebJob ran at: " + DateTime.Now.ToString());
        }
示例#6
0
        public static async Task <IEnumerable <SObject> > ReadAsync(this SalesforceClient self, ReadRequest request)
        {
            Response response;

            try {
                response = await self.ProcessAsync(request);
            } catch (AggregateException ex) {
                throw ex.Flatten().InnerException;
            }

            if (response == null)
            {
                return(Enumerable.Empty <SObject> ());
            }

            var result    = response.GetResponseText();
            var jsonValue = JsonValue.Parse(result);

            if (jsonValue == null)
            {
                throw new Exception("Could not parse Json data");
            }

            var results = jsonValue["records"];

            return(results.OfType <JsonObject> ().Select(j => new SObject(j)));
        }
        public void TestPropertiesAuthPathAndTokenPath ()
        {
			string path_auth = @"http://xamarin.com/auth";
			string path_token = @"http://xamarin.com/token";

			SalesforceClient.AuthPath = path_auth;
			SalesforceClient.TokenPath = path_token;

			string client_id = "ajde klajent";
			string client_secret = "very very secret";
			Uri uri_redirect =  new Uri("http://holisticware.net");

            SalesforceClient client = new SalesforceClient
            									(
            										client_id,
            										client_secret,
            										uri_redirect
            									);

            Assert.AreNotEqual
            			(
            				SalesforceClient.AuthPath,
							@"https://login.salesforce.com/services/oauth2/authorize"
            			);
			Assert.AreNotEqual
            			(
            				SalesforceClient.AuthPath,
							@"https://login.salesforce.com/services/oauth2/authorize"
            			);

			Assert.AreEqual(SalesforceClient.AuthPath, path_auth);
			Assert.AreEqual(SalesforceClient.TokenPath, path_token);

            return;
        }
示例#8
0
        public static async Task <bool> DeleteAsync(this SalesforceClient self, SObject sobject)
        {
            // Delete the row from the data source.
            var request  = new DeleteRequest(sobject);
            var response = await self.ProcessAsync(request);

            return(response.StatusCode == System.Net.HttpStatusCode.NoContent);
        }
示例#9
0
 public static Task <IEnumerable <SObject> > QueryAsync(this SalesforceClient self, string query)
 {
     return(self.ReadAsync(new ReadRequest {
         Resource = new Query {
             Statement = query
         }
     }));
 }
示例#10
0
        public static void Update(this SalesforceClient self, SObject sobject)
        {
            var updateRequest = new UpdateRequest(sobject);
            var result        = self.ProcessAsync(updateRequest);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                return;                 // TODO : Error handling/reporting
            }
        }
示例#11
0
        public static JsonObject Describe(this SalesforceClient self, string type)
        {
            var result = self.DescribeAsync(type);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                return(null); // TODO : Error handling/reporting
            }
            return(result.Result);
        }
示例#12
0
        public static async Task UpdateAsync(this SalesforceClient self, SObject sobject)
        {
            var updateRequest = new UpdateRequest(sobject);

            try {
                await self.ProcessAsync(updateRequest).ConfigureAwait(true);
            } catch (AggregateException ex) {
                Debug.WriteLine(ex.Message);
            }
        }
示例#13
0
        public static async Task <JsonObject> ChangesAsync(this SalesforceClient self, string type, ChangeTypes kind)
        {
            var request = new ChangesRequest {
                Resource = new SObject {
                    Id = kind.ToString().ToLowerInvariant(), ResourceName = type
                },
            };

            return(await self.ChangesAsync(request));
        }
示例#14
0
        public static bool Delete(this SalesforceClient self, SObject sobject)
        {
            var result = self.DeleteAsync(sobject);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                Debug.WriteLine("Request timed out");
                return(false);
            }
            return(result.Result);
        }
        public async void Setup ()
		{
            var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab";

            var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback");
            var secret = "5754078534436456018";

			Client = new SalesforceClient (key, secret, redirectUrl);

            // Use username/password flow for the demo.
            // This ensures we always have a valid
            // access_token for about 6 hours after this
            // method returns.
            var tokenClient = new HttpClient();
            var formData = new Dictionary<string,string> {
                {"grant_type", "password"},
                {"client_id", "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"},
                {"client_secret", "5754078534436456018"},
                {"username", "*****@*****.**"},
                {"password", "white1@needyrVpFxD3PAvjdH8svH7wLXTN98"},
            };
            var content = new FormUrlEncodedContent(formData);
            var responseTask = await tokenClient.PostAsync("https://login.salesforce.com/services/oauth2/token", content);
//            responseTask.RunSynchronously(TaskScheduler.Default);
//            responseTask.Wait();
            responseTask.EnsureSuccessStatusCode();
            var responseReadTask = await responseTask.Content.ReadAsStringAsync();
//            var rawResult = await response.Content.ReadAsStringAsync();
//            responseReadTask.RunSynchronously();
//            responseReadTask.Wait();
//            var result = JsonValue.Parse(rawResult);
            var result = JsonValue.Parse(responseReadTask);
            var users = Client.LoadUsers ();
			ISalesforceUser user;

            if (users.FirstOrDefault() == null)
			{
				user = new SalesforceUser {
					Username = "******",					
				};
				user.Properties ["instance_url"] = @"https://na15.salesforce.com";
                user.Properties ["refresh_token"] = @"5Aep861z80Xevi74eVVu3JCJRUeNrRZAcxky4UcHL1MvM2ALL3Wj_phoRIBXVC2ZcbP_BblUk39RfBF6cwu.lx3";
                user.Properties ["access_token"] = result["access_token"]; //@"00Di0000000bhOg!ARYAQN2uT2p0I.g1t03eAfogW8ZostVE61ZTMkkrOb1eiWADj9vEABhGUqqO05PQNdUA4pq60a3JTPTwyN6Z7blXpZXJbyHX";
                user.Properties ["requires_reauthentication"] = "false";
				Client.Save (user);
			}
			else
			{
				user = users.FirstOrDefault ();
			}

    			Client.CurrentUser = user;
		}
示例#16
0
        public static IEnumerable <SObject> Query(this SalesforceClient self, string query)
        {
            var result = self.QueryAsync(query);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                Debug.WriteLine("Request timed out");
                return(Enumerable.Empty <SObject> ());
            }

            return(result.Result);
        }
示例#17
0
        public static IEnumerable <SearchResult> Search(this SalesforceClient self, string search)
        {
            var result = self.SearchAsync(search);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                Debug.WriteLine("Request timed out");
                return(null);
            }

            return(result.Result);
        }
示例#18
0
        public static JsonObject Changes(this SalesforceClient self, string type, ChangeTypes kind)
        {
            var request = new ChangesRequest {
                Resource = new SObject {
                    Id = kind.ToString().ToLowerInvariant(), ResourceName = type
                }
            };

            var result = self.ChangesAsync(request);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                return(null); // TODO : Error handling/reporting
            }
            return(result.Result);
        }
示例#19
0
        /// <summary>
        /// Requests changes to all SObjects of the specified type in the given time frame.
        /// </summary>
        /// <remarks>
        /// Returns updates if passed ChangeTypes.Default.
        ///
        /// Start date must not exceed 30 days prior.
        ///
        /// Salesforce limits the result set size to 200,000 id's.
        /// If your request matches more than that, the service will
        /// return an EXCEEDED_ID_LIMIT error. To resolve this, either narrow
        /// down your time interval or sub-divide the internal into
        /// multiple requests.
        /// </remarks>
        /// <returns>The async.</returns>
        /// <param name="self">Self.</param>
        /// <param name = "request"></param>
        public static async Task <JsonObject> ChangesAsync(this SalesforceClient self, IAuthenticatedRequest request)
        {
            Response response;

            try {
                response = await self.ProcessAsync(request);
            } catch (AggregateException ex) {
                throw ex.Flatten().InnerException;
            }

            var result    = response.GetResponseText();
            var jsonValue = JsonValue.Parse(result);

            if (jsonValue == null)
            {
                throw new Exception("Could not parse Json data");
            }

            return((JsonObject)jsonValue);
        }
示例#20
0
        public static async Task <string> CreateAsync(this SalesforceClient self, SObject sobject)
        {
            var      createRequest = new CreateRequest(sobject);
            Response result;

            try {
                result = await self.ProcessAsync(createRequest).ConfigureAwait(true);
            } catch (AggregateException ex) {
                Debug.WriteLine(ex.Message);
                return(null);
            }
            var json      = result.GetResponseText();
            var jsonValue = JsonValue.Parse(json);

            if (jsonValue == null)
            {
                return(null);
            }
            sobject.Id = jsonValue["id"];
            return(sobject.Id);
        }
示例#21
0
        public static string Create(this SalesforceClient self, SObject sobject)
        {
            var createRequest = new CreateRequest(sobject);
            var result        = self.ProcessAsync(createRequest);

            if (!result.Wait(TimeSpan.FromSeconds(SalesforceClient.DefaultNetworkTimeout)))
            {
                return(null);
            }

            if (result.IsFaulted)
            {
                return(null);                // TODO: Do error reporting
            }
            var json      = result.Result.GetResponseText();
            var jsonValue = JsonValue.Parse(json);

            if (jsonValue == null)
            {
                return(null);
            }
            sobject.Id = jsonValue["id"];
            return(sobject.Id);
        }
		void InitializeSalesforce ()
		{
			const string consumerKey = "YOUR_CONSUMER_KEY";
			const string consumerSecret = "YOUR_CONSUMER_SECRET";
			var callbackUrl = new Uri (@"com.sample.salesforce:/oauth2Callback");

			// Creates our connection to salesforce.
			Client = new SalesforceClient (consumerKey, consumerSecret, callbackUrl);
			Client.AuthenticationComplete += (sender, e) => OnAuthenticationCompleted (e);

			// Get authenticated users from the local keystore
			var users = Client.LoadUsers ();
			if (!users.Any ()) {
				// Begin OAuth journey
				StartAuthorization (); 
			} else {
				// Immediately go to accounts screen
				LoadAccounts (); 
			}
		}