When I call GetReport I only get the headers for the tab delimited response. However, when I use the scratch pad to, RequestReport, RequestReportList, using the RequestId to get GeneratedReportId and then GetReport with that Id. I get expected results.
Does anyone have an idea why my code doesn't pull the report like the scrathpad does?
RequestReportRequest request = new RequestReportRequest();
request.Merchant = settings.SellerId;
request.MarketplaceIdList = new IdList();
request.MarketplaceIdList.Id = new List<string>(new string[] { settings.MarketplaceId });
request.ReportType = "_GET_MERCHANT_LISTINGS_DATA_";
RequestReportResponse requestResponse = _mws.RequestReport(request);
Thread.Sleep(15000);
Console.WriteLine(requestResponse.RequestReportResult.ReportRequestInfo.ReportProcessingStatus);
GetReportRequestListRequest reportRequestListRequest = new GetReportRequestListRequest();
reportRequestListRequest.Merchant = settings.SellerId;
List<ReportRequestInfo> requestInfos = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new GetReportRequestListResponse();
reportRequestListResponse = _mws.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new GetReportRequestListResult();
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
requestInfos = reportRequestListResult.ReportRequestInfo;
while (requestInfos[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Thread.Sleep(20000);
reportRequestListResponse = _mws.GetReportRequestList(reportRequestListRequest);
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
requestInfos = reportRequestListResult.ReportRequestInfo;
}
GetReportListRequest listRequest = new GetReportListRequest();
listRequest.Merchant = settings.SellerId;
listRequest.ReportRequestIdList = new IdList();
listRequest.ReportRequestIdList.Id.Add(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportListResponse listResponse = _mws.GetReportList(listRequest);
GetReportListResult getReportListResult = listResponse.GetReportListResult;
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = settings.SellerId;
reportRequest.WithReportId(getReportListResult.ReportInfo[0].ReportId);
GetReportResponse reportResponse = new GetReportResponse();
string fileName = dataPath + "\\report-" + getReportListResult.ReportInfo[0].ReportId + ".txt";
reportRequest.Report = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
reportResponse = _mws.GetReport(reportRequest);
I removed the MarketplaceId from the ReportRequest and it works fine. I'm not sure why it didn't pull the report with it specified, but it is working without the information.
Removed these 2 lines from above code.
request.MarketplaceIdList = new IdList();
request.MarketplaceIdList.Id = new List<string>(new string[] { settings.MarketplaceId });
Related
I have been able to authenticate my app on google analytics and display some data around unique page views. Now I want to get the page views based on Traffic source but I'm not quite sure how to get the filters on the dimensions. I have written my code in c# and can't get my head around examples in other languages I've seen. i have used the api Query Explorer and got the right expressions and results. My difficulty is how to translate that into my code. My code is below
var filepath = Server.MapPath("~/jsonfile"); // path to the json file for the Service account
GoogleCredential credentials;
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes);
}
var reportingService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var dateRange = new DateRange
{
StartDate = "2016-10-28",
EndDate = "2016-12-20"
};
var sessions = new Metric
{
Expression = "ga:uniquePageviews",
Alias = "Sessions"
};
var social = new Dimension { Name = "ga:socialNetwork" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { social },
Metrics = new List<Metric> { sessions },
ViewId = "myviewid"
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.FirstOrDefault().Data.Rows)
{
Response.Write(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
You should create a DimensionFilterClauses and pass it to the ReportRequest as follows:
//Create the Dimension Filter
var dimensionFilter = new DimensionFilter();
dimensionFilter.DimensionName = "ga:socialNetwork";
dimensionFilter.Expressions = new List<string> { "someValue" };
var dimensionFilterClause = new DimensionFilterClause();
dimensionFilterClause.Filters = new List<DimensionFilter> { dimensionFilter };
Then modify your ReportRequest:
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { social },
Metrics = new List<Metric> { sessions },
ViewId = "myviewid",
DimensionFilterClauses = new List<DimensionFilterClause> { dimensionFilterClause }
};
P.S:
Furthermore, if you need to filter Metric instead of Dimension, you would need to create a MetricFilterClauses as follows and then pass it to MetricFilterClauses in your ReportRequest:
//Create the Metric Filter
var metricFilter = new MetricFilter();
metricFilter.MetricName = "someMetric";
metricFilter.ComparisonValue = "someValue";
var metricFilterClause = new MetricFilterClause();
metricFilterClause.Filters = new List<MetricFilter> { metricFilter };
I followed the watermarking code given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Vml.Office;
using DocumentFormat.OpenXml.Vml.Wordprocessing;
using DocumentFormat.OpenXml.Wordprocessing;
using HorizontalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.HorizontalAnchorValues;
using Lock = DocumentFormat.OpenXml.Vml.Office.Lock;
using VerticalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.VerticalAnchorValues;
namespace DocumentWatermarkTest
{
class Program
{
static void Main(string[] args)
{
byte[] sourceBytes = File.ReadAllBytes(#"C:\Users\loggedinuser\Desktop\TestDoc.docx");
MemoryStream inMemoryStream = new MemoryStream();
inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length);
var doc = WordprocessingDocument.Open(inMemoryStream, true);
AddWatermark(doc);
doc.MainDocumentPart.Document.Save();
doc.Close();
doc.Dispose();
doc = null;
using (FileStream fileStream = new FileStream(#"C:\Users\loggedinuser\Desktop\TestDoc.docx", System.IO.FileMode.Create))
{
inMemoryStream.WriteTo(fileStream);
}
inMemoryStream.Close();
inMemoryStream.Dispose();
inMemoryStream = null;
}
static Header MakeHeader()
{
var header = new Header();
var paragraph = new Paragraph();
var run = new Run();
var text = new Text();
text.Text = "";
run.Append(text);
paragraph.Append(run);
header.Append(paragraph);
return header;
}
static void AddWatermark(WordprocessingDocument doc)
{
if (doc.MainDocumentPart.HeaderParts.Count() == 0)
{
doc.MainDocumentPart.DeleteParts(doc.MainDocumentPart.HeaderParts);
var newHeaderPart = doc.MainDocumentPart.AddNewPart<HeaderPart>();
var rId = doc.MainDocumentPart.GetIdOfPart(newHeaderPart);
var headerRef = new HeaderReference();
headerRef.Id = rId;
var sectionProps = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().LastOrDefault();
if (sectionProps == null)
{
sectionProps = new SectionProperties();
doc.MainDocumentPart.Document.Body.Append(sectionProps);
}
sectionProps.RemoveAllChildren<HeaderReference>();
sectionProps.Append(headerRef);
newHeaderPart.Header = MakeHeader();
newHeaderPart.Header.Save();
}
foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts)
{
var sdtBlock1 = new SdtBlock();
var sdtProperties1 = new SdtProperties();
var sdtId1 = new SdtId() { Val = 87908844 };
var sdtContentDocPartObject1 = new DocPartObjectSdt();
var docPartGallery1 = new DocPartGallery() { Val = "Watermarks" };
var docPartUnique1 = new DocPartUnique();
sdtContentDocPartObject1.Append(docPartGallery1);
sdtContentDocPartObject1.Append(docPartUnique1);
sdtProperties1.Append(sdtId1);
sdtProperties1.Append(sdtContentDocPartObject1);
var sdtContentBlock1 = new SdtContentBlock();
var paragraph2 = new Paragraph()
{
RsidParagraphAddition = "00656E18",
RsidRunAdditionDefault = "00656E18"
};
var paragraphProperties2 = new ParagraphProperties();
var paragraphStyleId2 = new ParagraphStyleId() { Val = "Header" };
paragraphProperties2.Append(paragraphStyleId2);
var run1 = new Run();
var runProperties1 = new RunProperties();
var noProof1 = new NoProof();
var languages1 = new Languages() { EastAsia = "zh-TW" };
runProperties1.Append(noProof1);
runProperties1.Append(languages1);
var picture1 = new Picture();
var shapetype1 = new Shapetype()
{
Id = "_x0000_t136",
CoordinateSize = "21600,21600",
OptionalNumber = 136,
Adjustment = "10800",
EdgePath = "m#7,l#8,m#5,21600l#6,21600e"
};
var formulas1 = new Formulas();
var formula1 = new Formula() { Equation = "sum #0 0 10800" };
var formula2 = new Formula() { Equation = "prod #0 2 1" };
var formula3 = new Formula() { Equation = "sum 21600 0 #1" };
var formula4 = new Formula() { Equation = "sum 0 0 #2" };
var formula5 = new Formula() { Equation = "sum 21600 0 #3" };
var formula6 = new Formula() { Equation = "if #0 #3 0" };
var formula7 = new Formula() { Equation = "if #0 21600 #1" };
var formula8 = new Formula() { Equation = "if #0 0 #2" };
var formula9 = new Formula() { Equation = "if #0 #4 21600" };
var formula10 = new Formula() { Equation = "mid #5 #6" };
var formula11 = new Formula() { Equation = "mid #8 #5" };
var formula12 = new Formula() { Equation = "mid #7 #8" };
var formula13 = new Formula() { Equation = "mid #6 #7" };
var formula14 = new Formula() { Equation = "sum #6 0 #5" };
formulas1.Append(formula1);
formulas1.Append(formula2);
formulas1.Append(formula3);
formulas1.Append(formula4);
formulas1.Append(formula5);
formulas1.Append(formula6);
formulas1.Append(formula7);
formulas1.Append(formula8);
formulas1.Append(formula9);
formulas1.Append(formula10);
formulas1.Append(formula11);
formulas1.Append(formula12);
formulas1.Append(formula13);
formulas1.Append(formula14);
var path1 = new Path()
{
AllowTextPath = DocumentFormat.OpenXml.Vml.BooleanValues.True,
ConnectionPointType = ConnectValues.Custom,
ConnectionPoints = "#9,0;#10,10800;#11,21600;#12,10800",
ConnectAngles = "270,180,90,0"
};
var textPath1 = new TextPath()
{
On = DocumentFormat.OpenXml.Vml.BooleanValues.True,
FitShape = DocumentFormat.OpenXml.Vml.BooleanValues.True
};
var shapeHandles1 = new Handles();
var shapeHandle1 = new Handle()
{
Position = "#0,bottomRight",
XRange = "6629,14971"
};
shapeHandles1.Append(shapeHandle1);
var lock1 = new Lock
{
Extension = ExtensionHandlingBehaviorValues.Edit,
TextLock = DocumentFormat.OpenXml.Vml.Office.BooleanValues.True,
ShapeType = DocumentFormat.OpenXml.Vml.Office.BooleanValues.True
};
shapetype1.Append(formulas1);
shapetype1.Append(path1);
shapetype1.Append(textPath1);
shapetype1.Append(shapeHandles1);
shapetype1.Append(lock1);
var shape1 = new Shape()
{
Id = "PowerPlusWaterMarkObject357476642",
Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin",
OptionalString = "_x0000_s2049",
AllowInCell = DocumentFormat.OpenXml.Vml.BooleanValues.False,
FillColor = "silver",
Stroked = DocumentFormat.OpenXml.Vml.BooleanValues.False,
Type = "#_x0000_t136"
};
var fill1 = new Fill() { Opacity = ".5" };
TextPath textPath2 = new TextPath()
{
Style = "font-family:\"Calibri\";font-size:1pt",
String = "DRAFT"
};
var textWrap1 = new TextWrap()
{
AnchorX = HorizontalAnchorValues.Margin,
AnchorY = VerticalAnchorValues.Margin
};
shape1.Append(fill1);
shape1.Append(textPath2);
shape1.Append(textWrap1);
picture1.Append(shapetype1);
picture1.Append(shape1);
run1.Append(runProperties1);
run1.Append(picture1);
paragraph2.Append(paragraphProperties2);
paragraph2.Append(run1);
sdtContentBlock1.Append(paragraph2);
sdtBlock1.Append(sdtProperties1);
sdtBlock1.Append(sdtContentBlock1);
headerPart.Header.Append(sdtBlock1);
headerPart.Header.Save();
//break;
}
}
}
}
When I use this code, the watermarked text lies below the actual contents of the word document. If there are images in the word document, the watermarked text gets hidden completely and is not visible. Can I somehow place the watermarked text on top of the contents of the word document? Any help would be really appreciated.
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 pull FBA shipment data report. I have a running application that succesfully pulls Unshipped Orders from Amazon. So bascially I took that code and changed it to what I need it to do for the FBA shipment orders. I barely changed the working code to get a report and now the GetReport function is returning a null and I dont know why. I am passing in a ReportId that is coming from Amazon's system.
If someone could peruse over the code and see if maybe I'm passing in a null object or something.
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
reportRequestRequest.Marketplace = marketplaceId;
reportRequestRequest.ReportType = "_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_";
reportRequestRequest.StartDate = DateTime.Now.AddDays(-2);
reportRequestRequest.EndDate = DateTime.Now;
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
Thread.Sleep(15000);
Console.WriteLine(requestResponse.RequestReportResult.ReportRequestInfo.ReportProcessingStatus);
GetReportRequestListRequest reportRequestListRequest = new GetReportRequestListRequest();
reportRequestListRequest.Marketplace = marketplaceId;
reportRequestListRequest.Merchant = merchantId;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new GetReportRequestListResponse();
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new GetReportRequestListResult();
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Thread.Sleep(20000);
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
GetReportListRequest listRequest = new GetReportListRequest();
listRequest.Merchant = merchantId;
listRequest.Marketplace = marketplaceId;
listRequest.ReportRequestIdList = new IdList();
listRequest.ReportRequestIdList.Id.Add(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportListResponse listResponse = service.GetReportList(listRequest);
//MessageBox.Show(listResponse.GetReportListResult.ReportInfo.ToString());
GetReportListResult getReportListResult = listResponse.GetReportListResult;
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
reportRequest.Marketplace = marketplaceId;
reportRequest.WithReportId(getReportListResult.ReportInfo[0].ReportId);
GetReportResponse reportResponse = new GetReportResponse();
{
reportResponse = service.GetReport(reportRequest); // <=== ERROR!!!!
}
catch (MarketplaceWebServiceException e)
{
Console.WriteLine(e);
}
StreamReader sr = new StreamReader(reportRequest.Report);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
After this line:
GetReportResponse reportResponse = new GetReportResponse();
You have to specify a report file, like this:
reportRequest.Report = File.Open("C:\\AmazonReport.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite);
Then, it will write the report to that file.
So, you can see your report there.
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")