How to bind data form database to a existing table in powerpoint using open xml - asp.net

I using openxml to create a powerpoint from an web app.I created a ppt with charts and opened ppt in openxml sdk productivity tool and code which was generated with that i modified the chart data which is coming from database,Code for which i created to modify the chart data as
created a class for the code in the sdk,in that CreatePart() i added these links
ChartPart chartPart1 = slidePart1.AddNewPart<ChartPart>("rId3");
GenerateChartPart1Content(chartPart1);
// This is below code added
#if true // Injects the chart part modification process
var chartModifier1 = new ChartPartModifier();
chartModifier1.UpdateSecondChartPart(chartPart1);
#endif
EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId2");
GenerateEmbeddedPackagePart1Content(embeddedPackagePart1);
and created a class for ChartPartModifier()
public void UpdateSecondChartPart(ChartPart chartPart)
{
// Searchs SeriesText and its Values to replace them with your dynamic data
var seriesLabels = chartPart.ChartSpace.Descendants<SeriesText>().ToList();
var seriesValues = chartPart.ChartSpace.Descendants<Values>().ToList();
var categoryAxis = chartPart.ChartSpace.Descendants<CategoryAxisData>().ToList();
for (int i = 0; i < this._lineSecCharts.Count; ++i)
{
var yourLine = this._lineSecCharts[i];
var label = seriesLabels[i].Descendants<NumericValue>().FirstOrDefault();
var values = seriesValues[i].Descendants<NumericValue>().ToList();
var categories = categoryAxis[i].Descendants<NumericValue>().ToList();
// Replaces the label of the series
label.Text = yourLine.Label;
// Replaces the values of the series
for (int valIdx = 0; valIdx < values.Count(); ++valIdx)
{
values[valIdx].Text = yourLine.Plots[valIdx].Value.ToString();
categories[valIdx].Text = yourLine.Plots[valIdx].Category;
}
}
}
Like this is there any way to modify the data in the table,If so can any one provide me the solution is much appreciated.

I found answer after a research i'm able to update the table values from database using openxml
the below code which(if condition) added between table appending the rows and graphicdata appending
table1.Append(tableProperties1);
table1.Append(tableGrid1);
table1.Append(tableRow1);
table1.Append(tableRow2);
table1.Append(tableRow3);
table1.Append(tableRow4);
table1.Append(tableRow5);
table1.Append(tableRow6);
table1.Append(tableRow7);
#if true // Injects the table modification process
TableModifier tableModifier = new TableModifier();//Create a class
tableModifier.UpdateTable(table1);//Send the table object of which you wanted to update
#endif
graphicData1.Append(table1);
graphic1.Append(graphicData1);
In class of TableModifier
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
public class TableModifier
{
public TableModifier()
{
this.SetupDataSource();
}
public void UpdateTable(Table table)
{
var rows = table.Descendants<TableRow>().ToList();
for (int r = 0; r < rows.Count(); ++r)
{
var yourRow = this._rows[r];
var cells = rows[r].Descendants<TableCell>().ToList();
for (int c = 0; c < cells.Count(); ++c)
{
var yourCell = yourRow.Cells[c];
var text = cells[c].Descendants<Text>().FirstOrDefault();
if (text != null)
{
text.Text = yourCell.Value;
}
}
}
}
private void SetupDataSource()
{
this._rows.Add(new Row()
{
Cells = new List<Cell>()
{
new Cell(){ Value = "Products" },
new Cell(){ Value = "2010" },
new Cell(){ Value = "2011" },
new Cell(){ Value = "2012" },
}
});
for (int i = 0; i < 6; ++i)
{
var productName = string.Format("Product {0}", (char)(i + 'A'));
this._rows.Add(new Row()
{
Cells = new List<Cell>()
{
new Cell(){ Value = productName },
new Cell(){ Value = "10%" },
new Cell(){ Value = "20%" },
new Cell(){ Value = "30%" },
}
});
}
}
#region Private Data Structure
private class Row
{
public List<Cell> Cells { get; set; }
}
private class Cell
{
public string Value { get; set; }
}
#endregion
private List<Row> _rows = new List<Row>();
}

Related

Add data only once

