-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataManager.cs
166 lines (150 loc) · 5.99 KB
/
DataManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
using Jwpro.Api.Proxy.Configuration;
using Jwpro.Api.Proxy.DTOs;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Jwpro.Api.Proxy
{
public class DataManager
{
private SalesForceConfiguration _config;
private string _token;
public DataManager(SalesForceConfiguration config = null)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
authenticate();
}
private void authenticate()
{
try
{
string postbody = $"grant_type=password&client_id={_config.Key}&client_secret={_config.Secret}&username={_config.Username}&password={_config.Password}{_config.AccountToken}";
_token = _config.AuthorizationUrl.PostToUrl(postbody).FromJson<SalesForceAuthenticationResponse>()
.access_token;
} catch(Exception ex)
{
throw new AuthenticationException("Error authenticating to Salesforce", ex);
}
}
private string getAccountBaseQuery()
{
StringBuilder query = new StringBuilder($"{_config.ApiUrl}query?q=SELECT");
PropertyInfo[] accountProperties = typeof(Account).GetProperties();
int count = 0;
foreach(PropertyInfo property in accountProperties)
{
if(property.Name.ToLower() != "attributes")
{
if(count > 0)
query.Append(",");
if(property.Name.ToLower() != "owner")
query.Append($"+{property.Name}");
else
{
PropertyInfo[] userProperties = typeof(User).GetProperties();
int userCount = 0;
foreach(PropertyInfo userProperty in userProperties)
{
if(userProperty.Name.ToLower() != "attributes")
{
if(userCount > 0)
query.Append(",");
query.Append($"+owner.{userProperty.Name}");
userCount++;
}
}
}
count++;
}
}
query.Append("+FROM+Account");
return query.ToString();
}
private SalesForceConfiguration getDefaultConfig()
{
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
return JsonConvert.DeserializeObject<SalesForceConfiguration>(
File.ReadAllText($@"{path}\salesForceConfig.json"));
}
public string AddTask(Task task)
{
if(string.IsNullOrEmpty(_token))
authenticate();
try
{
string url = $"{_config.ApiUrl}sobjects/task";
var taskJson = JsonConvert.SerializeObject(
task,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var response = url
.PostJsonToUrl(taskJson, requestFilter: req => req.AddBearerToken(_token))
.FromJson<AddTaskResponse>();
if(response.success)
{
return $"{url}/{response.id}";
}
} catch(Exception ex)
{
throw new InvalidOperationException("Error Adding Task to Sales Force", ex);
}
return null;
}
public Account GetAccount(string filter = null, string firstName = null, string lastName = null)
{
if(string.IsNullOrEmpty(_token))
authenticate();
Account account = null;
string query = getAccountBaseQuery();
try
{
if(!string.IsNullOrEmpty(filter))
{
string url = $"{query}WHERE{filter}";
var response = url.GetJsonFromUrl(requestFilter: req => req.AddBearerToken(_token))
.FromJson<ApiQueryResponse<Account>>();
if(response != null && response.TotalSize == 1)
{
account = response.Records[0];
}
}
if(account == null && !string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName))
{
string url = $"{query}+WHERE+FirstName='{firstName}' AND lastName='{lastName}'";
var response = url.GetJsonFromUrl(requestFilter: req => req.AddBearerToken(_token))
.FromJson<ApiQueryResponse<Account>>();
if(response != null && response.TotalSize == 1)
{
account = response.Records[0];
}
}
} catch(Exception ex)
{
throw new InvalidOperationException("Error Getting Provider", ex);
}
return account;
}
public IEnumerable<Account> GetAccounts(string filter = null)
{
if(string.IsNullOrEmpty(_token))
authenticate();
try
{
var url = getAccountBaseQuery();
if(!string.IsNullOrWhiteSpace(filter))
url = $"{url}WHERE{filter}";
var response = url.GetJsonFromUrl(requestFilter: req => req.AddBearerToken(_token))
.FromJson<ApiQueryResponse<Account>>();
return response.Records;
} catch(Exception ex)
{
throw new InvalidOperationException("Error Getting Salesforce Accounts", ex);
}
}
}
}