I've been trying to create some code to generate non-recurring tasks in EWS. I've followed this link, unfortunately, the code to actually send the task wasn't presented. I then followed this Office Dev Center link which everyone seems to reference.
However, CreateItemType() isn't recognised.
Here's my code so far:
const string o365Server = "myO365Domain";
const string targetMailId = "myemail#test.com";
var service = new ExchangeService();
var task = new Task(service);
string itemId = null;
task.Subject = "mySubject";
task.Body = new MessageBody {BodyType = BodyType.Text, Text = "my new task"};
task.StartDate = DateTime.Now;
var createItemRequest = new CreateItemType();
createItemRequest.Items = new NonEmptyArrayOfAllItemsType();
createItemRequest.Items.Items = new ItemType[1];
createItemRequest.Items.Items[0] = task;
I've installed Microsoft Exchange WebServices 2.2.0 via Nuget and
using Microsoft.Exchange.WebServices.Data;
I just want to be able to send tasks to individual email accounts in our O365 domain. Any help would be appreciated.
Dim clientTZService As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2010)
clientTZService.Credentials = New NetworkCredential(userEmail, userPass)
clientTZService.AutodiscoverUrl(userEmail, AddressOf RedirectionCallBack)
' Create the task
Dim Task1 As Task = New Task(clientTZService)
Task1.Subject = "New Task"
Task1.Body = New MessageBody(String.Format("test"))
Task1.StartDate = DateTime.Now
Dim DueDate As DateTime = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 2)
Task1.DueDate = DueDate
Task1.Save(New FolderId(WellKnownFolderName.Tasks, "test#domain.com"))
Related
How to validate uploaded ARM Template using azure .net SDK or Fluent API ?
I want to validate my uploaded ARM template like azure portal do using azure .net SDK or Fluent API ?
For reference please see below image azure is showing message if ARM template not valid so same thing i want to implement using any .net API or REST API.
#Jim Below error I am getting:
If you want to validate your arm template, please refer to the following steps
Create a service principal and assign Contributor role to the sp
az ad sp create-for-rbac -n "MyApp"
Install Package
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
Code
string clientId = "23****9c";
string clientSecret = "?s****/k";
string tenantDomain = "";
string subscription = "";
var creds= SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantDomain, AzureEnvironment.AzureGlobalCloud);
var restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(creds)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Build();
ResourceManagementClient managementClient = new ResourceManagementClient(restClient);
managementClient.SubscriptionId = subscription;
//Validates whether the specified template is syntactically correct and will be accepted by Azure Resource Manager..
DeploymentValidateResultInner res = await managementClient.Deployments.ValidateAsync("<groupName>", "<deployName>", new DeploymentInner()
{
Location = "",
Properties = new DeploymentProperties()
{
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
Console.WriteLine(res.Error.Message);
// get changes that will be made by the deployment if executed at the scope of resource group
WhatIfOperationResultInner res1 = await managementClient.Deployments.WhatIfAsync("<groupName>", "<deployName>", new DeploymentWhatIf() {
Location="",
Properties= new DeploymentWhatIfProperties() {
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
foreach (var change in res1.Changes) {
//
}
I like that the accepted answer adds the "what if" to validation. However, Microsoft.Azure.Management.ResourceManager is deprecated, and it took me a bit to figure out a way to validate an ARM template using the replacement library: Azure.ResourceManager.
Here's a code snippet that provides template validation using the new library (it doesn't include the what-if call):
var credential = new DefaultAzureCredential();
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new ArmClient(credential, subscriptionId);
var deploymentContent = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(templateContent),
Parameters = BinaryData.FromObjectAsJson(new
{
hostingPlanName = new
{
value = hostingPlanName
},
webSiteName = new
{
value = webAppName
},
skuName = new
{
value = webSkuName
},
skuCapacity = new
{
value = webSkuCapacity
},
})
});
var resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(SubscriptionId!, resourceGroupName);
// This ArmDeploymentResource resource may or may not exist, but it doesn't matter - it's just a placeholder for validation
var deploymentResourceId = ArmDeploymentResource.CreateResourceIdentifier(resourceGroupId, deploymentName);
var armDeployment = client.GetArmDeploymentResource(deploymentResourceId);
var validateOperation = await armDeployment.ValidateAsync(WaitUntil.Completed, toValidate, _cancellationToken);
var validateResult = validateOperation.Value;
if (validateResult.Error != null)
{
_logger.LogEndOperation(loggerOpKey, false, validateResult.Error.Message ?? "Validation errored");
_logger.LogError(JsonConvert.SerializeObject(validateResult.Error, Formatting.Indented));
return false;
}
// Log this if you want:
string deploymentDetails = $"Deployment: {deploymentName} ProvisioningState:{validateResult.Properties.ProvisioningState}\n"
+ $" started:{validateResult.Properties.Timestamp} duration:{validateResult.Properties.Duration}\n"
+ $" correlationId:{validateResult.Properties.CorrelationId}\n"
+ $" outputs:{JsonConvert.SerializeObject(validateResult.Properties.Outputs)}";
bool succeeded = validateResult.Properties.ProvisioningState == "Succeeded";
return succeeded;
Im trying to make PatternedRecurrence's so that a user can choose from 3 options, weekly, biweekly and monthly. However the code i've tried dosen't appear to be working, it posts to the API without error but does not appear anywhere on the test calendar, where as a non patterned one does appear on the calendar. THis is the code i've tried to set a weekly pattern.
NewEvent.Recurrence = new PatternedRecurrence();
NewEvent.Recurrence.Range = new RecurrenceRange();
NewEvent.Recurrence.Pattern = new RecurrencePattern();
NewEvent.Recurrence.Pattern.DaysOfWeek = new List<Microsoft.Office365.OutlookServices.DayOfWeek>();
NewEvent.Recurrence.Range.Type = RecurrenceRangeType.EndDate;
NewEvent.Recurrence.Range.EndDate = start.AddYears(2).ToString();
NewEvent.Recurrence.Range.StartDate = start.ToString();
NewEvent.Recurrence.Pattern.Interval = 1;
NewEvent.Recurrence.Pattern.Type = RecurrencePatternType.Weekly;
NewEvent.Recurrence.Pattern.FirstDayOfWeek = Microsoft.Office365.OutlookServices.DayOfWeek.Monday;
if (StartDay.ToString() == "Monday")
{NewEvent.Recurrence.Pattern.DaysOfWeek.Add(Microsoft.Office365.OutlookServices.DayOfWeek.DayOfWeek.Monday); }
else if (StartDay.ToString() == "Tuesday")
{ NewEvent.Recurrence.Pattern.DaysOfWeek.Add(Microsoft.Office365.OutlookServices.DayOfWeek.DayOfWeek.Tuesday); }
... for the rest of the days of the week
I've looked up the referances for this but they aren't very helpful, although i'd think what i've written makes enough sense to work, apart from all them if statements, I couldn't figure a better way to convert from System.DayOfWeek to Microsoft.Office365.OutlookServices.DayOfWeek
Did you have code to catch the execption? What's the response of the Request? We can use the Fiddler to track the response, if the recurrent appointment was created successfully, the response would contains the detail information about recurrence.
For example, here is a successful response:
{"#odata.context":"https://outlook.office.com/api/v2.0/$metadata#Me/Events/$entity","#odata.id":"https://outlook.office.com/api/v2.0/Users('7f4f5db6-539f-45d2-b133-26a25318269a#60c1366c-1b8f-4fcd-a190-058bfd47bcb4')/Events('AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS_cT5eu67AiEA77BwB6jcCHf_RcRZqcWLJUEog7AAACAQ0AAAB6jcCHf_RcRZqcWLJUEog7AAAAA_dGpgAAAA==')","#odata.etag":"W/\"eo3Ah3/kXEWanFiyVBKIOwAAA+SaVA==\"","Id":"AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS_cT5eu67AiEA77BwB6jcCHf_RcRZqcWLJUEog7AAACAQ0AAAB6jcCHf_RcRZqcWLJUEog7AAAAA_dGpgAAAA==","CreatedDateTime":"2016-01-21T23:45:06.8317353-08:00","LastModifiedDateTime":"2016-01-21T23:45:07.0973601-08:00","ChangeKey":"eo3Ah3/kXEWanFiyVBKIOwAAA+SaVA==","Categories":[],"OriginalStartTimeZone":"Pacific Standard Time","OriginalEndTimeZone":"Pacific Standard Time","ResponseStatus":{"Response":"Organizer","Time":"0001-01-01T00:00:00Z"},"iCalUId":"040000008200E00074C5B7101A82E00800000000A996F1CFE854D101000000000000000010000000D968C3A111A417438178343B150C0974","ReminderMinutesBeforeStart":15,"IsReminderOn":true,"HasAttachments":false,"Subject":"Sync up","Body":{"ContentType":"Text","Content":"Status updates, blocking issues, and next steps"},"BodyPreview":"Status updates, blocking issues, and next steps","Importance":"Normal","Sensitivity":"Normal","Start":{"DateTime":"2016-01-22T02:30:00.0000000","TimeZone":"Pacific Standard Time"},"End":{"DateTime":"2016-01-22T03:30:00.0000000","TimeZone":"Pacific Standard Time"},"Location":{"DisplayName":"Water cooler"},"IsAllDay":false,"IsCancelled":false,"IsOrganizer":true,"Recurrence":{"Pattern":{"Type":"Weekly","Interval":1,"Month":0,"DayOfMonth":0,"DaysOfWeek":["Friday"],"FirstDayOfWeek":"Sunday","Index":"First"},"Range":{"Type":"EndDate","StartDate":"2016-01-22","EndDate":"2017-01-22","RecurrenceTimeZone":"Pacific Standard Time","NumberOfOccurrences":0}},"ResponseRequested":true,"SeriesMasterId":null,"ShowAs":"Busy","Type":"SeriesMaster","Attendees":[],"Organizer":{"EmailAddress":{"Name":"Fei Xue","Address":"fx#msdnofficedev.onmicrosoft.com"}},"WebLink":"https://outlook.office365.com/owa/?ItemID=AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS%2BcT5eu67AiEA77BwB6jcCHf%2BRcRZqcWLJUEog7AAACAQ0AAAB6jcCHf%2BRcRZqcWLJUEog7AAAAA%2BdGpgAAAA%3D%3D&exvsurl=1&viewmodel=ICalendarItemDetailsViewModelFactory"}
And Here is the code that created the recurrent appointment by weekly:
OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
async () =>
{
// Since we have it locally from the Session, just return it here.
return token;
});
Location location = new Location
{
DisplayName = "Water cooler"
};
// Create a description for the event
ItemBody body = new ItemBody
{
Content = "Status updates, blocking issues, and next steps",
ContentType = BodyType.Text
};
// Create the event object
DateTimeTimeZone start=new DateTimeTimeZone() ;
string dateTimeFormat = "yyyy-MM-ddThh:mm:ss";
string timeZone = "Pacific Standard Time";//"Eastern Standard Time";
start.DateTime = new DateTime(2016, 1, 22, 14, 30, 0).ToString(dateTimeFormat);
start.TimeZone = timeZone;
DateTimeTimeZone end = new DateTimeTimeZone();
end.DateTime = new DateTime(2016, 1, 22, 15, 30, 0).ToString(dateTimeFormat);
end.TimeZone = timeZone;
Event newEvent = new Event
{
Subject = "Sync up",
Location = location,
Start = start,
End = end,
Body = body
};
newEvent.Recurrence = new PatternedRecurrence();
newEvent.Recurrence.Range = new RecurrenceRange();
string dateFormat = "yyyy-MM-dd";
newEvent.Recurrence.Range.EndDate = DateTime.Now.AddYears(1).ToString(dateFormat);
newEvent.Recurrence.Range.StartDate = DateTime.Now.ToString(dateFormat);
newEvent.Recurrence.Range.NumberOfOccurrences = 11;
newEvent.Recurrence.Pattern = new RecurrencePattern();
newEvent.Recurrence.Pattern.Type = RecurrencePatternType.Weekly;
newEvent.Recurrence.Pattern.Interval = 1;
newEvent.Recurrence.Pattern.DaysOfWeek= new List<Microsoft.Office365.OutlookServices.DayOfWeek>() { Microsoft.Office365.OutlookServices.DayOfWeek.Friday };
// Add the event to the default calendar
await client.Me.Events.AddEventAsync(newEvent);
I am needing some assistance with paypal Parallel payments C# I have tried the Classic API and the REST API that paypal has. I am running into cycles and don't know what else to do, I have tried to get chained payments working and I have google'd and there is a huge lack of support so Im now trying Parallel. Let you know i get an 500 internal Server error..
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver((decimal?)2.00);
secondaryReceiver.email = "xxxxxxxxx#gmail.com";
secondaryReceiver.primary = false;
secondaryReceiver.paymentType = "GOODS";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver((decimal?)10.00);
primaryReceiver.email = "xxxxxxxxxxxxxxxxxx-facilitator#gmail.com ";
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
primaryReceiver.invoiceId = "123456789";
receiverList.receiver.Add(primaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
string actionType = "Pay";
string returnUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "USD";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";
payRequest.feesPayer = "PRIMARYRECEIVER";
payRequest.trackingId = "123456789";
Dictionary<string, string> paypalConfig = new Dictionary<string, string>();
paypalConfig.Add("account1.apiUsername", "xxxxxxxxxxxxxxx-facilitator_api1.gmail.com");
paypalConfig.Add("account1.apiPassword", "xxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.apiSignature", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.applicationId", "APP-80W284485P519543T");
paypalConfig.Add("IPNEndpoint", "https://www.paypal.com/cgi-bin/webscr");
paypalConfig.Add("url", "https://www.paypal.com/webscr&cmd=_express-checkout&token=");
paypalConfig.Add("endpoint", "https://api-3t.paypal.com/2.0/");
paypalConfig.Add("mode", "sandbox");
PayPal.AdaptivePayments.AdaptivePaymentsService service = new PayPal.AdaptivePayments.AdaptivePaymentsService(paypalConfig);
PayResponse response = service.Pay(payRequest);
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" + response.payKey;
}
Now as for the web.config I dont know exactly how to do it or really what to do. i Have found a few things but need of help.
Thanks
I want to select the user "test" so I can create a contact into his mailbox.
My actual problem is that it will create Contacts into my user "c-sharp".
"c-sharp" has full access on "test" mailbox
I changed the IP and the contact infos users are also only for testing.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.EnableScpLookup = false;
service.Credentials = new WebCredentials("c-sharp", "c-sharp", "domain");
service.UseDefaultCredentials = false;
IgnoreBadCertificates();
service.Url = new Uri("https://192.000.000.000/EWS/Exchange.asmx");
Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "n.a.";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
contact.DisplayName = "bau gmbh";
// Specify the company name.
contact.CompanyName = "bau";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "00000 00000";
contact.PhoneNumbers[PhoneNumberKey.MobilePhone] = "n.a.";
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "00000 00000";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("e#mail.de");
//homepage
contact.BusinessHomePage = "n.a.";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "straße";
paEntry1.City = "stadt";
paEntry1.State = "D";
paEntry1.PostalCode = "88890";
paEntry1.CountryOrRegion = "Deutschland";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
contact.Save();
Already tried this:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
I tested it with "test" and "test#domain" and "test#domain.de"
And get back this error:
"Der Name des Identitätsprinzipals ist ungültig."
Own translation: "The name of the identity principal is unvailed"
You can use Impersonation like this
ExchangeUserData exchangeUserData = new ExchangeUserData();
exchangeUserData.Username = "c-sharp";
exchangeUserData.Password = "c-sharp"; // c-sharp's Password
ExchangeService service = Service.ConnectToServiceWithImpersonation(exchangeUserData, impersonatedUserPrincipal);
Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "n.a.";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
contact.DisplayName = "bau gmbh";
// Specify the company name.
contact.CompanyName = "bau";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "00000 00000";
contact.PhoneNumbers[PhoneNumberKey.MobilePhone] = "n.a.";
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "00000 00000";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("e#mail.de");
//homepage
contact.BusinessHomePage = "n.a.";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "straße";
paEntry1.City = "stadt";
paEntry1.State = "D";
paEntry1.PostalCode = "88890";
paEntry1.CountryOrRegion = "Deutschland";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
contact.Save();
If your c-sharp user has the proper rights in Exchange, you should be able to do:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("c-sharp", "c-sharp", "domain");
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
If this doesn't work for you, please comment below or update your question (there's an "edit" link under it) with the exact behavior you are seeing including any error messages.
Problem sloved.
I found the bug... both of you are right just change:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
Into:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test#domain.de");
Thats all ...
Great thanks to you
I am using Exchange Web Services v1 to pull down unread emails from a user's mailbox like so:
//get exchange service
ExchangeServiceBinding exchangeService = new ExchangeServiceBinding();
exchangeService.Credentials = credentials; //LAN credentials of user
exchangeService.Url = URL; // http://myserver.com/ews/exchange.asmx
//REturn all properties
FindItemType findType = new FindItemType();
findType.Traversal = ItemQueryTraversalType.Shallow;
findType.ItemShape = new ItemResponseShapeType();
findType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
//Only search the inbox
DistinguishedFolderIdType[] foldersToSearch = new DistinguishedFolderIdType[1];
foldersToSearch[0] = new DistinguishedFolderIdType();
foldersToSearch[0].Id = DistinguishedFolderIdNameType.inbox;
findType.ParentFolderIds = foldersToSearch;
//Only unread emails
RestrictionType restriction = new RestrictionType();
IsEqualToType isEqualTo = new IsEqualToType();
PathToUnindexedFieldType pathToFieldType = new PathToUnindexedFieldType();
pathToFieldType.FieldURI = UnindexedFieldURIType.messageIsRead;
//Not IsRead
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "0";
constantType.Item = constantValueType;
isEqualTo.Item = pathToFieldType;
isEqualTo.FieldURIOrConstant = constantType;
restriction.Item = isEqualTo;
findType.Restriction = restriction;
FindItemResponseType findResponse = exchangeService.FindItem(findType);
ResponseMessageType[] responseMessType = findResponse.ResponseMessages.Items;
List<ItemIdType> unreadItemIds = new List<ItemIdType>();
Now I would like to find emails from a generic mailbox.
How would I go about specifying the mailbox I would like to pull emails from?