I am trying to get a list of unique objects where each object further contains a list of unique sub-objects. Uniqueness in below example is determined by the id field in each class.
public class MyMain {
public static void main(String[] args) {
Parent p1 = new Parent(1L);
Child c11 = new Child(11L);
Child c12 = new Child(12L);
Parent p2 = new Parent(2L);
Child c21 = new Child(21L);
Child c22 = new Child(22L);
Child c23 = new Child(23L);
Holder holder1 = new Holder(p1.getId(), c11.getId());
Holder holder2 = new Holder(p1.getId(), c11.getId());
Holder holder3 = new Holder(p1.getId(), c11.getId());
Holder holder4 = new Holder(p1.getId(), c11.getId());
Holder holder5 = new Holder(p1.getId(), c12.getId());
Holder holder6 = new Holder(p1.getId(), c12.getId());
Holder holder7 = new Holder(p1.getId(), c12.getId());
Holder holder8 = new Holder(p2.getId(), c21.getId());
Holder holder9 = new Holder(p2.getId(), c21.getId());
Holder holder10 = new Holder(p2.getId(), c21.getId());
Holder holder11 = new Holder(p2.getId(), c22.getId());
Holder holder12 = new Holder(p2.getId(), c23.getId());
Holder holder13 = new Holder(p2.getId(), c23.getId());
List<Holder> holders = new ArrayList<>();
holders.add(holder1); holders.add(holder2); holders.add(holder3); holders.add(holder4);
holders.add(holder5); holders.add(holder6); holders.add(holder7); holders.add(holder8);
holders.add(holder9); holders.add(holder10); holders.add(holder11); holders.add(holder12); holders.add(holder13);
}
}
#Value
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
class Parent {
#EqualsAndHashCode.Include
public Long id;
public List<Child> chidren;
public Parent(Long id) { this.id = id; }
}
#Value
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
class Child {
#EqualsAndHashCode.Include
public Long id;
public Child(Long id) { this.id = id; }
}
#Value
class Holder {
Long parentId;
Long childId;
public Holder(Long parentId, Long childId) {
this.parentId = parentId;
this.childId = childId;
}
}
From the code fragment above, I am looking to get a List<Parent> (from holders ) that will contain two parents: p1 and p2. Each parent will then have a List<Child> containing unique children for that parent.
Expected output:
List<Parent> will have p1 and p2
p1.List<Child> will have c11 and c12 (only 2 entries)
p2.List<Child> will have c21, c22, c23 (only 3 entries)
I have worked out how to get a list of unique parents but not sure how to achieve unique children as well.
UPDATE:
Below seems to be working for me, however, not sure if there's a better way.
public class MyMain {
public static void main(String[] args) {
MyMain m = new MyMain();
Parent p1 = new Parent(1L, null);
Child c11 = new Child(11L);
Child c12 = new Child(12L);
Parent p2 = new Parent(2L, null);
Child c21 = new Child(21L);
Child c22 = new Child(22L);
Child c23 = new Child(23L);
Holder holder1 = new Holder(p1.getId(), c11.getId());
Holder holder2 = new Holder(p1.getId(), c11.getId());
Holder holder3 = new Holder(p1.getId(), c11.getId());
Holder holder4 = new Holder(p1.getId(), c11.getId());
Holder holder5 = new Holder(p1.getId(), c12.getId());
Holder holder6 = new Holder(p1.getId(), c12.getId());
Holder holder7 = new Holder(p1.getId(), c12.getId());
Holder holder8 = new Holder(p2.getId(), c21.getId());
Holder holder9 = new Holder(p2.getId(), c21.getId());
Holder holder10 = new Holder(p2.getId(), c21.getId());
Holder holder11 = new Holder(p2.getId(), c22.getId());
Holder holder12 = new Holder(p2.getId(), c23.getId());
Holder holder13 = new Holder(p2.getId(), c23.getId());
List<Holder> holders = new ArrayList<>();
holders.add(holder1); holders.add(holder2); holders.add(holder3); holders.add(holder4);
holders.add(holder5); holders.add(holder6); holders.add(holder7); holders.add(holder8);
holders.add(holder9); holders.add(holder10); holders.add(holder11); holders.add(holder12); holders.add(holder13);
Map<Long, Set<Long>> returnSet= holders.stream()
.collect(Collectors.toMap(Holder::getParentId, x -> m.uniqChildIdSet(x), MyMain::merge));
System.out.println(returnSet);
}
public static Set<Long> uniqChildIdSet(Holder holder) {
HashSet<Long> uniqChild = new HashSet();
uniqChild.add(holder.getChildId());
return uniqChild;
}
public static Set<Long> merge(Set<Long> l1, Set<Long> l2) {
l1.addAll(l2);
return l1;
}
}
#Value
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
class Parent {
#EqualsAndHashCode.Include
public Long id;
public List<Child> chidren;
public Parent(Long id, List<Child> chidren) { this.id = id;
this.chidren = chidren;
}
}
#Value
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
class Child {
#EqualsAndHashCode.Include
public Long id;
public Child(Long id) { this.id = id; }
}
#Value
class Holder {
Long parentId;
Long childId;
public Holder(Long parentId, Long childId) {
this.parentId = parentId;
this.childId = childId;
}
}
Here is what you could use, without any helper methods.
What it's basically doing is the following
Group by the Holder's parent id
For this Holder, take all the childId properties and put them in a Set<Long>
Map<Long, Set<Long>> returnSet = holders.stream()
.collect(Collectors.groupingBy(
Holder::getParentId,
Collectors.mapping(
Holder::getChildId,
Collectors.toSet()
)
)
);
Output
{1=[11, 12], 2=[21, 22, 23]}
Related
Using xamarin I would like to add a few pins to map to make a route.
My API for adding pins:
{"Id":1,"X":1.0,"Y":2.0,"RouteId":1,"Route":null}
My API for adding routes:
{"Id":1,"Name":"dd","Description":"fff"}
"RouteId:1" is associated with "Id:1"
I would like to create a route by pressing the button(OnNewRouteClicked)
My code:
public partial class CreatorPage : ContentPage
{
private CustomPin pin;
public CreatorPage()
{
InitializeComponent();
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(53.010281, 18.604922), Distance.FromMiles(1.0)));
}
private void OnClearClicked(object sender, EventArgs e)
{
customMap.Pins.Clear();
customMap.MapElements.Clear();
}
private async void OnMapClicked(object sender, MapClickedEventArgs e)
{
if (String.IsNullOrWhiteSpace(nazwaEntry.Text))
{
await DisplayAlert("Błąd", "Podaj nazwę punktu", "Ok");
return;
}
CustomPin pin = new CustomPin
{
Type = PinType.SavedPin,
Position = new Position(e.Position.Latitude, e.Position.Longitude),
Label = nazwaEntry.Text,
Address = opisEntry.Text,
Name = "Xamarin",
Url = "http://xamarin.com/about/",
Question = zagadkaEntry.Text,
Answer = odpowiedzEntry.Text
};
pin.MarkerClicked += async (s, args) =>
{
args.HideInfoWindow = true;
string pinName = ((CustomPin)s).Label;
// string pytanie = ((CustomPin)s).Question;
string opis = ((CustomPin)s).Address;
// string odpowiedz = ((CustomPin)s).Answer;
await DisplayAlert($"{pinName}", $"{opis}", "Quiz");
// await DisplayAlert("Quiz", $"{pytanie}", "Przejdź do odpowiedzi");
await Navigation.PushAsync(new QuestionPage(new Question()));
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
var json = JsonConvert.SerializeObject(new { X = pin.Position.Latitude, Y = pin.Position.Longitude });
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var result = await client.PostAsync("URL to points", content);
if (result.StatusCode == HttpStatusCode.Created)
{
await DisplayAlert("Komunikat", "Dodanie puntku przebiegło pomyślnie", "Anuluj");
}
}
private void OnNewRouteClicked(object sender, EventArgs e)
{
}
}
I wrote an example and hope it will help you. In the OnNewRouteClicked method, get all the points which routeId = 1 and draw a polyline with them:
public partial class MainPage : ContentPage
{
List<Points> myPoints { get; set; }
Routes myRoute { get; set; }
public MainPage()
{
InitializeComponent();
//Some data you get from your apis
myRoute = new Routes() { Id = 1 };
myPoints = new List<Points>();
myPoints.Add(new Points() { Id = 1, X = 55.6666, Y = 66.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 2, X = 52.6666, Y = 68.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 3, X = 53.6666, Y = 62.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 1, X = 55.6666, Y = 61.4444, RouteId = 2 }); ;
myPoints.Add(new Points() { Id = 2, X = 51.6666, Y = 65.4444, RouteId = 2 }); ;
myPoints.Add(new Points() { Id = 4, X = 54.6666, Y = 67.4444, RouteId = 1 }); ;
myPoints.Add(new Points() { Id = 5, X = 59.6666, Y = 69.4444, RouteId = 1 }); ;
}
private void OnNewRouteClicked(object sender, EventArgs e)
{
List<Position> positions = new List<Position>();
//Get all the points which RouteId = 1
foreach (var item in myPoints)
{
Points tempPoint = item as Points;
if (tempPoint.RouteId == myRoute.Id)
{
Position tempPosition = new Position(tempPoint.X,tempPoint.Y);
positions.Add(tempPosition);
}
}
//your map
Map map = new Map
{
// ...
};
// instantiate a polyline
Polyline polyline = new Polyline
{
StrokeColor = Color.Blue,
StrokeWidth = 12,
};
//add your positions to polyline.Geopath
foreach (var item in positions)
{
polyline.Geopath.Add(item);
}
// add the polyline to the map's MapElements collection
map.MapElements.Add(polyline);
}
}
public class Routes
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Points
{
public int Id { get; set; }
public double X { get; set; }
public double Y { get; set; }
public int RouteId { get; set; }
}
I am attempting to make a loan calculator that shows payment number, interest, principal, and balance in tableview in JavaFX. Right now only the principal and balance columns are populating. I am fairly new to JavaFX, so I am not sure if I have made a mistake in FX or in my formula. Here is my code:
public class LoanTable extends Application {
Integer payment;
Double interest;
Double principal;
Double balance;
#Override
public void start(Stage primaryStage) {
BorderPane border = new BorderPane();
GridPane grid = new GridPane();
ScrollPane scroll = new ScrollPane();
Label labelTitle = new Label("Enter Loan Amount, Number of Years, and Annual Interest Rate");
labelTitle.getStyleClass().add("labelTitle");
Label loan = new Label("Loan Amount");
TextField loanAmount = new TextField();
Label years = new Label("Number of Years");
TextField numYears = new TextField();
Label interestRate = new Label("Annual Interest Rate");
TextField rate = new TextField();
Button compute = new Button("Display Loan Schedule");
TableView<Finance> table = new TableView<>();
TableColumn paymentColumn = new TableColumn("Payment#");
paymentColumn.setMinWidth(200);
paymentColumn.setCellValueFactory(new PropertyValueFactory<Finance, Integer>("payment"));
TableColumn interestColumn = new TableColumn("Interest");
interestColumn.setMinWidth(200);
interestColumn.setCellValueFactory(new PropertyValueFactory<Finance, Double>("interest"));
TableColumn prinColumn = new TableColumn("Principal");
prinColumn.setMinWidth(200);
prinColumn.setCellValueFactory(new PropertyValueFactory<Finance, Double>("principal"));
TableColumn balColumn = new TableColumn("Balance");
balColumn.setMinWidth(200);
balColumn.setCellValueFactory(new PropertyValueFactory<Finance, Double>("balance"));
table.getColumns().addAll(paymentColumn, interestColumn, prinColumn, balColumn);
grid.add(labelTitle, 0, 0);
grid.add(new Label(), 0, 1);
grid.add(loan, 0, 2);
grid.add(loanAmount, 1, 2);
grid.add(years, 0, 3);
grid.add(numYears, 1, 3);
grid.add(interestRate, 0, 4);
grid.add(rate, 1, 4);
grid.add(compute, 4, 0);
scroll.setContent(table);
border.setTop(grid);
border.setBottom(scroll);
Scene scene = new Scene(border, 800, 800);
scene.getStylesheets().add("loan_table.css");
primaryStage.setScene(scene);
primaryStage.show();
compute.setOnAction((e) -> {
Double loanTotal = Double.parseDouble(loanAmount.getText());
Integer year = Integer.parseInt(numYears.getText());
Double rateInterest = Double.parseDouble(rate.getText());
double monthlyInterest = rateInterest / 1200;
double monthlyPayment = loanTotal * monthlyInterest / (1 - 1 / Math.pow(1 + monthlyInterest, year * 12));
balance = loanTotal;
for(int i = 1; i < year * 12; i++) {
interest = monthlyInterest * balance;
principal = monthlyPayment - interest;
balance = balance - principal;
payment = i + 1;
}
ObservableList<Finance> data = FXCollections.observableArrayList(new Finance(payment, interest, principal, balance));
table.setItems(data);
});
}
public static class Finance {
private final SimpleIntegerProperty payment;
private final SimpleDoubleProperty interest;
private final SimpleDoubleProperty principal;
private final SimpleDoubleProperty balance;
private Finance(int payment, double interest, double principal, double balance) {
this.payment = new SimpleIntegerProperty(payment);
this.interest = new SimpleDoubleProperty(interest);
this.principal = new SimpleDoubleProperty(principal);
this.balance = new SimpleDoubleProperty(balance);
}
public Integer getPayment(int numYears) {
return payment.get();
}
public Double getInterest(double rate) {
return interest.get();
}
public Double getPrincipal() {
return principal.get();
}
public Double getBalance() {
return balance.get();
}
}
public static void main(String[] args) {
launch(args);
}
}
I was really hoping someone could help me,
I need to get the variable product from the method GridView1_RowDataBound to the quote value class string product.
Its for a pdf creator and any help would be greatly appreciated as i've been stuck on this for quite a while, please excuse as I'm fairly inexperienced in .net.
Thanks very much!!
enter code here
public partial class quotedetail : System.Web.UI.Page
{
private string quoteId;
private string product;
private string connectId = "";
string description = "Save Your Quote as a PDF with your Company Logo and Print out for Customers";
public string ConnectId { get { return connectId; } }
protected void Page_Init(object sender, EventArgs e)
{
connectId = Global.GetConnectionString();
quoteId = Request.QueryString["quote"];
product =
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
(Master as WebOnlineMasterPage).PageTitle = "Quote - " + quoteId;
DisplayPage();
}
}
protected void DisplayPage()
{
try
{
DataSet ds = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
FormView1.DataSource = ds.Tables[0];
GridView1.DataSource = ds.Tables[1];
Page.DataBind();
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Global.CheckException(ex);
description = "Sorry, information about this quote is unavailable.";
Panel1.Visible = false;
}
(Master as WebOnlineMasterPage).PageDescription = description;
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
protected void FormView1_DataBound(object sender, EventArgs e)
{
// get the expiry date
bool isopen = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["IsOpen"];
bool expired = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["Expired"];
int viewIndex = 0;
if (isopen && !expired)
viewIndex = 1;
// set appropriate view
MultiView view = (MultiView)FormView1.FindControl("QuoteProcessView");
view.ActiveViewIndex = viewIndex;
}
protected void AcceptQuote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("checkout.aspx?quote=" + quoteId);
}
protected void Requote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("requestquote.aspx?quote=" + quoteId);
}
// ********************PDF Start********************
protected void SaveAsPdf_Click(object sender, EventArgs e)
{
DataSet quote = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
Document document = CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = document;
renderer.RenderDocument();
MemoryStream ms = new MemoryStream();
renderer.PdfDocument.Save(ms);
byte[] pdfBytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=quote.pdf");
Response.AddHeader("Content-Length", pdfBytes.Length.ToString());
Response.BinaryWrite(pdfBytes);
Response.StatusCode = 200;
Response.End();
}
public Document CreateDocument()
{
Document document = new Document();
document.Info.Title = "A sample invoice";
document.Info.Subject = "Demonstrates how to create an invoice.";
DefineStyles(document);
TextFrame addressFrame;
MigraDoc.DocumentObjectModel.Tables.Table table;
CreatePage(document, out addressFrame, out table );
FillContent(document, addressFrame, table);
return document;
}
void DefineStyles(Document document)
{
// Get the predefined style Normal.
MigraDoc.DocumentObjectModel.Style style = document.Styles["Normal"];
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Verdana";
style = document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
style = document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Verdana";
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
// Create a new style called Reference based on style Normal
style = document.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "5mm";
style.ParagraphFormat.SpaceAfter = "5mm";
style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}
void CreatePage(Document document, out TextFrame addressFrame, out MigraDoc.DocumentObjectModel.Tables.Table table)
{
// Each MigraDoc document needs at least one section.
Section section = document.AddSection();
// Put a logo in the header
MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(Server.MapPath("~/images/cnwlogo.jpg"));
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
addressFrame = section.AddTextFrame();
addressFrame.Height = "3.0cm";
addressFrame.Width = "7.0cm";
addressFrame.Left = ShapePosition.Left;
addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
addressFrame.Top = "5.0cm";
addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = addressFrame.AddParagraph("PowerBooks Inc · Sample Street 42 · 56789 Cologne");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("INVOICE", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Cologne, ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
table = section.AddTable();
table.Style = "Table";
table.Borders.Color = Colors.DarkBlue;
table.Borders.Width = 0.25;
table.Borders.Left.Width = 0.5;
table.Borders.Right.Width = 0.5;
table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
Column column = table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("5cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
CreateHeaderRow(table);
table.SetEdge(0, 0, 7, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, Color.Empty);
//create data table
}
private static void CreateHeaderRow(MigraDoc.DocumentObjectModel.Tables.Table table)
{
Row headerRow1 = table.AddRow();
headerRow1.HeadingFormat = true;
headerRow1.Format.Alignment = ParagraphAlignment.Center;
headerRow1.Format.Font.Bold = true;
headerRow1.Shading.Color = Colors.AliceBlue;
headerRow1.Cells[0].AddParagraph("PRODUCT");
headerRow1.Cells[0].Format.Font.Bold = false;
headerRow1.Cells[0].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[0].MergeDown = 1;
headerRow1.Cells[1].AddParagraph("DESCRIPTION");
headerRow1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[1].MergeDown = 1;
headerRow1.Cells[2].AddParagraph("QTY");
headerRow1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[2].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[2].MergeDown = 1;
headerRow1.Cells[3].AddParagraph("UNIT");
headerRow1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[3].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[3].MergeDown = 1;
headerRow1.Cells[4].AddParagraph("PRICE");
headerRow1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[4].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[4].MergeDown = 1;
headerRow1.Cells[5].AddParagraph("TAX");
headerRow1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[5].MergeDown = 1;
headerRow1.Cells[6].AddParagraph("TOTAL");
headerRow1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[6].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[6].MergeDown = 1;
}
class QuoteItemRow
{
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductID"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
public QuoteItemRow(decimal quantity, decimal price, decimal discount, string itemNumber, string title)
{
Quantity = quantity;
Price = price;
Discount = discount;
ItemNumber = itemNumber;
Title = title;
}
public decimal Quantity;
public decimal Discount;
public decimal Price;
public string ItemNumber;
public string Title;
}
void FillContent(Document document, TextFrame addressFrame, MigraDoc.DocumentObjectModel.Tables.Table table)
{
Paragraph paragraph = addressFrame.AddParagraph();
paragraph.AddText("Joe Bloggs");
paragraph.AddLineBreak();
paragraph.AddText("12 Some St");
paragraph.AddLineBreak();
paragraph.AddText(product);
// Iterate the invoice items
decimal totalExtendedPrice = 0;
QuoteItemRow[] items = new QuoteItemRow[] {
new QuoteItemRow (2.0m, 3.4m, 0.2m, "3213421", product ),
new QuoteItemRow (2.4m, 3.4m, 0.0m, "3534DD21", quoteId ),
new QuoteItemRow (8, 0.4m, 0.1m, "908587", quoteId ),
};
foreach (QuoteItemRow item in items)
{
decimal quantity = item.Quantity;
decimal price = item.Price;
decimal discount = item.Discount;
// Each item fills two rows
Row row1 = table.AddRow();
Row row2 = table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Colors.LightGray;
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
paragraph = row1.Cells[1].AddParagraph();
paragraph.AddFormattedText(item.Title, TextFormat.Bold);
row2.Cells[1].AddParagraph(item.Quantity.ToString());
row2.Cells[2].AddParagraph("$" + price.ToString("0.00"));
row2.Cells[3].AddParagraph("$" + discount.ToString("0.0"));
row2.Cells[4].AddParagraph();
row2.Cells[5].AddParagraph("$" + price.ToString("0.00"));
decimal extendedPrice = quantity * price;
extendedPrice = extendedPrice * (100 - discount) / 100;
row1.Cells[5].AddParagraph("$" + extendedPrice.ToString("0.00"));
row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
totalExtendedPrice += extendedPrice;
table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
}
// Add an invisible row as a space line to the table
Row row = table.AddRow();
row.Borders.Visible = false;
// Add the total price row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Total Price");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Add the VAT row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("VAT (19%)");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph((0.19m * totalExtendedPrice).ToString("0.00") + " €");
// Add the additional fee row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Shipping and Handling");
row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
// Add the total due row
row = table.AddRow();
row.Cells[0].AddParagraph("Total Due");
row.Cells[0].Borders.Visible = false;
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
totalExtendedPrice += 0.19m * totalExtendedPrice;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Set the borders of the specified cell range
table.SetEdge(5, table.Rows.Count - 4, 1, 4, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
// Add the notes paragraph
paragraph = document.LastSection.AddParagraph();
paragraph.Format.SpaceBefore = "1cm";
paragraph.Format.Borders.Width = 0.75;
paragraph.Format.Borders.Distance = 3;
paragraph.Format.Borders.Color = Colors.DarkBlue;
paragraph.Format.Shading.Color = Colors.LightGray;
}
}
Easiest solution would be to put the value in a Session
Session.Add("ProductCode", ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
To get the value:
Session["ProductCode"].ToString()
Keep in mind though that you are doing this in the item databound, in the event that you are expecting multiple values for product code, I would suggest storing the values in a collection prior to putting it in the Session.
i.e.
if(Session["ProductCode"] != null)
{
List<string> pcodes = Session["ProductCode"] as List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
else
{
List<string> pcodes = new List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
To get the values:
Session["ProductCode"] as List<string>()
Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.
I am trying to bind generic list to DropDownList an i am not sure how to continue.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
public class Paths
{
public string orignalPathName;
public int orignalPathId;
public string newPathName;
}
public static List<Paths> GetOriginalPaths()
{
return PrepareOriginalPathsData();
}
public static List<Paths> PrepareOriginalPathsData()
{
List<Paths> objPaths = new List<Paths> {
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp1", orignalPathId= 1} ,
new Paths{orignalPathName = "comp2", orignalPathId= 2} ,
new Paths{orignalPathName = "comp3", orignalPathId= 3} ,
new Paths{orignalPathName = "comp4", orignalPathId= 4}
};
return objPaths;
}
public static List<Paths> GetNewPaths(int orignalPathId)
{
List<Paths> lstNewPaths = new List<Paths>();
Paths objnewPaths = null;
var newPath = (from np in PrepareNewPathsData() where np.orignalPathId == orignalPathId select new { newpathname = np.newPathName, orgId = np.orignalPathId });
foreach (var np in newPath)
{
objnewPaths = new Paths();
objnewPaths.orignalPathId = np.orgId;
objnewPaths.newPathName = np.newpathname;
lstNewPaths.Add(objnewPaths);
}
return lstNewPaths;
}
public static List<Paths> PrepareNewPathsData()
{
List<Paths> objNewPaths = new List<Paths> {
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part1", orignalPathId= 1} ,
new Paths{newPathName = "part3", orignalPathId= 2} ,
new Paths{newPathName = "part4", orignalPathId= 3} ,
new Paths{newPathName = "part5", orignalPathId= 4} ,
};
return objNewPaths;
}
Fix it!
I had to add this:
public class Paths
{
public string orignalPathName { get; set; }
public int orignalPathId { get; set; }
public string newPathName { get; set; }
}
Your problem might be from the bind prospective you might bind only if not post back!!
If(!Page.IsPostBack)
{
List<Paths> paths = new List<Paths>();
paths = GetOriginalPaths();
DropDownList1.DataSource = paths;
DropDownList1.DataTextField = "orignalPathName";
DropDownList1.DataValueField = "orignalPathId";
DropDownList1.DataBind();
}
What problem are you encountering exactly?
By the way, the DataValueField should be unique. Aas it is it could cause an issue either with the bind, or on post-back.