Mail Merge sendgrid c# - c#

Using the SendGrid C# API. I have spent several hours looking through the documentation here and more frustratingly here. I have searched through several SO posts and messed around with the code but to no avail.
Basically I have an email template that begins like so:
--------------------------
{RecipientName},
here is the rest of the email body...
--------------------------------
I simply want every instance of {RecipientName} to be the first name of the person receiving the email. I see there is a Personalization class but there doesn't seem to be any documentation or actual examples of how to use it for this purpose.
Here is the code which works great for actually sending the email to the recipients:
List<EmailAddress> allRecipients = new List<EmailAddress>();
for (int i = 0; i < notice.AllRecipients.Count; i++)
{
_Logger.Info("processing recipient number " + i);
Employee e = _companyLogic.GetEmployeeByEmployeeId(notice.AllRecipients[i].EmployeeId);
EmailAddress email = new EmailAddress(e.EmailAddress, e.FirstName + " " + e.LastName);
allRecipients.Add(email);
}
msg.AddTos(allRecipients);
It would seem the perfect place to add the Substitution would be in the for loop. But I am not seeing how this can be accomplished.

I believe this is the documentation you need: https://github.com/sendgrid/sendgrid-csharp/blob/master/USE_CASES.md#transactional_templates

Related

C# - Get Direct Reports under another manager's Direct Reports list

I've been trying to figure out how to do this but I'm always met with a bump on the road. What I'm trying to do is to get the reporting people under my manager's direct reports list; so for example, "Alex" is a direct report under my manager, however, when you go into his organization you see that he also has direct reports that report directly to him - I am trying to get "those" reports not only from his side but from anyone else in the list that has direct reports as well. What is needed for me to effectively execute that idea? Many thanks!
This is my code to only get Direct Reports under my manager tree:
public void GetManagerDirectReports()
{
Application App = new Application();
AddressEntry currentUser = App.Session.CurrentUser.AddressEntry;
if (currentUser.Type == "EX")
{
ExchangeUser manager = currentUser.GetExchangeUser().GetExchangeUserManager();
if (manager != null)
{
AddressEntries addrEntries = manager.GetDirectReports();
if (addrEntries != null)
{
foreach (AddressEntry addrEntry in addrEntries)
{
ExchangeUser exchUser = addrEntry.GetExchangeUser();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Name: "
+ exchUser.Name);
sb.AppendLine("Title: "
+ exchUser.JobTitle);
sb.AppendLine("Department: "
+ exchUser.Department);
sb.AppendLine("Email: "
+ exchUser.PrimarySmtpAddress);
Debug.WriteLine(sb.ToString());
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}
}
}
}
I opted to go ahead and use LDAP instead of Microsoft's EWS because I saw it uses _ComObject and I don't believe that will work with what I need it to work for. Essentially, I created a master load class and then a sub-class to handle LDAP syntax which would give me the emails of all managers who have direct reports. Something I found useful while doing my research is this filter string which came in quite handy in my time of need (where "cn" is the manager's name):
searcher = new DirectorySearcher
{
Filter = "(&(objectClass=user)(objectCategory=person)(manager=" + cn + ",OU=Unit,OU=People,DC=my,DC=domain,DC=com))"
};
searcher.PropertiesToLoad.Add("DirectReports");
searcher.PropertiesToLoad.Add("mail");
Hope this can serve of some use to coming questions related to this in the future.

Google map API- display alternative routes with distance on info window

I am using google map and I am bit stuck at one point. I want to display alternative routes for my source and destination point. Currently I am using the code which is working perfectly and displaying correct result but the only the problem is that this code displaying infowindow for all routes with distance and time. And it needs to be differently colored for alternative routes..
Please help me out.
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true,
optimizeWaypoints
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(request,
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var step=2;
for (var i = 0, len = response.routes.length; i < len; i++) {
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response,
routeIndex: i
});
stepDisplay.setContent(response.routes[i].legs[i].steps[step].distance.text + "<br>" + response.routes[i].legs[i].steps[step].duration.text + " ");
stepDisplay.setPosition(response.routes[i].legs[i].steps[step].end_location);
stepDisplay.open(mapObject);
}
} else {
$("#error").append("Unable to retrieve your route<br />");
}
});
I analyzed your code as much as I could (not really that experienced with JS). So I'm gonna go on ahead and try to address the concerns on your comment.
InfoWindow for all routes
Based on the code snippet you provided, the for loop already iterates over the response.routes. In here, I see you are already setting an InfoWindow (showing distance and time), based on the route:
stepDisplay.setContent(response.routes[i].legs[i].steps[step].distance.text + "<br>" + response.routes[i].legs[i].steps[step].duration.text + " ");
stepDisplay.setPosition(response.routes[i].legs[i].steps[step].end_location);
stepDisplay.open(mapObject);
-- It made me wonder as to why you still specified this as a problem. Then it hit me, is it that the only InfoWindow shown here is for the last route? If so, your probably not setting it to the map properly. So I looked around and found this JSFiddle Sample where I can try out if it's possible to show multiple InfoWindows. I just added the code where you include an InfoWindow like so:
directionsDisplay.setDirections(response);
var step = 1;
var infowindow2 = new google.maps.InfoWindow();
infowindow2.setContent(response.routes[0].legs[0].steps[step].distance.text + "<br>" + response.routes[0].legs[0].steps[step].duration.text + " ");
infowindow2.setPosition(response.routes[0].legs[0].steps[step].end_location);
infowindow2.open(map);
-- when you open the JSFiddle Sample above, just add the code snippet like above, below the directionsDisplay.setDirections(response); and it will show something like this:
[Multiple InfoWindow Map Screenshot][1]
Route lines should be different colors
For this concern, I found a similar post here. From the answer:
You can specify the color of the line when you create the DirectionsRenderer, using the optional DirectionsRendererOptions struct.
Here's a part of the snippet in the answer:
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "red"
}
});
I tried it out and this is how it looked like:
[Route Different Color Screenshot][2]
How you set the color of each route is up to you though.
Hope this helps. Good luck. :)
PS: Included the Screenshot links in the comments.*

