How can I get the Exchange Server programmatically from my App(C#) - exchange-server

Currently I can send email successfully through WebDAV with C#, but there is a shortage in my App that I have hard-code the Exchange Server of my outlook, so it might only works for me, if it were moved to another PC and use another outlook account, it might not work because the Exchange Server for this outlook account might not the same as mine(that's beacuse our company for different email account might assign different Exchange server), so my question is that how can I get the Exchange Server for the current Email accout dynamically. In fact I can get this Exchange Server from the outlook client when I clicked the menu item to add a new Outlook Account, but dose there exist any API for me to get this Exchange Server programmatically such as with C#?
In fact I use the following code to send Email:
using System;
using System.Net;
using System.IO;
namespace WebDavNET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
try
{
// TODO: Replace with the name of the computer that is running Exchange 2000.
string strServer = "ExchServe";
// TODO: Replace with the sender's alias.
string strSenderAlias = "sender";
// TODO: Replace with the sender's e-mail address.
string strFrom = "sender#example.com";
// TODO: Replace with the recipient's e-mail address.
string strTo = "recipient#example.com";
string strSubject = "Send Using HttpWebRequest";
string strBody = "Hello World";
string sUri;
sUri = "http://" + strServer + "/Exchange/" + strSenderAlias;
sUri = sUri + "/%23%23DavMailSubmissionURI%23%23/";
System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
DateTime mySentTime = new DateTime();
sQuery = "From: " + strFrom + "\n" +
"To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + DateTime.Now.ToString() + "\n" +
"X-Mailer: My DAV mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" + "\n" +
strBody;
// Set the credentials.
// TODO: Replace with the appropriate user credential.
NetworkCredential myCred = new NetworkCredential(#"DomainName\User", "Password");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set the headers.
HttpWRequest.Headers.Set("Translate", "f");
HttpWRequest.ContentType = "message/rfc822";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes.
HttpWRequest.Timeout = 300000;
// Set the request method.
HttpWRequest.Method = "PUT";
// Store the data in a byte array.
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send the request and get the response.
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code.
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers.
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the response stream.
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close the stream.
strm.Close();
// Clean up.
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}
As you can see in the code there is a variable named "strServer", In my App I just hard-code my Exchange Server for this variable, so my question is that dose there exist any API for me to get the Exchange Server dynamically for the specific outlook account?
Thanks!

You can use EWS(exchange Web Services) too. here is the link
You can use XML creator for creating items or requests required for operations in the link. Just go through the operations given on the link.

Related

MinIO Uploading a file with name containing especial characters issues an HTTP 403 Forbidden

Uploading an object from a .net webclient to MinIO where the object contains special characters in the name issues an HTTP 403.
This object fails: old_me_bold+19(1).jpg
This object is ok: old_me_bold19.jpg
The message is:
The request signature we calculated does not match the signature you provided. Check your key and signing method.
What is breaking in MinIO?
Encoding the Url did not work either. I also tried PresignedPutObjectAsync to create a tmp Url already signed then I did a PUT using an HttpClient with the same result. To test that this way would work, I removed the special characters from the name of the file and the client was able to send the file to MinIO.
This code fails:
public async System.Threading.Tasks.Task PutAttachementAsync(
Attachment attachment,
string bukectName,
string objectName,
string attachmentType = "application/octet-stream")
{
using (HttpClient client = new HttpClient())
{
var minioClient = GetMinioClient();
client.BaseAddress = new Uri(Config.Instance.GetConfig("MinIOURL"));
var tempFileName = CreateAttachmentTempFile(attachment, out bool virusScanResult);
if (!virusScanResult)
return;
using (FileStream str = new FileStream(tempFileName.FileAttachmentPath, FileMode.Open))
{
try
{
String signedTMPUrl = await minioClient.PresignedPutObjectAsync(bukectName, objectName, 60 * 60 * 24);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(attachmentType));
HttpResponseMessage response = await client.PutAsync(signedTMPUrl, new StreamContent(str));
if (response.IsSuccessStatusCode)
{
Log.InfoFormat("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Log.InfoFormat("Response Message Header \n\n" + response.Content.Headers + "\n");
}
else
{
Log.InfoFormat("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
catch (MinioException e)
{
Log.Error("Error occurred: " + e.Message);
}
}
}
}
That code is running from an ASP.Net application hosted in IIS. I wonder if IIS is injecting something into the header before the message goes to MinIO.
Any other file that I send to MinIO, if the name does not contain characters such as (), then the upload works always.

Email body returns a blank or null in chilkat mail

I have the following code that reads a bunch of emails from a folder. It gets the emails fine, as I can see the number of emails are correct and the header is correct as well.
However it returns nothing for the body. I do have a email with simple text as well but that too does not return anything. Part of the code is below.
any help is appreciated. the account I am reading is from a office 365 and i used the imap.Connect
(*i can read these emails from the Microsoft Outlook, so i think the issue is with my chilkat code)
Chilkat.MessageSet messageSet = imap.Search(#"ALL", fetchUids);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Fetch the email headers into a bundle object:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Sort the email bundle by date, recipient, sender, or subject:
bool ascending = true ; bool descending = true;
bundle.SortByDate(ascending);
//bundle.SortByDate(descending);
// To sort by recipient, sender, or subject, call
// SortBySender, SortByRecipient, or SortBySubject.
// Display the Subject and From of each email.
int i = 0;
string body="";
while (i < bundle.MessageCount)
{
Chilkat.Email email = null;
email = bundle.GetEmail(i);
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + email.GetHeaderField("Date");
//Debug.WriteLine(email.GetHeaderField("Date"));
//Debug.WriteLine(email.Subject);
txtOutput.Text = txtOutput.Text + Environment.NewLine + email.From;
//Debug.WriteLine(email.From);
//Debug.WriteLine("--");
if (email.HasHtmlBody())
{
body = email.GetHtmlBody() + String.Empty;
}
else if (email.HasPlainTextBody())
{
body = email.GetPlainTextBody() + String.Empty;
}
else
{
body = email.Body + String.Empty;
}
txtOutput.Text = txtOutput.Text + Environment.NewLine + body.Trim() ;
i = i + 1;
}
You downloaded headers-only:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
Of course there is no body...

Java Fitbit by using FITBIT4j --approach through pin method

FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitAPIClientService<FitbitApiClientAgent> fitbit = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl,
credentialsCache), clientConsumerKey, clientSecret,
credentialsCache, entityCache, subscriptionStore);
final LocalUserDetail localUser = new LocalUserDetail("1");//user means my userid
String url = fitbit.getResourceOwnerAuthorizationURL(localUser, "");
System.out.println("Open " + url);
System.out.print("Enter PIN:");//What is this? Is this the userid?
String pin = readFromUser();
APIResourceCredentials creds = fitbit
.getResourceCredentialsByUser(localUser);
creds.setTempTokenVerifier(pin);
fitbit.getTokenCredentials(localUser);
// you can save the access_token here to reuse later
// System.out.println("Your access_token: " + creds.getAccessToken());
// System.out.println("Your access_token_secret: " + creds.getAccessTokenSecret());
UserInfo profile = fitbit.getClient().getUserInfo(localUser);
System.out.println(profile.getDisplayName() + ", member since "
+ profile.getMemberSince());
LocalDate date = FitbitApiService.getValidLocalDateOrNull("2012-06-01");
Sleep sleep = fitbit.getClient().getSleep(localUser,
FitbitUser.CURRENT_AUTHORIZED_USER, date);
System.out.println("Your sleep on " + date + ": inBed=" + sleep.getSummary().getTotalTimeInBed() + " asleep=" + sleep.getSummary().getTotalMinutesAsleep());
Error:
com.fitbit.api.FitbitAPIException: 500: Something is broken. Please
post to the group so the Fitbit team can investigate.
{"errors":[{"errorType":"request","fieldName":"500","message":"Oops!
An unexpected error occurred. If it continues please report it at
help.fitbit.com."}],"success":false}
How to proceed with pin based approach ? What is the pin ? How to get the pin for a fitbit user? (as Iam a fitbit user).

square Connect API Batch

I am using .NET to list the payments from my square account.
I am able to get a list of the payments, but to get the description field I have to go one level deeper and make http end point calls for each payment. This is time consuming.
Question: Can anyone provide me with a sample in Visual C# or Java to make batch calls for retrieving payments (using multiple payment id's)?
Your help is greatly appreciated.
Thanks,
Prashant
#Andrew - Here's what I am using, I am just not sure how to add the headers for batch payments retrieval.
string res = string.Empty;
string qs = string.Empty;
foreach (string s in parameters.Keys)
{
if (qs == string.Empty)
qs = "?";
else
qs += "&";
qs += s + "=" + parameters[s];
}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_connectUrl + "/" + command + qs); ///
request.Proxy = null;
request.Headers.Add("Authorization", "Bearer " + _accessToken);// ");
request.ContentType = "application/json";
request.Method = method; // "GET";
try { HttpWebResponse responseGet = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(responseGet.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
responseGet.Close();
request = null;
return output.ToString();
}
catch (Exception exp)
Looks like I've been able to answer my own query.
We need to be able to send the following POST to the HTTP Endpoint
{"requests":[{"method":"GET","relative_path":"/v1/me/payments/<payment_id>","access_token":"XXXX","request_id":"1"},{"method":"GET","relative_path":"/v1/me/payments/<payment_id>","access_token":"XXXX","request_id":"2"}]}
the following code in .NET achieves the above
//Convert the body of request into a byte array
byte[] byteArray = Encoding.UTF8.GetBytes(body);
//Set the length
request.ContentLength = byteArray.Length;
//Write the body to the request by using a datastream
//This line never returns....
Stream datastream = request.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
And that's all there is to it.
Hope this helps anyone is is set out to use the batch mode.
Thanks

Tile notification for windows phone - invalid XML payload -

I send two push notifications a toast and a tile (just a count)
the toast gets received:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Toast><wp:Text1></wp:Text1><wp:Text2>asdf</wp:Text2><wp:Param></wp:Param></wp:Toast></wp:Notification>
the tile does not:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Tile><wp:BackgroundImage></wp:BackgroundImage><wp:Count>122</wp:Count><wp:Title></wp:Title><wp:BackBackgroundImage></wp:BackBackgroundImage><wp:BackTitle></wp:BackTitle><wp:BackContent></wp:BackContent></wp:Tile></wp:Notification>
This is the xml i provide and I keep getting format errors. Is there something wrong in the format?
Your tile format should be like
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
Sending tile notification code.It will work for me. If any query than let me know
protected void ButtonSendTile_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the tile notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the tile message.
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}

Resources