I've been trying to update a calendar with an event but it doesn't seem to be going through. could you comment on whether I'm formatting my event correctly? I've been struggling with this for some time now.
private void InsertEventIntoCalendar()
{
List<EventAttendee> ef = new List<EventAttendee>();
ef.Add(new EventAttendee{ Email = "event#gmail.com"});
List<EventReminder> eventReminder = new List<EventReminder>();
eventReminder.Add(new EventReminder{ Minutes = 4, Method = "email"});
Event.RemindersData de = new Event.RemindersData();
de.Overrides = eventReminder;
Event newEvent = new Event
{
Attendees = ef,
Reminders = de,
Summary = "Tin Roof",
Description = "Its gonna be epic",
Location = "Claremont",
Start = new EventDateTime
{
Date = "2012-09-30",
DateTime = "2012-09-30T10:00:00.000-02:00",
TimeZone = "Cape Town"
},
End = new EventDateTime
{
Date = "2012-09-30",
DateTime = new DateTime( "2012-09-30T10:25:00.000-02:00",
TimeZone = "Cape Town"
},
};
_service.Events.Insert(newEvent, "event#gmail.com").Fetch();
}
Just in case it helps anyone else. I figured out how to solve this. I was looking for the answer as well and stumbled on a solution:
public static void GCalAdd(string summary, string location, string description,
DateTime start, DateTime end, List<EventAttendee> attendees)
{
try
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = ClientCredentials.ClientID,
ClientSecret = ClientCredentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);
var service = new CalendarService(auth);
var curTimeZone = TimeZone.CurrentTimeZone;
var dateOffsetStart = new DateTimeOffset(start, curTimeZone.GetUtcOffset(start));
var dateOffsetEnd = new DateTimeOffset(end, curTimeZone.GetUtcOffset(end));
var startTimeString = dateOffsetStart.ToString("o");
var endTimeString = dateOffsetEnd.ToString("o");
var evt = new Event
{
Summary = summary,
Location = location,
Description = description,
Start = new EventDateTime { DateTime = startTimeString },
End = new EventDateTime { DateTime = endTimeString },
Attendees = attendees,
};
var insert = service.Events.Insert(evt, "primary").Fetch();
if (insert != null)
{
MessageBox.Show(#"calendar item inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
And, to use it, do something like the following:
var ea = new EventAttendee
{
DisplayName = "testname",
Email = "email#gmail.com",
Organizer = false,
Resource = false
};
var ea2 = new EventAttendee
{
DisplayName = "testname2",
Email = "email2#gmail.com",
Organizer = true,
Resource = false
};
var list = new List<EventAttendee> { ea, ea2 };
var now = DateTime.Now;
var t30 = now + TimeSpan.FromMinutes(30);
Program.GCalAdd("test event", "test location", "test description", now, t30, list);
I think error in reminder data. Look here - Google Calendar API v3 with C# - Unable to insert recurrence exceptions.
Related
in c#:
using Opc.Ua class
1- I initialize an OPCUAServer:
myOPCUAServer = new OPCUAClass(Properties.Settings.Default.OPCServerAddress, Properties.Settings.Default.OPCServerPort, Properties.Settings.Default.OPCServerApplicationName, TagList, false, 1, Properties.Settings.Default.OPCServerNamespace);
1.1
public OPCUAClass(string serverAddres, string serverport, string serverApplicationName, Dictionary<string, TagClass> taglist, bool sessionrenewalRequired, double sessionRenewalMinutes, string nameSpace)
{
ServerAddress = serverAddres;
ServerPortNumber = serverport;
ServerApplicationName = serverApplicationName;
ApplicationName = "AB Servicio cosignas y parametros";
TagList = taglist;
SessionRenewalRequired = sessionrenewalRequired;
SessionRenewalPeriodMins = sessionRenewalMinutes;
OPCNameSpace = nameSpace;
LastTimeOPCServerFoundAlive = DateTime.Now;
InitializeOPCUAClient();
SubscribeItems();
if (SessionRenewalRequired)
{
LastTimeSessionRenewed = DateTime.Now;
RenewerThread = new Thread(renewSessionThread);
RenewerThread.Start();
}
}
1.2
public void InitializeOPCUAClient()
{
var config = new ApplicationConfiguration()
{
ApplicationName = ApplicationName,
ApplicationUri = Utils.Format(#"urn:{0}:" + ApplicationName + "", ServerAddress),
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier { StoreType = #"Directory", StorePath = #"%ProgramData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(#"CN={0}, DC={1}", ApplicationName, ServerAddress) },
TrustedIssuerCertificates = new CertificateTrustList { StoreType = #"Directory", StorePath = #"%ProgramData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
TrustedPeerCertificates = new CertificateTrustList { StoreType = #"Directory", StorePath = #"%ProgramData%\OPC Foundation\CertificateStores\UA Applications" },
RejectedCertificateStore = new CertificateTrustList { StoreType = #"Directory", StorePath = #"%ProgramData%\OPC Foundation\CertificateStores\RejectedCertificates" },
AutoAcceptUntrustedCertificates = true,
AddAppCertToTrustedStore = true
},
DiscoveryServerConfiguration = new DiscoveryServerConfiguration
{
BaseAddresses = { "opc.tcp://localhost:4840" },
ServerNames = { "UALocalDiscoveryServer" }
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 360000 },
TraceConfiguration = new TraceConfiguration()
};
config.Validate(ApplicationType.Client).GetAwaiter().GetResult();
if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
}
var application = new ApplicationInstance
{
ApplicationName = ApplicationName,
ApplicationType = ApplicationType.Client,
ApplicationConfiguration = config
};
application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();
string serverAddress = ServerAddress;
var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "/" + ServerApplicationName, useSecurity: SecurityEnabled, discoverTimeout: 15000);
OPCSession = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult();
{
var subscription = new Subscription(OPCSession.DefaultSubscription) { PublishingInterval = 1000 };
OPCSession.AddSubscription(subscription);
subscription.Create();
}
}
2- I suscribe to tags:
TagList.Clear();
foreach (string opcTag in tags_opc.Values)
{
TagList.Add(opcTag, new TagClass(opcTag, opcTag));
}
myOPCUAServer.TagList = TagList;
myOPCUAServer.SubscribeItems();
3- I try to read tags after i make sure i am suscribed
MonitoredItem item = OPCSession.Subscriptions.FirstOrDefault()
.MonitoredItems.Where(mi => mi.StartNodeId.Identifier.ToString().EndsWith(tag_opc)).FirstOrDefault();
if (item != null)
{
ReadValueId nodeToRead = new ReadValueId();
nodeToRead.NodeId = item.StartNodeId;
nodeToRead.AttributeId = Attributes.Value;
ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
nodesToRead.Add(nodeToRead);
// read current value.
DataValueCollection result = null;
DiagnosticInfoCollection diagnosticInfo = null;
OPCSession.Read(
null,
0,
TimestampsToReturn.Neither,
nodesToRead,
out result,
out diagnosticInfo);
Note out result
I am using Logix Designer software to access PLC Controller tags, as an OPC Server.
Lets suppose my OPC Server includes:
[003]My_tag.element tag
If i try to read it with C# code:
result[0].StatusCode.ToString() will be BadNodeIdUnknown
Then i use UaExpert software to write 3 into [003]My_tag.element tag
Afterwards, when i read the same tag with C# code:
result[0].StatusCode.ToString() will be Good
So it became readable after writing something into it.
Before anything, writing a value into [003]My_tag.element tag through Logix Designer does not solve anything, so it is straightly related to activating something through external software, and not tag value itself.
Any ideas?
Thanks.
I'm trying this code to create object Event using C#,
three month ago its worked and I created the events but now doesn't work, I realized that assembly has a new parameter "Event Type" but I don't know if It affects my object event
Event calendarEvent = new Event();
DateTime start = DateTime.Now;
calendarEvent.Kind = "";
calendarEvent.Summary = "test";
calendarEvent.Status = "confirmed";
calendarEvent.Visibility = "public";
calendarEvent.Description = "test";
calendarEvent.Creator = new Event.CreatorData
{
Email= "email#example.com",
Self=true
};
calendarEvent.Organizer = new Event.OrganizerData
{
Email = "email#example.com",
Self = true
};
calendarEvent.Start = new EventDateTime
{
DateTime = start,
TimeZone = "America/Mexico_City"
};
calendarEvent.End = new EventDateTime
{
DateTime = start.AddHours(1),
TimeZone = "America/Mexico_City"
};
calendarEvent.Recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=1" };
calendarEvent.Sequence = 0;
calendarEvent.HangoutLink = "";
calendarEvent.ConferenceData = new ConferenceData
{
CreateRequest = new CreateConferenceRequest
{
RequestId = "1234abcdef",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Status = new ConferenceRequestStatus
{
StatusCode = "success"
}
},
EntryPoints = new List<EntryPoint>
{
new EntryPoint
{
EntryPointType = "video",
Uri = "",
Label = ""
}
},
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Name = "Google Meet",
IconUri = ""
},
ConferenceId = ""
};
//calendarEvent.EventType = "default";
When excute the line to create the event:
EventsResource.InsertRequest request = service.Events.Insert(calendarEvent, "email#example.com");
request.ConferenceDataVersion = 1;
Event createdEvent = request.Execute();
I get:
Google.Apis.Requests.Request Error Invalid conference type value. [400] Reason[invalid] Domain[global]"
When creating an event with a new conference data. You just need to specify the createRequest field, and set the conferenceDataVersion request parameter to 1 for all event modification requests.
Try this:
calendarEvent.ConferenceData = new ConferenceData
{
CreateRequest = new CreateConferenceRequest
{
RequestId = "1234abcdef",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
}
},
};
That's when i need to use the Stripe API so when i need it, it will go wrong and make mistakes in the Stripe area as you can see here.
i have : v15.6.1 on Stripe.net
Where it goes wrong is here:
planservice.Create(new StripePlanCreateOptions()
to here:
PlanId = abn.PriceValueUnikId };
all the value I get by json eg userid, pric and pricId there is content in them.
[HttpPost]
public IActionResult Post([FromBody] JObject token)
{
var api = Settings.ConstName.StrinpAPIKeyTest;
StripeConfiguration.SetApiKey(api);
var chargeService = new StripeChargeService();
chargeService.ExpandBalanceTransaction = true;
chargeService.ExpandCustomer = true;
chargeService.ExpandInvoice = true;
//StripeCharge stripeCharge = chargeService.Get(api);
var customerSerive = new StripeCustomerService(api);
var subservice = new StripeSubscriptionService(api);
var planservice = new StripePlanService(api);
var pricId = (int)token.GetValue("pricid");
var pric = (int)token.GetValue("pric");
var userid = (int) Userid();
var abn = _dbContext.PriceValue.FirstOrDefault(i => i.PriceValueId == pricId || i.Price == pric);
//Finder information omkring pakken til den enkelte pakke.
var currentUser = _dbContext.Users.FirstOrDefault(i => i.UserId == userid);
if (currentUser != null)
{
if (abn != null)
{
var orderid = Settings.ValueWordsAndNumbers.OrdreValue();//Orderid
var planType = $"OrderId: {orderid} - Pris: {abn.Price} - Mdr: {abn.Months} UserId: {userid}";
planservice.Create(new StripePlanCreateOptions()//error from here
{
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
Id = abn.PriceValueUnikId
});
var newCustomer = new StripeCustomerCreateOptions
{
SourceToken = token["id"].ToString(),
Email = token["email"].ToString(),
PlanId = abn.PriceValueUnikId,
};//error to here
var stripeCustomer = customerSerive.Create(newCustomer);
}
}
var planOptions = new StripePlanCreateOptions() {
Product = new StripePlanProductCreateOptions() {
Name = "planType"
},
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};
var planService = new StripePlanService();
StripePlan plan = planService.Create(planOptions);
API version to 2018-02-06 and add support for Product & Plan API
Now Product is REQUIRED.
you need past ID product or dictionary containing fields used to create a service product.
var planOptions = new StripePlanCreateOptions() {
ProductId ="Product Plan id",
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};
i am new to travelport universal api. i receive response from api. I perform LOW FARE SEARCH and in response the fare information and the flight information return in two different list.the problem is that i don't find any relationship in these LIST's. and also WHAT IS THE BEST WAY TO DECODE THE WSDL RESPONSE. i am using WSDL below is my code
string TargetBranch = "P7004961";
string OriginApplication = "uAPI";
string Origin="DXB";
string Destination="LHR";
string Departuredate = "2014-03-25T00:00:00";
string FlightStatus = "One-way";
string url = "https://americas-uapi.copy-webservices.travelport.com/B2BGateway/connect/uAPI/AirService";
string ReturnDate = "2014-04-05T00:00:00";
string UserName = "Universal API/uAPI6035036525-8ff7f8fc", Password = "DSXSEDn3fme9d6m2DfKP5rEaW";
LowFareSearchReq req = new LowFareSearchReq();
req.TargetBranch = TargetBranch;
BillingPointOfSaleInfo biPOS = new BillingPointOfSaleInfo();
biPOS.OriginApplication = OriginApplication;
req.BillingPointOfSaleInfo = biPOS;
/////////// Origin to Destination////////////////
SearchAirLeg airLeg = new SearchAirLeg();
Airport fromAirPort = new Airport() { Code = Origin };
typeSearchLocation fromTypLoc = new typeSearchLocation() { Item = fromAirPort };
airLeg.SearchOrigin = new typeSearchLocation[1] { fromTypLoc };
Airport toAirPort = new Airport() { Code = Destination };
typeSearchLocation toTypLoc = new typeSearchLocation() { Item = toAirPort };
airLeg.SearchDestination = new typeSearchLocation[1] { toTypLoc };
typeTimeSpec origDep = new typeTimeSpec() { PreferredTime = Departuredate };
airLeg.Items = new typeTimeSpec[1] { origDep };
/////////////////// Destination to Origin ////////////////////
SearchAirLeg returnLeg = new SearchAirLeg();
Airport RetfromAirport = new Airport() { Code = Destination };
typeSearchLocation fromLocation = new typeSearchLocation() { Item = RetfromAirport };
returnLeg.SearchOrigin = new typeSearchLocation[1] { fromLocation };
Airport retToAirpot = new Airport() { Code = Origin };
typeSearchLocation tolocation = new typeSearchLocation() { Item = retToAirpot };
returnLeg.SearchDestination = new typeSearchLocation[1] { tolocation };
typeTimeSpec retdate = new typeTimeSpec() { PreferredTime = ReturnDate };
returnLeg.Items = new typeTimeSpec[1] { retdate };
///////// checking for one way or return//////////////////////////
if (FlightStatus == "One-way")
{
req.Items = new object[] { airLeg };
}
else
{
req.Items = new object[] { airLeg, returnLeg };
}
AirSearchModifiers AirsearchModifier = new AirSearchModifiers()
{
DistanceType = typeDistance.KM,
IncludeFlightDetails = true,
PreferNonStop = true,
MaxSolutions = "300",
PreferredProviders= new Provider[1]{ new Provider(){ Code="1G"}}
};
req.AirSearchModifiers = AirsearchModifier;
SearchPassenger pass1 = new SearchPassenger() { Code = "ADT" };
req.SearchPassenger = new SearchPassenger[] { pass1 };
string Currency = "PKR";
AirPricingModifiers AirPriceMode = new AirPricingModifiers() { CurrencyType = Currency, };
req.AirPricingModifiers = AirPriceMode;
LowFareSearchRsp response = new LowFareSearchRsp();
AirLowFareSearchBinding binding = new AirLowFareSearchBinding();
binding.Url = url;
binding.Credentials = new NetworkCredential(UserName, Password);
response = binding.service(req);
Thanks to all.Finally i found result which is below quit easy in fact In the LowFareSearch response you get back among other info a list of AirSegments and a list of AirPricingSolutions. Each AirPricingSolution contains AirPricingInfo with the applicable SegmentRef keys and BookingCode info. Each SegmentRef key corresponds to a flight in the AirSegment list. This is how you know which flights (AirSegments) correspond to a specific price (AirPricingSolution).
I am trying to search for message items between two dates from the inbox folder.
I use the following restrictionType but it throws this error:
firmt.RootFolder = null
What am I doing wrong?
There is some messages between the mentionned dates ;-)
Thanks for your suggestions.
using (ExchangeServiceBinding esb = new ExchangeServiceBinding())
{
esb.Url = ConfigurationManager.AppSettings["ExchangeWebServicesURL"].ToString();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
esb.PreAuthenticate = true;
esb.Credentials = new NetworkCredential(email, password);
FindItemType findItemRequest = new FindItemType();
// paging
IndexedPageViewType ipvt = new IndexedPageViewType();
ipvt.BasePoint = IndexBasePointType.Beginning;
ipvt.MaxEntriesReturned = nombreMessage;
ipvt.MaxEntriesReturnedSpecified = true;
ipvt.Offset = offset;
findItemRequest.Item = ipvt;
// filter by dates
AndType andType = new AndType();
List<SearchExpressionType> searchExps = new List<SearchExpressionType>();
RestrictionType restriction = new RestrictionType();
PathToUnindexedFieldType pteft = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeSent
};
IsGreaterThanOrEqualToType IsGreaterThanOrEqualTo = new IsGreaterThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(-6d).ToString()
}
}
};
searchExps.Add(IsGreaterThanOrEqualTo);
IsLessThanOrEqualToType IsLessThanOrEqualTo = new IsLessThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(1d).ToString()
}
}
};
searchExps.Add(IsLessThanOrEqualTo);
andType.Items = searchExps.ToArray();
restriction.Item = andType;
findItemRequest.Restriction = restriction;
//// Define the sort order of items.
FieldOrderType[] fieldsOrder = new FieldOrderType[1];
fieldsOrder[0] = new FieldOrderType();
PathToUnindexedFieldType dateOrder = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeReceived
};
fieldsOrder[0].Item = dateOrder;
fieldsOrder[0].Order = SortDirectionType.Descending;
findItemRequest.SortOrder = fieldsOrder;
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
// define which item properties are returned in the response
findItemRequest.ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.IdOnly
};
// identify which folder to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType { Id = DistinguishedFolderIdNameType.inbox };
// add folders to request
findItemRequest.ParentFolderIds = folderIDArray;
// find the messages
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
//-------------
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType responseMessage = responseMessages.Items[0];
if (responseMessage is FindItemResponseMessageType)
{
FindItemResponseMessageType firmt = (responseMessage as FindItemResponseMessageType);
*******FindItemParentType fipt = firmt.RootFolder;********
object obj = fipt.Item;
// FindItem contains an array of items.
ArrayOfRealItemsType realitems = (obj as ArrayOfRealItemsType);
ItemType[] items = realitems.Items;
// if no messages were found, then return null -- we're done
if (items == null || items.Count() <= 0)
return null;
// FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
for (int i = 0; i < items.Count(); i++)
itemIds[i] = items[i].ItemId;
GetItemType getItemType = new GetItemType
{
ItemIds = itemIds,
ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.AllProperties,
BodyType = BodyTypeResponseType.Text,
BodyTypeSpecified = true,
AdditionalProperties = new BasePathToElementType[] {
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageFrom },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageIsRead },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageSender },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageToRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageCcRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageBccRecipients }
}
}
};
GetItemResponseType getItemResponse = esb.GetItem(getItemType);
messages = ReadItems(getItemResponse, items.Count());
}
I found the answer on my own after a long search about date format.
The restrictions has to be defined as this:
// greater or equal to
string dateStart = DateTime.Today.add(-6d);
string dateEnd = DateTime.Today.Add(1d);
PathToUnindexedFieldType dateSentPath = new PathToUnindexedFieldType();
dateSentPath.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsGreaterThanOrEqualToType IsGreaterThanOrEqual = new IsGreaterThanOrEqualToType();
IsGreaterThanOrEqual.Item = dateSentPath;
FieldURIOrConstantType dateConstant = new FieldURIOrConstantType();
ConstantValueType dateConstantValue = new ConstantValueType();
dateConstantValue.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateStart.Year.ToString(), dateStart.Month.ToString(), dateStart.Day.ToString());
dateConstant.Item = dateConstantValue;
IsGreaterThanOrEqual.FieldURIOrConstant = dateConstant;
// less than or equal to
PathToUnindexedFieldType dateSentPath1 = new PathToUnindexedFieldType();
dateSentPath1.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsLessThanOrEqualToType lessThanOrEqualTo = new IsLessThanOrEqualToType();
lessThanOrEqualTo.Item = dateSentPath1;
FieldURIOrConstantType dateConstant1 = new FieldURIOrConstantType();
ConstantValueType dateConstantValue1 = new ConstantValueType();
dateConstantValue1.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateEnd.Year.ToString(), dateEnd.Month.ToString(), dateEnd.Day.ToString());
dateConstant1.Item = dateConstantValue1;
lessThanOrEqualTo.FieldURIOrConstant = dateConstant1;
RestrictionType restriction = new RestrictionType();
AndType andType = new AndType();
andType.Items = new SearchExpressionType[] { lessThanOrEqualTo, IsGreaterThanOrEqual };
restriction.Item = andType;
findItemRequest.Restriction = restriction;
Hope this help someone some day ;-)
In case anyone stumbles upon this in the future, EWS has gotten even more strict about date formatting. The accepted answer formatting works for 2 digit months, but it does not for single digit months.
The formatting that works in all cases is:
DateTime.Today.AddDays(15).ToString("yyyy-MM-ddThh:mm:ssZ")
The restriction also works using the "Sortable date/time pattern".
Datetime.Now.ToString("s")