This is how I send my email:
public async System.Threading.Tasks.Task<string> SendInternalEmail(BasicEmailStructureViewModel Structure, List<string> AdditionalVariables, TenantEmailTemplate tenantEmailTemplate, TenantCommunication tenantCommunication, string ReceiverId, string ReceiverEmail, string ReceiverName, string CampaignName)
{
try
{
var client = new SendGridClient(tenantCommunication.SendgridApiKey);
var message = new SendGridMessage();
message.SetFrom(new EmailAddress(tenantCommunication.SendgridPrimarySender, tenantCommunication.SendgridPrimarySenderTag));
message.AddTo(new EmailAddress(ReceiverEmail, $"{ReceiverName}"));
message.Subject = tenantEmailTemplate.Subject;
message.SetTemplateId(tenantEmailTemplate.TemplateId);
List<string> jsonVars = new List<string>();
var subjectString = #$"""subject"":""{tenantEmailTemplate.Subject}""";
jsonVars.Add(subjectString);
foreach (PropertyInfo prop in Structure.GetType().GetProperties())
{
var variableString = #$"""{prop.Name}"":""{prop.GetValue(Structure, null)}""";
}
for (var i = 0; i < AdditionalVariables.Count; i++)
{
jsonVars.Add(AdditionalVariables[i]);
}
var flattenList = "{" + string.Join(",", jsonVars) + "}";
var emailData = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(flattenList);
message.SetTemplateData(emailData);
if (CampaignName != null && CampaignName != "")
{
message.AddCustomArg("CampaignName", CampaignName);
}
var response = await client.SendEmailAsync(message);
if (response.IsSuccessStatusCode == true)
{
return Guid.NewGuid().ToString();
}
else
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
return errorMessage;
}
}
catch(Exception e)
{
if (e != null)
{
return e.Message;
}
}
return "Invalid Email";
}
A typical input to this function will be like this:
var variableString =
#$"""verification_link"":""www.website.com?Key={Input.Key}""";
My email sends normally, however, none of the variables that I have set have been sent through. This is based roughly off the template sample on github: https://github.com/sendgrid/sendgrid-csharp/blob/main/examples/templates/templates.cs
Is there another sample I can use or what is the correct way to send variables dynamically?
I don't think that is the best way to construct the JSON for your dynamic template variables.
Would it be possible for you to build the variables as an object and then serialize them. Like:
var templateData = new {
subject = tenantEmailTemplate.Subjectm
otherVariableName = otherVariable
};
string emailData = JsonConvert.SerializeObject(templateData);
message.SetTemplateData(emailData);
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.
Let me clarify this for you.
I HAVE THIS CODE TO MAKE THE REQUEST
try
{
//Set Basic Auth
var userPagarme = test_key;
var password = "";
var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var clienteToAdd = new PagarmeCliente()
{
Name = registerUser.Name,
Code = registerUser.Code,
Document = registerUser.Document,
Type = registerUser.Type,
Document_Type = registerUser.Document_Type,
Birthdate = registerUser.Birthdate,
Email = registerUser.Email,
Gender = registerUser.Gender,
Address = new PagarmeClienteEndereco()
{
city = registerUser.City,
country = registerUser.Country,
line_1 = registerUser.Line_1,
line_2 = registerUser.Line_2,
state = registerUser.State,
zip_code = registerUser.Zip_Code
},
Phones = new PagarmeClienteTelefone()
{
mobile_phone = new PagarmeClienteTelefoneMobile()
{
area_code = registerUser.Mobile_phone_area_code,
country_code = registerUser.Mobile_phone_country_code,
number = registerUser.Mobile_phone_number
},
}
};
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
return BadRequest("\nException Caught - Message :{0} " + e.Message);
}
That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:
string idThatIWant = responseBodyJSON.id... or something like that.
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
You converted your model to JSON but you didn't use that jsonString. This could be the cause of the problem.
var respBody = JsonConvert.DeserializeObject<PagarmeCliente>(responseBody);
respBody.ID should be available if the class PagarmeCliente has the ID field you wanted populated.
I understand this might be an easy thing or C# Experts but I'm kinda struggling to get values out of a Http Response using Azure Rest API.
What I trying to do: I have a requirement to get Azure TrafficManager ProfileName, EndpointName and TargetName from Azure Rest API using C#. I managed to get to the ProfileName but unable fetch the Endpoint Name and Target Name from the response.
Each Subscription has more than one Traffic Manager Profiles and each Profile has multiple Endpoints. So, I looped the initial ProfileName Response (1st Rest API Call) in FOR Loop which is working fine and trying to get to Endpoints and Targets out (2nd Rest API Call) in below code.
Please help me fetch Endpoints and Targets from 2nd Rest API Call.
I pasted the HTTP Response that I'm getting from 2nd Rest API Call.
2nd Http Response which has Endpoint Name and Target Name
{
"id":"\/subscriptions\/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\/resourceGroups\/MyResourceGroupName\/providers\/Microsoft.Network\/trafficManagerProfiles\/MyTrafficManagerProfileName",
"name":"MyTrafficManagerProfileName",
"type":"Microsoft.Network\/trafficManagerProfiles",
"location":"global",
"tags":{},
"properties":
{
"profileStatus":"Enabled",
"trafficRoutingMethod":"Weighted",
"dnsConfig":
{
"relativeName":"MyTrafficManagerProfileName",
"fqdn":"yTafficManagerProfileName.trafficmanager.net",
"ttl":60
},
"monitorConfig":
{
"profileMonitorStatus":"Online",
"protocol":"HTTPS",
"port":443,
"path":"\/vip",
"intervalInSeconds":30,
"toleratedNumberOfFailures":3,
"timeoutInSeconds":10
},
"endpoints":
[
{
"id":"\/subscriptions\/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\/resourceGroups\/MyResourceGroupName\/providers\/Microsoft.Network\/trafficManagerProfiles\/MyTrafficManagerProfileName\/azureEndpoints\/MyEndPointName1",
"name":"MyEndPointName1",
"type":"Microsoft.Network\/trafficManagerProfiles\/azureEndpoints",
"properties":
{
"endpointStatus":"Enabled",
"endpointMonitorStatus":"Online",
"targetResourceId":"\/subscriptions\/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\/resourceGroups\/MyResourceGroupName\/providers\/Microsoft.Web\/sites\/MyTrafficManagerProfileName",
"target":"MyTargetName1",
"weight":1000,
"priority":1,
"endpointLocation":"North Central US"
}
},
{
"id":"\/subscriptions\/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\/resourceGroups\/MyResourceGroupName\/providers\/Microsoft.Network\/trafficManagerProfiles\/MyTrafficManagerProfileName\/externalEndpoints\/MyEndPointName2",
"name":"MyEndPointName2",
"type":"Microsoft.Network\/trafficManagerProfiles\/externalEndpoints",
"properties":
{
"endpointStatus":"Disabled",
"endpointMonitorStatus":"Disabled",
"target":"MyTargetName2",
"weight":1,
"priority":2,
"endpointLocation":null
}
}
]
,"trafficViewEnrollmentStatus":"Disabled"
}
}
C# Method to fetch Values from Azure Rest API
private static async Task GetTMPDetailsAsync(string token, string TeamGroupsName, string ServiceName, string SubscriptionName, string SubscriptionGUID, string SQLServerName, string SQLServerAdmin, string SQLServerAdminPasword, string DatabaseName)
{
string ResourceType = "Microsoft.Network/trafficmanagerprofiles";
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://management.azure.com/subscriptions/")
};
// Get Network Profile Name and ResourceGroupName
string URI = $"/subscriptions/{SubscriptionGUID}/resources?$filter=resourceType%20EQ%20'{ResourceType}'&api-version=2019-05-10";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic ResourcesList = JsonConvert.DeserializeObject<object>(HttpsResponse);
if (ResourcesList.value != null && !ResourcesList.value.Contains("SubscriptionNotFound"))
{
foreach (dynamic ResourceName in ResourcesList["value"])
{
string ResourceID = ResourceName.id;
string ProfileName = ResourceName.name;
string Region = ResourceName.location;
string ResourceGroupName = ResourceID.Remove(0, 67);
int CharsToRemove = 52 + ProfileName.Length;
ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);
var TMPhttpClient = new HttpClient
{
BaseAddress = new Uri("https://management.azure.com/subscriptions/")
};
// Get EndPoints and Targets
string TMPURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{ProfileName}?api-version=2018-04-01";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage EndPointResponse = await httpClient.GetAsync(TMPURI).ConfigureAwait(false);
var EndPointsResponse = await EndPointResponse.Content.ReadAsStringAsync();
dynamic ProfileList = JsonConvert.DeserializeObject<object>(EndPointsResponse);
foreach (dynamic ProfileDetailed in ProfileList)
{
string EndPointName = ProfileDetailed.properties.endpoints.name;
string Target = ProfileDetailed.properties.endpoints.properties.target;
DateTime RawDate = DateTime.Now;
string RefreshedAt = RawDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
Console.WriteLine($"'{TeamGroupsName}', '{ServiceName}', '{SubscriptionName}', '{SubscriptionGUID}', '','', '{ProfileName}', '{Region}',' {EndPointName}', {Target}, '{RefreshedAt}'");
//string SQLStatement = ($"INSERT INTO AzureCapacityUsage..TMPDetailed_New" +
// $" Select '{TeamGroupsName}', '{ServiceName}', '{SubscriptionName}', '{SubscriptionGUID}', '','', '{ProfileName}', '{Region}',' {EndPointName}', {Target}, '{RefreshedAt}'");
//SQLConnectionHelper.ExecuteTSQL(SQLServerName, SQLServerAdmin, SQLServerAdminPasword, DatabaseName, SQLStatement);
}
}
}
}
private static async Task GetTMPDetailsAsync(string token, string TeamGroupsName, string ServiceName, string SubscriptionName, string SubscriptionGUID, string SQLServerName, string SQLServerAdmin, string SQLServerAdminPasword, string DatabaseName)
{
string ResourceType = "Microsoft.Network/trafficmanagerprofiles";
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://management.azure.com/subscriptions/")
};
// Get Network Profile Name and ResourceGroupName
string URI = $"/subscriptions/{SubscriptionGUID}/resources?$filter=resourceType%20EQ%20'{ResourceType}'&api-version=2019-05-10";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic ResourcesList = JsonConvert.DeserializeObject<object>(HttpsResponse);
if (ResourcesList.value != null && !ResourcesList.value.Contains("SubscriptionNotFound"))
{
foreach (dynamic ResourceName in ResourcesList["value"])
{
string ResourceID = ResourceName.id;
string ProfileName = ResourceName.name;
string Region = ResourceName.location;
string ResourceGroupName = ResourceID.Remove(0, 67);
int CharsToRemove = 52 + ProfileName.Length;
ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);
var TMPhttpClient = new HttpClient
{
BaseAddress = new Uri("https://management.azure.com/subscriptions/")
};
// Get EndPoints and Targets
string TMPURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{ProfileName}?api-version=2018-04-01";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage EndPointResponse = await httpClient.GetAsync(TMPURI).ConfigureAwait(false);
var endPointsResponse = await EndPointResponse.Content.ReadAsStringAsync();
ProfileDetailed profiles = JsonConvert.DeserializeObject<ProfileDetailed>(endPointsResponse);
foreach (var endpoint in profiles.Properties.Endpoints)
{
Console.WriteLine($"{endpoint}");
string endpointName = endpoint.Name;
string target = endpoint.EndPointProperties.Target;
DateTime RawDate = DateTime.Now;
string RefreshedAt = RawDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
Console.WriteLine($"'{TeamGroupsName}', '{ServiceName}', '{SubscriptionName}', '{SubscriptionGUID}', '','', '{ProfileName}', '{endpointName}', {target}, '{RefreshedAt}'");
string SQLStatement = ($"INSERT INTO AzureCapacityUsage..TMPDetailed_New" +
$" Select '{TeamGroupsName}', '{ServiceName}', '{SubscriptionName}', '{SubscriptionGUID}', '','', '{ProfileName}', '{endpointName}', '{target}', '{RefreshedAt}'");
SQLConnectionHelper.ExecuteTSQL(SQLServerName, SQLServerAdmin, SQLServerAdminPasword, DatabaseName, SQLStatement);
}
}
}
}
I am using PushSharp 4.0.10.0 library to send the notification on iOS devices but it's not working. I have debugged it and found there is some ApnsConfiguration connection problem.
I am using this code to send the notificaiton:
public IHttpActionResult Notify()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpContent requestContent = Request.Content;
string errorMessage = "Some error occured.please try again later";
HttpStatusCode responseCode = HttpStatusCode.Unauthorized;
string requestParameter = requestContent.ReadAsStringAsync().Result;
string tokan = "";
var r = Request;
var header = r.Headers;
try
{
if (requestParameter != null)
{
PushNotificationModel complaintModel = JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/xyz.pem"));
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
appleCert, "xyz");
// Create a new broker
var push = new ApnsServiceBroker(config);
int DeviceType = 1;
string deviceId = Convert.ToString(complaintModel.deviceToken);
string message = "New notification!!";
Guid complaintId = complaintModel.ComplaintId;
string detail = complaintModel.detail;
try
{
//System.Web.Hosting.HostingEnvironment.MapPath("~/Images/User/")
// var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/CTPwd.pem"));
push.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
message = ex.Message;
}
else
{
message = "Not an APNSException";
}
// Mark it as handled
return true;
});
};
try
{
push.OnNotificationSucceeded += (notification) =>
{
message = "New Notification";
};
push.Start();
string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + message + '"' + ",\"sound\": \"default\"}}";
//string appleJsonFormat = "{\"aps\": {\"alert\": " + "Hello World" + ",\"sound\": \"default\"}}";
push.QueueNotification(new ApnsNotification
{
DeviceToken = deviceId,
Payload = JObject.Parse(appleJsonFormat)
});
push.Stop();
}
catch(Exception ex)
{
}
I have searched on google, but did not find any relevant answer. Is there any syntax problem ?
Thanks in advance.
Please use .P12 file format for push notification happy coding:)
Am using DocuSign Api's for signing documents. Now I have created template in DocuSign and Uploaded the PDF's there.
Now when user click's on submit, we need to auto populate docusign pdf's and I don't have custom fields added at docusign and it should be dynamic. Below is the code which is not working.
public string SignDocument()
{
var accountId = Login();
var url = GetRecipientDocumentUrl(accountId);
return url;
}
private string Login()
{
string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
DocuSign.eSign.Client.Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
var authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// find the default account for this user
foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
{
if (loginAcct.IsDefault == "true")
{
accountId = loginAcct.AccountId;
break;
}
}
if (accountId == null)
{ // if no default found set to first account
accountId = loginInfo.LoginAccounts[0].AccountId;
}
return accountId;
}
private string GetRecipientDocumentUrl(string accountId)
{
//var envelope = BuildEnvelopeDefinition(documents);
var envelope = BuildEnvelopeDefinition();
// |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
var envelopesApi = new EnvelopesApi();
//TemplateCustomFields
var summary = envelopesApi.CreateEnvelope(accountId, envelope);
//===========================================================
// Step 3: Create Embedded Signing View (URL)
//===========================================================
var viewOptions = BuildRecipientViewRequest(envelope);
var recipientView = envelopesApi.CreateRecipientView(accountId, summary.EnvelopeId, viewOptions);
return recipientView.Url;
}
private EnvelopeDefinition BuildEnvelopeDefinition()
{
TemplateRole templateRole = new TemplateRole();
templateRole.Email = "kpothireddy#firstam.com";
templateRole.Name = "Sample";
templateRole.RoleName = "1";
templateRole.Tabs = new Tabs();
templateRole.Tabs.TextTabs = new List<Text>();
Text textTab = new Text();
textTab.TabLabel = "Approved by";
textTab.Value = "Kranthi";
//textTab.XPosition = "100";
//textTab.YPosition = "100";
templateRole.Tabs.TextTabs.Add(textTab);
templateRole.ClientUserId = Guid.NewGuid().ToString();
List<TemplateRole> rolesList = new List<TemplateRole>();
rolesList.Add(templateRole);
//rolesList.Add(templateRole1);
var envelope = new EnvelopeDefinition
{
TemplateRoles = rolesList,
//TemplateId = "3b07a774-5ec5-4bbd-928a-a4b0bace2fc5",
TemplateId = "44d25c06-4fc3-4cbe-a9d0-7e0e1e3013bc", //Prefill
Status = "sent"
};
//Envelope e = new Envelope();
return envelope;
}
private RecipientViewRequest BuildRecipientViewRequest(EnvelopeDefinition envelope)
{
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = ReturnUrl,
ClientUserId = envelope.TemplateRoles.First().ClientUserId, // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = envelope.TemplateRoles.First().Name,
Email = envelope.TemplateRoles.First().Email
//UserName = envelope.Recipients.Signers.First().Name,
//Email = envelope.Recipients.Signers.First().Email
};
return viewOptions;
}
Could you please help me out.