can't get the body/attachments of new mails in outlook

I've developed an Outlook plugin using C# where for each new mail received, i get(and save) the sender/subject/the body of email & the attachments. Well, the last 2 gave me a headache. I can see the sender and the subject of the new mail but for the body&attachments it seems that is a problem. I've used NewMailEx for getting the new mails in Inbox. The function looks like this:
private void Application_NewMailEx(string EntryIDCollection)
{
string[] entryIdArray = EntryIDCollection.Split(',');
foreach (string entryId in entryIdArray)
{
try
{
Outlook.MailItem item = (Outlook.MailItem)Application.Session.GetItemFromID(EntryIDCollection, null);
string subj = item.Subject; //works
string to = item.To; //works
string bec = item.BCC; //does not work but dont care
string body = item.Body; //DOES NOT SAVE THE BODY OF THE NEW MAIL RECEIVED
string final = "Sender: " + item.SenderEmailAddress + "\r\n" + "Subject: " + subj + "\r\n" + "BCC: " + bec + "\r\n" + "TO: " + to + "\r\n\n" + "Body: " + body + "\r\n\n";
System.IO.File.AppendAllText(#"D:\tmp\atr.txt", final);
//the result of item.attachments.count is always 0 , even though I've
//sent mails with a different number of attachments. So the if
//statement is false
if (item.Attachments.Count > 0)
{
for (int i = 1; i <= item.Attachments.Count; i++)
{
item.Attachments[i].SaveAsFile(#"D:\tmp\" + item.Attachments[i].FileName);
}
}
Marshal.ReleaseComObject(item);
}
catch (System.Exception e)
{
MessageBox.Show(e.Message);
}
}
}
Where does the Item variable come from? You need to initialize it using Application.Session.getItemfromID().
I'm writing in VBA, so I feel like posting my code here would be a faux pas, but I have come to a solution using similar Object Libraries from the Outlook application that I think transfer well to your C++ intentions.
First of all, switching to POP3 certainly fixes this problem, but you're stuck using POP3, which is only ideal from a programming standpoint.
The solution I have found follows this algorithm:
//Generate Outlook MailItem Object, "item"
//If item.DownloadState is not 1,
//item.Display
//item.Close(1)
//Perform end of code operations
//Call Function that is identical to Application_NewMailEx but is not Application_NewMailEx because Application_NewMailEx is a function that is thrown during the incoming mail event.
//Else,
//Perform Intended Code
You see how calling a function identical to Application_NewMailEx creates a kind of loop because if item.DownloadState is not 1, you'll be calling that function again? I get that this isn't the most ideal coding practice, but I have scoured the internet and Outlook Application and Outlook Object Library experts have no idea how to solve this problem any other way (in fact, no one even proposes THIS solution)
For my full VBA Solution Check out:
https://superuser.com/questions/894972/outlook-strange-item-attachments-error/990968#990968

How to get Google Plus's post data ( likes - shares - comments )?

Using C# , I want to read the Shares , Comments and Likes of a Google + post like this https://plus.google.com/107200121064812799857/posts/GkyGQPLi6KD
That post is an activity. This page includes infomation on how to get infomation about activities. This page gives some examples of using the API. This page has downloads for the Google API .NET library, which you can use to access the Google+ APIs, with XML documentation etc.
You'll need to use the API Console to get an API key and manage your API usage.
Also take a look at the API Explorer.
Here's a working example:
Referencing Google.Apis.dll and Google.Apis.Plus.v1.dll
PlusService plus = new PlusService();
plus.Key = "YOURAPIKEYGOESHERE";
ActivitiesResource ar = new ActivitiesResource(plus);
ActivitiesResource.Collection collection = new ActivitiesResource.Collection();
//107... is the poster's id
ActivitiesResource.ListRequest list = ar.List("107200121064812799857", collection);
ActivityFeed feed = list.Fetch();
//You'll obviously want to use a _much_ better way to get
// the activity id, but you aren't normally searching for a
// specific URL like this.
string activityKey = "";
foreach (var a in feed.Items)
if (a.Url == "https://plus.google.com/107200121064812799857/posts/GkyGQPLi6KD")
{
activityKey = a.Id;
break;
}
ActivitiesResource.GetRequest get = ar.Get(activityKey);
Activity act = get.Fetch();
Console.WriteLine("Title: "+act.Title);
Console.WriteLine("URL:"+act.Url);
Console.WriteLine("Published:"+act.Published);
Console.WriteLine("By:"+act.Actor.DisplayName);
Console.WriteLine("Annotation:"+act.Annotation);
Console.WriteLine("Content:"+act.Object.Content);
Console.WriteLine("Type:"+act.Object.ObjectType);
Console.WriteLine("# of +1s:"+act.Object.Plusoners.TotalItems);
Console.WriteLine("# of reshares:"+act.Object.Resharers.TotalItems);
Console.ReadLine();
Output:
Title: Wow Awesome creativity...!!!!!
URL:http://plus.google.com/107200121064812799857/posts/GkyGQPLi6KD
Published:2012-04-07T05:11:22.000Z
By:Funny Pictures & Videos
Annotation:
Content: Wow Awesome creativity...!!!!!
Type:note
# of +1s:210
# of reshares:158

Setting up 3DCart API with a C# App

I have been trying to create an application to go through our database at a set interval and update/add any new items to 3DCarts database. Their code example uses soap in an xml file to send 1 request per call. So I need to to be able to generate the xml I need with the items information on the fly before sending it. I have done hardly anything with XML files like this and cannot figure out how to create the chunk of code I need and send it. One method that has been suggested is create a file but still executing has been a problem and would be very inefficient for a large number of items. Here is what I have so far
sqlStatement = "SELECT * FROM products WHERE name = '" + Convert.ToString(reader.GetValue(0)) + "'";
ServiceReferenceCart.cartAPIAdvancedSoapClient bcsClient = new ServiceReferenceCart.cartAPIAdvancedSoapClient();
ServiceReferenceCart.runQueryResponse bcsResponse = new ServiceReferenceCart.runQueryResponse();
bcsClient.runQuery(storeUrl, userKey, sqlStatement, callBackURL);
string result = Convert.ToString(bcsResponse);
listBox1.Items.Add(result);
EDIT: Changed from sample code block to current code block as I got a service reference setup finally. They provide no details though for using the functions in the reference. With this bcsResponse is just a blank, when I try adding .Body I have the same result but when I add .runQuery to the .Body I get a "Object reference not set to an instance of an object." error. As I have said I have not messed with service references before.
I hope I have explained well enough I just really have not worked with this kind of stuff before and it has become extremely frustrating.
Thank you in advance for any assistance.
I actually ended up figuring this out after playing around with it. Here is what I did to get the reference to work. This may have been easy for anyone who have used the references before but I have not and have decided to post this in case anyone else has this problem. The SQL can be SELECT, ADD, UPDATE and DELETE statements this was to see if the sku was listed before updating/adding.
//Will be using these multiple times so a variable makes more sense
// DO NOT include http:// in the url, also id is not shown in their
//database layout pdf they will give but it is the sku/product number
string sqlStatement = "SELECT id FROM products WHERE id = '" + Convert.ToString(reader.GetValue(0)) + "')))";
string userKey = "YourKeyHere";
string storeUrl = "YourStoresURLHere";
// Setting up instances from the 3DCart API
cartAPIAdvancedSoapClient bcsClient = new cartAPIAdvancedSoapClient();
runQueryRequest bcsRequest = new runQueryRequest();
runQueryResponse bcsResponse = new runQueryResponse();
runQueryResponseBody bcsRespBod = new runQueryResponseBody();
runQueryRequestBody bcsReqBod = new runQueryRequestBody();
//assigning required variables to the requests body
bcsReqBod.storeUrl = storeUrl;
bcsReqBod.sqlStatement = sqlStatement;
bcsReqBod.userKey = userKey;
//assigning the body to the request
bcsRequest.Body = bcsReqBod;
//Setting the response body to be the result
bcsRespBod.runQueryResult = bcsClient.runQuery(bcsReqBod.storeUrl, bcsReqBod.userKey, bcsReqBod.sqlStatement, bcsReqBod.callBackURL );
bcsResponse.Body = bcsRespBod;
//adding the result to a string
string result = bcsResponse.Body.runQueryResult.Value;
//displaying the string, this for me was more of a test
listBox1.Items.Add(result);
You will also need to activate the Advanced API on your shop as you may notice there is no actual option as the pdf's say, you need to go to their store and purchase(its free) and wait for them to activate it. This took about 2 hrs for us.

Categories