I am updating data and then I am adding them back to my list. However if I pres the update button few times on the row I will get the same line repeated few times. Can you please help how to add updated data without duplication?
First I remove
private void OnItemSelected(DocumentData selectedItem)
{
var index = Results.IndexOf(selectedItem);
Results.Remove(selectedItem);
Navigation.PushPopupAsync(new EditPopUp(selectedItem, this, index));
}
And then I update
public void UpdateValue(DocumentData selectedItem, int index)
{
var detail = new DocumentData()
{
FieldValue = selectedItem.FieldValue,
FieldDescriptor = selectedItem.FieldDescriptor,
Size = LoadSize(),
Padding = LoadPadding(),
};
Results.Insert(index, detail);
}
check for the existence of a matching item before you insert
var exists = Results.Any(r => r.FieldValue == selectedItem.FieldValue && r.FieldDescriptor == selectedItem.FieldDescriptor);
if (!exists) {
var detail = new DocumentData()
{
FieldValue = selectedItem.FieldValue,
FieldDescriptor = selectedItem.FieldDescriptor,
Size = LoadSize(),
Padding = LoadPadding(),
};
Results.Insert(index, detail);
}

Xamarin Forms - Create Entry or Picker dynamically based on a property and bind it to a ObservableCollection object

I have a xamarin forms application that receives data from the database. The database gives "Car" data back. Those objects all have a couple of properties. On of those properties decides what kind of view should be shown on the screen. So a car could have a property named "TypeOfView" with a value "Entry" or "Picker" etc..
The problem is a follows: How can I dynamically create views based on that property and how can that be bind to objects in a list in the viewmodel?
// This is the codebehind where UI controls get created
BindingContext = DependencyInjectionService.Get<CheckListEditViewModel>();
var stack = new StackLayout()
{
Orientation = StackOrientation.Vertical,
Padding = 5
};
for (int i = 0; i < (BindingContext as CheckListEditViewModel).CheckListItems.Count; i++)
{
var item = (BindingContext as CheckListEditViewModel).CheckListItems[i];
var description = new Label()
{
Text = item.Description
};
stack.Children.Add(description);
if ((item.ChecklistItemType == Domain.ChecklistItemType.Number))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Numeric;
numerEntry.TextChanged += MyMethod;
numerEntry.SetBinding(Entry.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(numerEntry);
// this is to test if the binding worked
var testLabelBindingTesting = new Label();
testLabelBindingTesting.SetBinding(Label.TextProperty, new Binding(mode: BindingMode.TwoWay, path: "Value", source: item));
stack.Children.Add(testLabelBindingTesting);
}
else if ((item.ChecklistItemType == Domain.ChecklistItemType.Email))
{
var numerEntry = new Entry();
numerEntry.Keyboard = Keyboard.Email;
stack.Children.Add(numerEntry);
}
}
Content = stack;
// The list is in the viewmodel class:
public ObservableCollection<ChecklistItem> CheckListItems { get; set; }

How do I create a dynamic Linq query to fill an ASP.NET databound ListView?

