C# Botframework Loop inside of AdaptiveCard - c#

I have created one dialog to evaluate our company consultant in our chatbot (C# botframework), but I can't use for or foreach inside of AdaptiveCard. I need to create one TextBlock() and one ChoiceSet() block for each item from List Pergunta, but I can't do it with foreach. Any suggestion or better idea to create this loop ?
Here is my complete dialog code in C#.
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System.Collections.Generic;
using AdaptiveCards;
using SimpleEchoBot.Formulário;
namespace SimpleEchoBot.Dialogs
{
[Serializable]
public class RatingDialog : IDialog<EntidadeCliente>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(this.MessageReceivedAsync);
return Task.CompletedTask;
}
public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var replyMessage = context.MakeMessage();
Attachment attachment = null;
attachment = CriarAdapativecard();
replyMessage.Attachments = new List<Attachment> { attachment };
await context.PostAsync(replyMessage);
}
public Attachment CriarAdapativecard()
{
AdaptiveCard card = new AdaptiveCard()
{
Body = new List<CardElement>()
{
new Container()
{
Items = new List<CardElement>()
{
new ColumnSet()
{
Columns = new List<Column>()
{
new Column()
{
Size = ColumnSize.Auto,
Items = new List<CardElement>()
{
new Image()
{
Url = "D:/EvaWeb.png",
Size = ImageSize.Medium,
Style = ImageStyle.Person
}
}
},
new Column()
{
Size = ColumnSize.Auto,
Items = new List<CardElement>()
{
new TextBlock()
{
Text = "Olá, temos uma novidade!",
Weight = TextWeight.Bolder,
IsSubtle = true
},
new TextBlock()
{
Text = "Gostaria de iniciar a avaliação do consultor?",
Wrap = true
}
}
}
}
}
}
}
},
// Buttons
Actions = new List<ActionBase>()
{
new ShowCardAction()
{
Title = "Sim",
Speak = "<s>Sim</s>",
Card = AvaliarConsultor("")
},
new ShowCardAction()
{
Title = "Não",
Speak = "<s>Não</s>",
Card = PularAvaliacao()
},
}
};
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
return attachment;
}
private static AdaptiveCard PularAvaliacao()
{
//does nothing on No option from user
return new AdaptiveCard()
{ };
}
private static AdaptiveCard AvaliarConsultor(List<string> Pergunta)
{
var adaptiveCard = new AdaptiveCard()
{
Body = new List<CardElement>()
{
new TextBlock()
{
Text = "Avaliação de questionário 1!",
Weight = TextWeight.Bolder,
Size = TextSize.Large
},
new TextBlock() { Text = Pergunta[0]},
new ChoiceSet()
{
Id = "nota",
Style = ChoiceInputStyle.Compact,
IsMultiSelect = false,
Choices = new List<Choice>()
{
new Choice()
{
Title = "⭐",
Value = "1"
},
new Choice()
{
Title = "⭐⭐",
Value = "2"
},
new Choice()
{
Title = "⭐⭐⭐",
Value = "3"
},
new Choice()
{
Title = "⭐⭐⭐⭐",
Value = "4"
},
new Choice()
{
Title = "⭐⭐⭐⭐⭐",
Value = "5"
}
}
}
},
Actions = new List<ActionBase>()
{
new SubmitAction()
{
Title = "Registrar",
Speak = "<s>Registrar avaliação</s>",
DataJson = "{ \"Type\": \"Registrar\" }"
}
}
};
return adaptiveCard;
}
}
}

I need to create one TextBlock() and one ChoiceSet() block for each item from List Pergunta, but I can't do it with foreach.
To achieve your requirement, please refer to the following code snippet.
private static AdaptiveCard AvaliarConsultor(List<string> Pergunta)
{
var adaptiveCard = new AdaptiveCard()
{
Body = new List<CardElement>()
{
new TextBlock()
{
Text = "Avaliação de questionário 1!",
Weight = TextWeight.Bolder,
Size = TextSize.Large
},
},
Actions = new List<ActionBase>()
{
new SubmitAction()
{
Title = "Registrar",
Speak = "<s>Registrar avaliação</s>",
DataJson = "{ \"Type\": \"Registrar\" }"
}
}
};
//dynamically generate TextBlock and ChoiceSet
//and then add to AdaptiveCard Body
foreach (var item in Pergunta)
{
var textblock = new TextBlock() { Text = item };
var choiceset = new ChoiceSet()
{
Id = "nota",
Style = ChoiceInputStyle.Compact,
IsMultiSelect = false,
Choices = new List<Choice>()
{
new Choice()
{
Title = "⭐",
Value = "1"
},
new Choice()
{
Title = "⭐⭐",
Value = "2"
},
new Choice()
{
Title = "⭐⭐⭐",
Value = "3"
},
new Choice()
{
Title = "⭐⭐⭐⭐",
Value = "4"
},
new Choice()
{
Title = "⭐⭐⭐⭐⭐",
Value = "5"
}
}
};
adaptiveCard.Body.Add(textblock);
adaptiveCard.Body.Add(choiceset);
}
return adaptiveCard;
}
Test result:

Related

Pass result of a Adaptive card combo box to another method

