We are using open xml for displaying bar graph in exl export but it is not showing labels on data like values above each bar.
Here is the code i am using
BarChart barChart = plotArea.AppendChild<BarChart>(new BarChart(new BarDirection() { Val = new EnumValue<BarDirectionValues>(BarDirectionValues.Column) },
new BarGrouping() { Val = new EnumValue<BarGroupingValues>(BarGroupingValues.Clustered) }));
BarChartSeries barChartSeries = barChart.AppendChild<BarChartSeries>(new BarChartSeries(new Index()
{
Val =
new UInt32Value(i)
},
new Order() { Val = new UInt32Value(i) },
new SeriesText(new NumericValue() { Text = key })));
where key is data value for bar. But still it is not displaying. Can anyone tell where exactly have to put data label so that value labels should be visible on top of each bar in bar graph
You just need to create a DataLabels class, modify how you want them to look and append it to your series. Hope this helps
C.DataLabels dataLabels2 = new C.DataLabels();
C.TextProperties textProperties2 = new C.TextProperties();
A.BodyProperties bodyProperties2 = new A.BodyProperties();
A.ListStyle listStyle2 = new A.ListStyle();
A.Paragraph paragraph2 = new A.Paragraph();
A.ParagraphProperties paragraphProperties2 = new A.ParagraphProperties();
A.DefaultRunProperties defaultRunProperties2 = new A.DefaultRunProperties() { FontSize = 700 };
A.SolidFill solidFill2 = new A.SolidFill();
A.SchemeColor schemeColor2 = new A.SchemeColor() { Val = A.SchemeColorValues.Background1 };
solidFill2.Append(schemeColor2);
defaultRunProperties2.Append(solidFill2);
paragraphProperties2.Append(defaultRunProperties2);
A.EndParagraphRunProperties endParagraphRunProperties2 = new A.EndParagraphRunProperties() { Language = "en-US" };
paragraph2.Append(paragraphProperties2);
paragraph2.Append(endParagraphRunProperties2);
textProperties2.Append(bodyProperties2);
textProperties2.Append(listStyle2);
textProperties2.Append(paragraph2);
C.ShowLegendKey showLegendKey2 = new C.ShowLegendKey() { Val = false };
C.ShowValue showValue2 = new C.ShowValue() { Val = true };
C.ShowCategoryName showCategoryName2 = new C.ShowCategoryName() { Val = false };
C.ShowSeriesName showSeriesName2 = new C.ShowSeriesName() { Val = false };
C.ShowPercent showPercent2 = new C.ShowPercent() { Val = false };
C.ShowBubbleSize showBubbleSize2 = new C.ShowBubbleSize() { Val = false };
C.ShowLeaderLines showLeaderLines2 = new C.ShowLeaderLines() { Val = false };
dataLabels2.Append(textProperties2);
dataLabels2.Append(showLegendKey2);
dataLabels2.Append(showValue2);
dataLabels2.Append(showCategoryName2);
dataLabels2.Append(showSeriesName2);
dataLabels2.Append(showPercent2);
dataLabels2.Append(showBubbleSize2);
dataLabels2.Append(showLeaderLines2);
barChartSeries2.Append(dataLabels2);
Related
I want to add custom text on BarChart like this:
How to do this using OpenXML which feature?
Please help
This can be achieved by adding text on shape which is not part of chart. It can be placed by positioning spreadsheet rows. Here's are sample codes:
string[] strGenerator = new string[] { "2213969", "2213963", "2213979", "2213969", "2213963", "2213979" };
string[] strRowId = new string[] { "22", "20", "18","18","20","22" };
string[] strColumnId = new string[] { "1", "1", "1", "10", "10", "10" };
string[] strRowOffset = new string[] { "18000", "27000", "27000", "50000", "50000", "50000" }; //{ "80000", "186266", "95036", "81643", "27214", "136071" };
string[] strColumnOffset = new string[] { "489858", "508606", "520699", "497453", "497453", "497453" }; //{ "489858", "508606", "520699", "197453", "182032", "163285" };
for (i = 0; i < 6; i++)
{
Xdr.OneCellAnchor oneCellAnchor6 = new Xdr.OneCellAnchor();
Xdr.FromMarker fromMarker8 = new Xdr.FromMarker();
Xdr.ColumnId columnId10 = new Xdr.ColumnId();
columnId10.Text = strColumnId[i]; // "1";
Xdr.ColumnOffset columnOffset10 = new Xdr.ColumnOffset();
columnOffset10.Text = strColumnOffset[i]; // "520699"
Xdr.RowId rowId10 = new Xdr.RowId();
rowId10.Text = strRowId[i]; //"16";
Xdr.RowOffset rowOffset10 = new Xdr.RowOffset();
rowOffset10.Text = strRowOffset[i];//"95036"; // Convert.ToString(95036*(i+1));// "95036";
fromMarker8.Append(columnId10);
fromMarker8.Append(columnOffset10);
fromMarker8.Append(rowId10);
fromMarker8.Append(rowOffset10);
//Xdr.Extent extent6 = new Xdr.Extent() { Cx = 1782535L, Cy = 204108L };
Xdr.Extent extent6 = new Xdr.Extent() { Cx = 1782535L, Cy = 204108L };
Xdr.Shape shape6 = new Xdr.Shape() { Macro = "", TextLink = "" };
Xdr.NonVisualShapeProperties nonVisualShapeProperties6 = new Xdr.NonVisualShapeProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties8 = new Xdr.NonVisualDrawingProperties() { Id = (UInt32Value)21U, Name = "TextBox 20" };
A.NonVisualDrawingPropertiesExtensionList nonVisualDrawingPropertiesExtensionList8 = new A.NonVisualDrawingPropertiesExtensionList();
A.NonVisualDrawingPropertiesExtension nonVisualDrawingPropertiesExtension8 = new A.NonVisualDrawingPropertiesExtension() { Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}" };
OpenXmlUnknownElement openXmlUnknownElement9 = OpenXmlUnknownElement.CreateOpenXmlUnknownElement("<a16:creationId xmlns:a16=\"http://schemas.microsoft.com/office/drawing/2014/main\" id=\"{6230E3EC-6B4D-47AE-A392-192F8AB4F7CE}\" />");
nonVisualDrawingPropertiesExtension8.Append(openXmlUnknownElement9);
nonVisualDrawingPropertiesExtensionList8.Append(nonVisualDrawingPropertiesExtension8);
nonVisualDrawingProperties8.Append(nonVisualDrawingPropertiesExtensionList8);
Xdr.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties6 = new Xdr.NonVisualShapeDrawingProperties() { TextBox = true };
nonVisualShapeProperties6.Append(nonVisualDrawingProperties8);
nonVisualShapeProperties6.Append(nonVisualShapeDrawingProperties6);
Xdr.ShapeProperties shapeProperties6 = new Xdr.ShapeProperties();
A.Transform2D transform2D6 = new A.Transform2D();
A.Offset offset8 = new A.Offset() { X = 1130299L, Y = 3276903L };
A.Extents extents8 = new A.Extents() { Cx = 1782535L, Cy = 204108L };
//A.Offset offset8 = new A.Offset() { X = 0, Y = 0 };
//A.Extents extents8 = new A.Extents() { Cx = 0, Cy = 0 };
transform2D6.Append(offset8);
transform2D6.Append(extents8);
A.PresetGeometry presetGeometry6 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList6 = new A.AdjustValueList();
presetGeometry6.Append(adjustValueList6);
A.NoFill noFill6 = new A.NoFill();
shapeProperties6.Append(transform2D6);
shapeProperties6.Append(presetGeometry6);
shapeProperties6.Append(noFill6);
Xdr.ShapeStyle shapeStyle6 = new Xdr.ShapeStyle();
A.LineReference lineReference6 = new A.LineReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage16 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
lineReference6.Append(rgbColorModelPercentage16);
A.FillReference fillReference6 = new A.FillReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage17 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
fillReference6.Append(rgbColorModelPercentage17);
A.EffectReference effectReference6 = new A.EffectReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage18 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
effectReference6.Append(rgbColorModelPercentage18);
A.FontReference fontReference6 = new A.FontReference() { Index = A.FontCollectionIndexValues.Minor };
A.SchemeColor schemeColor29 = new A.SchemeColor() { Val = A.SchemeColorValues.Text1 };
fontReference6.Append(schemeColor29);
shapeStyle6.Append(lineReference6);
shapeStyle6.Append(fillReference6);
shapeStyle6.Append(effectReference6);
shapeStyle6.Append(fontReference6);
Xdr.TextBody textBody6 = new Xdr.TextBody();
A.BodyProperties bodyProperties6;
// if (i == 2)
// {
// bodyProperties6 = new A.BodyProperties() { VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip, Wrap = A.TextWrappingValues.Square, RightToLeftColumns = false, Anchor = A.TextAnchoringTypeValues.Bottom };
// }
// else
// {
bodyProperties6 = new A.BodyProperties() { VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip, Wrap = A.TextWrappingValues.Square, RightToLeftColumns = false, Anchor = A.TextAnchoringTypeValues.Top };
// }
A.NoAutoFit noAutoFit6 = new A.NoAutoFit();
bodyProperties6.Append(noAutoFit6);
A.ListStyle listStyle6 = new A.ListStyle();
A.Paragraph paragraph6 = new A.Paragraph();
A.ParagraphProperties paragraphProperties3 = new A.ParagraphProperties() { Alignment = A.TextAlignmentTypeValues.Left };
A.Run run9 = new A.Run();
A.RunProperties runProperties9 = new A.RunProperties() { Language = "en-US", FontSize = 1100, Bold = false, Italic = false, Underline = A.TextUnderlineValues.None, Strike = A.TextStrikeValues.NoStrike };
A.SolidFill solidFill15 = new A.SolidFill();
A.SchemeColor schemeColor30 = new A.SchemeColor() { Val = A.SchemeColorValues.Background1 };
solidFill15.Append(schemeColor30);
A.EffectList effectList7 = new A.EffectList();
A.LatinFont latinFont6 = new A.LatinFont() { Typeface = "+mn-lt" };
A.EastAsianFont eastAsianFont6 = new A.EastAsianFont() { Typeface = "+mn-ea" };
A.ComplexScriptFont complexScriptFont6 = new A.ComplexScriptFont() { Typeface = "+mn-cs" };
runProperties9.Append(solidFill15);
runProperties9.Append(effectList7);
runProperties9.Append(latinFont6);
runProperties9.Append(eastAsianFont6);
runProperties9.Append(complexScriptFont6);
A.Text text9 = new A.Text();
text9.Text = strGenerator[i];
run9.Append(runProperties9);
run9.Append(text9);
A.Run run10 = new A.Run();
A.RunProperties runProperties10 = new A.RunProperties() { Language = "en-US", FontSize = 1200 };
A.SolidFill solidFill16 = new A.SolidFill();
A.SchemeColor schemeColor31 = new A.SchemeColor() { Val = A.SchemeColorValues.Background1 };
solidFill16.Append(schemeColor31);
runProperties10.Append(solidFill16);
A.Text text10 = new A.Text();
text10.Text = "";
run10.Append(runProperties10);
run10.Append(text10);
paragraph6.Append(paragraphProperties3);
paragraph6.Append(run9);
paragraph6.Append(run10);
textBody6.Append(bodyProperties6);
textBody6.Append(listStyle6);
textBody6.Append(paragraph6);
shape6.Append(nonVisualShapeProperties6);
shape6.Append(shapeProperties6);
shape6.Append(shapeStyle6);
shape6.Append(textBody6);
Xdr.ClientData clientData8 = new Xdr.ClientData();
oneCellAnchor6.Append(fromMarker8);
oneCellAnchor6.Append(extent6);
oneCellAnchor6.Append(shape6);
oneCellAnchor6.Append(clientData8);
drawingspart.WorksheetDrawing.Append(oneCellAnchor6);
}
So I have a fairly standard chart method using the c# DocumentFormat.OpenXML, namespace which works fine. But I can't figure out how to put number labels on the axes, specifically the value axis. Unfortunately the c# openxml is almost completely undocumented. I'll be happy to see an answer elsewhere if this is a duplicate question, because I can't find it. How do I add number labels to my axes?
My full code is below, but here is the part where I create the value axis, so I assume I have to add something in the parentheses here, like a new ???? but I don't know what it is.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new DocumentFormat.OpenXml.Drawing.Charts.Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) })
//, new ???????() { ???? } //I think I need to add something here
);
Here is the graph I'm getting now:
And here is how I want it to look:
Here is the full code:
private static void InsertChartInSpreadsheet(SpreadsheetDocument document, string title, Dictionary<string, int> data)
{
WorksheetPart graphWorksheetPart = (WorksheetPart)document.WorkbookPart.AddNewPart<WorksheetPart>();
graphWorksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>() ;
Sheet sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(graphWorksheetPart),
SheetId = 2,
Name = "Graph"
};
sheets.Append(sheet);
// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = graphWorksheetPart.AddNewPart<DrawingsPart>();
graphWorksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{ Id = graphWorksheetPart.GetIdOfPart(drawingsPart) });
graphWorksheetPart.Worksheet.Save();
// Add a new chart and set the chart language to English-US.
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
// Create a new clustered column chart.
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
BarChart barChart = plotArea.AppendChild<BarChart>(new BarChart(new BarDirection()
{ Val = new EnumValue<BarDirectionValues>(BarDirectionValues.Column) },
new BarGrouping() { Val = new EnumValue<BarGroupingValues>(BarGroupingValues.Clustered) }));
uint i = 0;
// Iterate through each key in the Dictionary collection and add the key to the chart Series
// and add the corresponding value to the chart Values.
foreach (string key in data.Keys)
{
BarChartSeries barChartSeries = barChart.AppendChild<BarChartSeries>(new BarChartSeries(new Index()
{
Val = new UInt32Value(i)
},
new Order() { Val = new UInt32Value(i) },
new SeriesText(new NumericValue() { Text = key })));
StringLiteral strLit = barChartSeries.AppendChild<CategoryAxisData>(new CategoryAxisData()).AppendChild<StringLiteral>(new StringLiteral());
strLit.Append(new PointCount() { Val = new UInt32Value(1U) });
strLit.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(0U) }).Append(new NumericValue(title));
NumberLiteral numLit = barChartSeries.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(
new DocumentFormat.OpenXml.Drawing.Charts.Values()).AppendChild<NumberLiteral>(new NumberLiteral());
numLit.Append(new FormatCode("General"));
numLit.Append(new PointCount() { Val = new UInt32Value(1U) });
numLit.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(0u) }).Append(new NumericValue(data[key].ToString()));
i++;
}
barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
// Add the Category Axis.
CategoryAxis catAx = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new DocumentFormat.OpenXml.Drawing.Charts.Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new DocumentFormat.OpenXml.Drawing.Charts.Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }),
);
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Right) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
// Save the chart part.
chartPart.ChartSpace.Save();
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("1"),
new ColumnOffset("581025"),
new RowId("1"),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("9"),
new ColumnOffset("276225"),
new RowId("16"),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
// Save the WorksheetDrawing object.
drawingsPart.WorksheetDrawing.Save();
}
The attached code should get the desired look for your x and y axis. The new code segments are surrounded with comments
//START NEW CODE
//END NEW CODE
All of the new code is in the Category and Value Axis areas towards the bottom:
private static void InsertChartInSpreadsheet(SpreadsheetDocument document, string title, Dictionary<string, int> data)
{
WorksheetPart graphWorksheetPart = (WorksheetPart)document.WorkbookPart.AddNewPart<WorksheetPart>();
graphWorksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>() ;
Sheet sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(graphWorksheetPart),
SheetId = 2,
Name = "Graph"
};
sheets.Append(sheet);
// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = graphWorksheetPart.AddNewPart<DrawingsPart>();
graphWorksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{ Id = graphWorksheetPart.GetIdOfPart(drawingsPart) });
graphWorksheetPart.Worksheet.Save();
// Add a new chart and set the chart language to English-US.
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
// Create a new clustered column chart.
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
BarChart barChart = plotArea.AppendChild<BarChart>(new BarChart(new BarDirection()
{ Val = new EnumValue<BarDirectionValues>(BarDirectionValues.Column) },
new BarGrouping() { Val = new EnumValue<BarGroupingValues>(BarGroupingValues.Clustered) }));
uint i = 0;
// Iterate through each key in the Dictionary collection and add the key to the chart Series
// and add the corresponding value to the chart Values.
foreach (string key in data.Keys)
{
BarChartSeries barChartSeries = barChart.AppendChild<BarChartSeries>(new BarChartSeries(new Index()
{
Val =
new UInt32Value(i)
},
new Order() { Val = new UInt32Value(i) },
new SeriesText(new NumericValue() { Text = key })));
StringLiteral strLit = barChartSeries.AppendChild<CategoryAxisData>(new CategoryAxisData()).AppendChild<StringLiteral>(new StringLiteral());
strLit.Append(new PointCount() { Val = new UInt32Value(1U) });
strLit.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(0U) }).Append(new NumericValue(title));
NumberLiteral numLit = barChartSeries.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(
new DocumentFormat.OpenXml.Drawing.Charts.Values()).AppendChild<NumberLiteral>(new NumberLiteral());
numLit.Append(new FormatCode("General"));
numLit.Append(new PointCount() { Val = new UInt32Value(1U) });
numLit.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(0u) }).Append
(new NumericValue(data[key].ToString()));
i++;
}
barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
// Add the Category Axis.
CategoryAxis catAx = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new DocumentFormat.OpenXml.Drawing.Charts.Orientation()
{
Val = new EnumValue<DocumentFormat.
OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
//START NEW CODE
new Delete() {Val = false},
//END NEW CODE
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
//START NEW CODE
new NumberingFormat() {FormatCode = "General", SourceLinked = false},
new MajorTickMark() {Val = TickMarkValues.Outside},
new MinorTickMark() {Val = TickMarkValues.Cross},
//END NEW CODE
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) },
//START NEW CODE
new NoMultiLevelLabels() {Val = true}
//END NEW CODE
));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new DocumentFormat.OpenXml.Drawing.Charts.Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
//START NEW CODE
new Delete() {Val = false},
//END NEW CODE
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
},
//START NEW CODE
new MajorTickMark() {Val = TickMarkValues.Outside},
new MinorTickMark() {Val = TickMarkValues.Cross},
//END NEW CODE
new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Right) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
// Save the chart part.
chartPart.ChartSpace.Save();
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("1"),
new ColumnOffset("581025"),
new RowId("1"),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("9"),
new ColumnOffset("276225"),
new RowId("16"),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.
Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.
Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
// Save the WorksheetDrawing object.
drawingsPart.WorksheetDrawing.Save();
}
I used the OpenXML Productivity Tool to compare your generated file with a similar one that contained the axis details. With the compare, you can see which calls are needed to add to the plain axis in order to turn on the markings.
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 creating a bar chart with openxml and need to have the x axis labels on the bottom of the chart rotated at a 45 degree angle. Using the documentation for openxml barcharts I cannot figure out how to displays the labels. Below is the function I use to create the chart. Any suggestions would be greatly appreciated.
public static void InsertChartInSpreadsheet(string docName, string worksheetName, string title,
System.Data.DataTable data)
{
// Open the document for editing.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
{
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == worksheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return;
}
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() { Id = worksheetPart.GetIdOfPart(drawingsPart) });
worksheetPart.Worksheet.Save();
// Add a new chart and set the chart language to English-US.
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
// Create a new bar chart.
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
BarChart barChart = plotArea.AppendChild<BarChart>(new BarChart(new BarDirection() { Val = new EnumValue<BarDirectionValues>(BarDirectionValues.Column) },
new DataLabels(new DataLabelPosition { Val = new EnumValue<DataLabelPositionValues>(DataLabelPositionValues.InsideBase) }
)));
uint i = 0;
// Iterate through each key in the Dictionary collection and add the key to the chart Series
// and add the corresponding value to the chart Values.
foreach (DataRow r in data.Rows)
{
BarChartSeries barChartSeries = barChart.AppendChild<BarChartSeries>(new BarChartSeries(new Index()
{
Val = new UInt32Value(i)
},
new Order() { Val = new UInt32Value(i) },
new SeriesText(new NumericValue() { Text = r[2].ToString().Trim() }
)));
StringLiteral strLit = barChartSeries.AppendChild<CategoryAxisData>(new CategoryAxisData()).AppendChild<StringLiteral>(new StringLiteral());
strLit.Append(new PointCount() { Val = new UInt32Value(1U) });
strLit.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(0U) }).Append(new NumericValue(title));
NumberLiteral numLit = barChartSeries.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(
new DocumentFormat.OpenXml.Drawing.Charts.Values()).AppendChild<NumberLiteral>(new NumberLiteral());
numLit.Append(new FormatCode("General"));
numLit.Append(new PointCount() { Val = new UInt32Value(1U) });
numLit.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(0u) }).Append(new NumericValue(r[8].ToString().Trim()));
i++;
}
barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
// Add the Category Axis.
CategoryAxis catAx = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId() { Val = new UInt32Value(48650112u) }, new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.
OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Left) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Save the chart part.
chartPart.ChartSpace.Save();
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("0"),
new ColumnOffset("581025"),
new RowId("3"),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("17"),
new ColumnOffset("276225"),
new RowId("32"),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.
Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.
Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) }) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
// Save the WorksheetDrawing object.
drawingsPart.WorksheetDrawing.Save();
}
}
place in category Axis construtor
new C.Delete { Val = false },
new C.TextProperties(new BodyProperties { Rotation = -5400000, Vertical = TextVerticalValues.Horizontal },
new ListStyle(),
new Paragraph(new ParagraphProperties(new DefaultRunProperties(), new EndParagraphRunProperties { Language = "en-US" }))),
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")