I am having some trouble figuring out the right way to go about creating a dynamic query that I can use values from DropDownList controls to filter and sort/order the results of a database query to fill a ListView. I am able to hard code individual queries, which works ok, except for the fact that it takes an incredible amount of effort, and is not easily changed.
My code is as follows (using all filters):
queryResult = From product In myEntities.InventoryProducts
Where product.VendorID = ddlFilterVendor.SelectedValue And product.ItemType = ddlItemType.SelectedValue And product.LabelSize = ddlLabelSize.SelectedValue And product.PrintLabel = boolPrint And product.Edited = boolEdited
Order By product.ID Ascending
Select product
Return queryResult
Is there a better method to this? I would like to be able to select the value from each DropDownList and generate a custom WHERE clause, as well as an ORDER BY clause.
Any help would be greatly appreciated, thanks.
I can give you a simple example as to how to to proceed with your idea. I am sure if you look through StackOverflow or search via google you will get code that does a better job of dynamic expression building. The same concept can be used for order by.
void Main()
{
var ops = new List<Ops>
{
new Ops
{
OperandType = typeof(string),
OpType=OpType.Equals,
OperandName = "Name",
ValueToCompare = "MM" // in your case this will be the values from the dropdowns
},
new Ops
{
OperandType = typeof(int),
OpType=OpType.Equals,
OperandName = "ID",
ValueToCompare = 1
},
};
var testClasses = new List<TestClass>
{
new TestClass { ID =1, Name = "MM", Date = new DateTime(2014,12,1)},
new TestClass { ID =2, Name = "BB", Date = new DateTime(2014,12,2)}
};
// this will produce prop => ((prop.Name == "MM") And (prop.ID == 1))
var whereDelegate = ExpressionBuilder.BuildExpressions<TestClass>(ops);
foreach(var item in testClasses.Where(whereDelegate))
{
Console.WriteLine("ID " +item.ID);
Console.WriteLine("Name " +item.Name);
Console.WriteLine("Date" + item.Date);
}
}
// Define other methods and classes here
public enum OpType
{
Equals
}
public class Ops
{
public Type OperandType {get; set;}
public OpType OpType {get; set;}
public string OperandName {get;set;}
public object ValueToCompare {get;set;}
}
public class TestClass
{
public int ID {get;set;}
public string Name {get; set;}
public DateTime Date {get;set;}
}
public class ExpressionBuilder
{
public static Func<T,bool> BuildExpressions<T>( List<Ops> opList)
{
Expression currentExpression= null;
var parameterExpression = Expression.Parameter(typeof(T), "prop");
for(int i =0; i< opList.Count; i++)
{
var op = opList[i];
Expression innerExpression = null;
switch(op.OpType)
{
case OpType.Equals :
{
var propertyExpression = Expression.Property(parameterExpression ,
op.OperandName);
var constExpression = Expression.Constant(op.ValueToCompare);
innerExpression = Expression.Equal(propertyExpression,
constExpression);
break;
}
}
if (i >0)
{
currentExpression = Expression.And(currentExpression, innerExpression);
}
else
{
currentExpression = innerExpression;
}
}
var lambdaExpression = Expression.Lambda<Func<T,bool>>(currentExpression,
new []{parameterExpression });
Console.WriteLine(lambdaExpression);
return lambdaExpression.Compile() ;
}
}

How to create Multiple worksheet in Excel?

I am creating Excel using DocumentFormat.OpenXml in ASP.Net.
Can anybody have idea how can create Multiple worksheet in Excel.
For ex. Sheet1, Sheet2, Sheet3...... sheetn
Try the following method:
/// <summary>
/// Add a blank worksheet to the workbook
/// </summary>
/// <param name="workbookPart">Wookbook part</param>
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
// Create the new worksheet
Worksheet worksheet = new Worksheet();
worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 15D };
SheetData sheetData1 = new SheetData();
PageMargins pageMargins1 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
PageSetup pageSetup1 = new PageSetup() { Orientation = OrientationValues.Portrait, Id = "rId1" };
worksheet.Append(sheetDimension1);
worksheet.Append(sheetViews1);
worksheet.Append(sheetFormatProperties1);
worksheet.Append(sheetData1);
worksheet.Append(pageMargins1);
worksheet.Append(pageSetup1);
newWorksheetPart.Worksheet = worksheet;
newWorksheetPart.Worksheet.Save();
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
}
EDIT
Here is the class that contains the method:
public static class ExcelHelpers
{
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{...}
}
Open up your excel document like this and call the method:
public static void Export(string document)
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(document, true))
{
ExcelHelpers.InsertBlankWorksheet(doc.WorkbookPart);
}
}

C# 3 collection problem

Why in C# 3 I can do this:
DataTable dt = new DataTable() {
Columns = { "1", "2", "3" } };
But I can't do this:
class Person {
int Id { get; set; }
}
class Program {
static void Main(string[] args)
{
var v = new List<Person> { 1, 2, 3 };
}
}
Because there is not implicit conversion from int to Person. If you were to define an implicit conversion for Person, that should work:
http://msdn.microsoft.com/en-us/library/z5z9kes2(v=VS.100).aspx
Note in the example that a double value is implicitly convertable to a Digit type. You could define an implicit conversion for int to Person.
Neither 1, nor 2, nor 3 are Person objects.
You could, though try:
var people = new List<Person>() { new Person() { Id = 1 }, new Person() { Id = 2 } , new Person() { Id = 3 } };
Because and integer is not the same as a Person object, and the Id is a property that needs to be assigned to.
var v = new List<Person>();
for (i = 1; i <= 3; i++) {
var p = new Person() {
Id = i;
}
v.Add(p);
}
You need to call the constructor to actually instance it. In your code you are basically saying that Person is of type int and this is not the case, the variable inside is.
You can do something like this to achieve what you want.
var v = new List<Person>() { new Person(1), new Person(2), new Person(3) };
Given that you have a constructor that accepts an int.
Like this one:
public Person(int id)
{
Id = id;
}

Resources