I am using Adaptive card combo box to show some categories of products. Once the user clicks on the category that category should pass to another method and display all the products of that category in another adaptive card Combo Box and let user select a product.
Here is the code to get all category to combo box.
public async Task GetCategoryAdaptiveCard(IDialogContext context)
{
var replyToConversation = context.MakeMessage();
replyToConversation.Attachments = new List<Attachment>();
HttpResponseMessage response = new HttpResponseMessage();
string query = string.Format(APIChatBot + "/AllCategory");
using (var client = ClientHelper.GetClient())
{
response = await client.GetAsync(query);
}
var categoryList = await response.Content.ReadAsAsync<IEnumerable<CategoryDTO>>();
AdaptiveCard adaptiveCard = new AdaptiveCard();
adaptiveCard.Speak = "Please Select A Category from the list";
adaptiveCard.Body.Add(new TextBlock()
{
Text = "Please Select A Category from the list",
Size = TextSize.Normal,
Weight = TextWeight.Normal
});
adaptiveCard.Body.Add(new TextBlock()
{
Text = "Category List",
Size = TextSize.Normal,
Weight = TextWeight.Normal
});
List<AdaptiveCards.Choice> list = new List<AdaptiveCards.Choice>();
foreach (var item in categoryList)
{
AdaptiveCards.Choice choice = new AdaptiveCards.Choice()
{
Title = item.CategoryName,
Value = item.Id.ToString()
};
list.Add(choice);
}
adaptiveCard.Body.Add(new ChoiceSet()
{
Id = "Category",
Style = ChoiceInputStyle.Compact,
Choices = list
});
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = adaptiveCard
};
replyToConversation.Attachments.Add(attachment);
await context.PostAsync(replyToConversation);
}
Here is the method i used to get the Product for the selected category.
public async Task GetProductForCategory(IDialogContext context, string category)
{
var replyToConversation = context.MakeMessage();
replyToConversation.Attachments = new List<Attachment>();
HttpResponseMessage response = new HttpResponseMessage();
string query = string.Format(APIChatBot + "/ProductByCategory/" + category);
using (var client = ClientHelper.GetClient())
{
response = await client.GetAsync(query);
}
var productList = await response.Content.ReadAsAsync<IEnumerable<ProductDTO>>();
if(productList .Count() == 0)
{
string message = "Sorry There Are No products For this Category" + category;
await context.PostAsync(message);
}
else
{
List<AdaptiveCards.Choice> list = new List<AdaptiveCards.Choice>();
foreach (var item in productList )
{
AdaptiveCards.Choice choice = new AdaptiveCards.Choice()
{
Title = item.ProductName,
Value = item.Id.ToString()
};
list.Add(choice);
}
AdaptiveCard adaptiveCard = new AdaptiveCard();
adaptiveCard.Body.Add(new TextBlock()
{
Text = "List of Products for the Category " + category,
Size = TextSize.Normal,
Weight = TextWeight.Normal
});
adaptiveCard.Body.Add(new TextBlock()
{
Text = "Please Select A Product From The List",
Size = TextSize.Normal,
Weight = TextWeight.Normal
});
adaptiveCard.Body.Add(new ChoiceSet()
{
Id = "ProductForCategory",
Style = ChoiceInputStyle.Compact,
Choices = list
});
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = adaptiveCard
};
replyToConversation.Attachments.Add(attachment);
await context.PostAsync(replyToConversation);
}
}
How can i pass the category selected by the user to the method that selects the product based on category?
If you create an adaptive card something like this:
var reply = context.MakeMessage();
var card = new AdaptiveCard();
var choices = new List<Choice>();
choices.Add(new Choice()
{
Title = "Category 1",
Value = "c1"
});
choices.Add(new Choice()
{
Title = "Category 2",
Value = "c2"
});
var choiceSet = new ChoiceSet()
{
IsMultiSelect = false,
Choices = choices,
Style = ChoiceInputStyle.Compact,
Id = "Category"
};
card.Body.Add(choiceSet);
card.Actions.Add(new SubmitAction() { Title = "Select Category", Data = Newtonsoft.Json.Linq.JObject.FromObject(new { button = "select" }) });
reply.Attachments.Add(new Attachment()
{
Content = card,
ContentType = AdaptiveCard.ContentType,
Name = $"Card"
});
await context.PostAsync(reply);
When the user selects one of the options, and clicks the button, the resulting activity's value will be a jobject you can deserialize and use to create a product specific adaptive card:
class CategorySelection
{
public string Category { get; set; }
}
var activityValue = activity.Value as Newtonsoft.Json.Linq.JObject;
if (activityValue != null)
{
var categorySelection = activityValue.ToObject<CategorySelection>();
var category = categorySelection.Category;
//query the database for products of this category type,
//create another adaptive card displaying the products and send to user
await context.PostAsync(reply);
}

Add numbers to axes of chart

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.

Button for Toast NotificationsExtensions not appearing

This is my first time implementing a Toast notification, but I have a problem with buttons:
I am creating the Toast notification using NotificationsExtensions:
ToastContent tc = new ToastContent()
{
Visual = new ToastVisual()
{
TitleText = new ToastText() { Text = "Quick Save" },
BodyTextLine1 = new ToastText() { Text = "Type below the info that you wanna save and press enter" }
},
Actions = new ToastActionsCustom()
{
Inputs =
{
new ToastTextBox(nameBox)
{
PlaceholderContent = "type here"
}
},
Buttons =
{
new ToastButton("save", "save")
{
TextBoxId = nameBox
}
}
},
Duration = ToastDuration.Short
};
You forgot add ImageUri for your button
ToastContent tc = new ToastContent()
{
Visual = new ToastVisual()
{
TitleText = new ToastText()
{
Text = "Quick Save"
},
BodyTextLine1 = new ToastText()
{
Text = "Type below the info that you wanna save and press enter"
}
},
Actions = new ToastActionsCustom()
{
Inputs =
{
new ToastTextBox("nameBox")
{
PlaceholderContent = "type here"
}
},
Buttons =
{
new ToastButton("save", "save")
{
TextBoxId = "nameBox",
ImageUri = "Assets/check.png"
}
}
}
};
var text = tc.GetContent();
var xml = tc.GetXml();
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier().Show(toast);

Displaying data labels on open xml charts in c#

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);

Open XML data lables

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" }))),

Categories

Resources