DevExpress MVC 17.1 How to open a Popup Window when the ValueChange event is called in a LargeDataComboBox - devexpress

I need that at the time the ValueChanged event of the LargeDataComboBox is called (when I click on a row in the drop-down list) a Popup Window is displayed.
_searchPanel.cshtml
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBoxSearchPanel";
settings.Height = 30;
settings.SelectedIndex = 0;
settings.Properties.DropDownStyle = DropDownStyle.DropDown;
settings.CallbackRouteValues = new { Controller = "SearchPanel", Action = "SearchPanel" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
settings.Properties.FilterMinLength = 2;
settings.Properties.ClearButton.DisplayMode = ClearButtonDisplayMode.OnHover;
settings.Properties.ValueField = "id_usuario";
settings.Properties.ValueType = typeof(string);
settings.Properties.TextFormatString = "{0} {1}";
settings.Properties.Columns.Add(column =>
{
column.FieldName = "iduser";
column.Caption = "User";
});
settings.Properties.Columns.Add(column =>
{
column.FieldName = "fullname";
column.Caption = "FUllName";
column.Width = 175;
});
settings.Properties.ClientSideEvents.ValueChanged = "function(s, e) { OnValueChangeSearchPanel(s, e)}";
}
).BindList(Model).GetHtml()
function where the ValueChanged event is called
function OnValueChangeSearchPanel(s, e) {
var x = s.GetSelectedItem().text.split(" ");
console.log(x[0]);
//I need to replace the alert with a popup
alert(x[0]);
}
_popupWindow.cshtml
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupUser";
settings.AllowDragging = true;
settings.ShowOnPageLoad = true;
settings.CloseAction = CloseAction.CloseButton;
settings.HeaderText = "User";
settings.SetContent(() =>
{
ViewContext.Writer.Write(
"<h1>" + "Welcome" + "</h1>"
);
});
Diagram of how it should work

The code below does the trick
function OnValueChangeSearchPanel(s, e) {
var x = s.GetSelectedItem().text.split(" ");
popupUser.Show();
}
Your Helper should look like this (complete code here)
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupUser";
settings.AllowDragging = true;
settings.ShowOnPageLoad = true;
settings.EnableClientSideAPI = true;
settings.CloseAction = CloseAction.CloseButton;
settings.PopupAction = PopupAction.None;
settings.HeaderText = "User";
settings.SetContent(() =>
{
ViewContext.Writer.Write(
"<h1>" + "Welcome" + "</h1>"
);
});

Related

How to Autolink the url in Trix Editor

When we paste the content in trix-editor the href not getting paste as simple text. How can we make it as a link.
var TrixAutoLinker,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
addEventListener("trix-initialize", function(event) {
return new TrixAutoLinker(event.target);
});
TrixAutoLinker = (function() {
var INPUT, PATTERN, isValidURL;
function TrixAutoLinker(element) {
this.element = element;
this.autoLink = bind(this.autoLink, this);
this.editor = this.element.editor;
this.element.addEventListener("trix-render", this.autoLink);
this.autoLink();
}
TrixAutoLinker.prototype.autoLink = function() {
var currentRange, i, len, range, ref, ref1, results1, url;
ref = this.getURLsWithRanges();
results1 = [];
for (i = 0, len = ref.length; i < len; i++) {
ref1 = ref[i], url = ref1.url, range = ref1.range;
if (this.getHrefAtRange(range) !== url) {
currentRange = this.editor.getSelectedRange();
this.editor.setSelectedRange(range);
if (this.editor.canActivateAttribute("href")) {
this.editor.activateAttribute("href", url);
}
results1.push(this.editor.setSelectedRange(currentRange));
} else {
results1.push(void 0);
}
}
return results1;
};
TrixAutoLinker.prototype.getDocument = function() {
return this.editor.getDocument();
};
TrixAutoLinker.prototype.getDocumentString = function() {
return this.getDocument().toString();
};
TrixAutoLinker.prototype.getHrefAtRange = function(range) {
return this.getDocument().getCommonAttributesAtRange(range).href;
};
PATTERN = /(https?:\/\/\S+\.\S+)\s/ig;
TrixAutoLinker.prototype.getURLsWithRanges = function() {
var match, position, range, results, string, url;
results = [];
string = this.getDocumentString();
while (match = PATTERN.exec(string)) {
url = match[1];
if (isValidURL(url)) {
position = match.index;
range = [position, position + url.length];
results.push({
url: url,
range: range
});
}
}
return results;
};
INPUT = document.createElement("input");
INPUT.type = "url";
INPUT.required = true;
isValidURL = function(value) {
INPUT.value = value;
return INPUT.checkValidity();
};
return TrixAutoLinker;
})();
// ---
// generated by coffee-script 1.9.2

How to add Category names in search in Nopcommerce 3.8

Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.

change visbilite text in devexpress asp.net

i need to set visibilité false in textbox and i nned to let him invisible and this the propriété of my code :
#Html.DevExpress().TextBox(
f =>
{
f.Name = "codeclient";
f.Text = "";
f.Width = 300;
f.Enabled = false;
f.Height = 30;
f.Properties.NullText = " choisir client";
}).GetHtml()
can someone help me how to change visiblité of textbox from visible to invisible
#Html.DevExpress().TextBox(
f =>
{
f.Name = "codeclient";
f.Text = "";
f.Width = 300;
f.Enabled = false;
f.ClientVisible = false;
f.Height = 30;
f.Properties.NullText = " choisir client";
}).GetHtml()
add f.ClientVisible = false;

MvcxGridview with datatype System.Byte[]

I'm using MvcxGridView to bind a DataTable model and I have a problem with a DataColumn with datatype System.Byte[].
When I view data, gridview does not show a value and only displays System.Byte[]. I want the GridView to display a picture in that column.
When I save data, I get this message:
Invalid cast from 'System.String' to 'System.Byte[]'
How can I solve these problems?
Here is my code in view:
#using System.Data;
#model TestPA6MVC.Models.EntityModelForViewDataSettingGrid
#functions{
MVCxGridViewCommandColumn CreateCommandColumn(string AllowEdit,string AllowAdd)
{
MVCxGridViewCommandColumn column = new MVCxGridViewCommandColumn();
column.Visible = true;
column.NewButton.Visible = (AllowAdd.ToLower()=="true")?true:false;
column.DeleteButton.Visible = (AllowEdit.ToLower() == "true") ? true : false; ;
//column.EditButton.Visible = true;
return column;
}
}
#{
var grid = Html.DevExpress().GridView(
settings => {
settings.Name = "gvEditing";
settings.CallbackRouteValues = new {
Controller = "Home", Action = "GridViewPartial",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew", ViewName = Model.ViewName };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate", ViewName = Model.ViewName };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete", ViewName = Model.ViewName };
settings.SettingsEditing.BatchUpdateRouteValues = new {
Controller = "Home", Action = "BatchEditingUpdateModel",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
if (Model.AllowEdit.ToLower() == "true")
{
settings.SettingsEditing.Mode = GridViewEditingMode.Batch;//Kieu view chinh sua
}
else { settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm; }
settings.SettingsBehavior.ConfirmDelete = true;//Cho phep hien thi thong bao xac nhan
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;//Cho phep chinh sua do rong cot
settings.Width = 800;//Chieu rong cua gridview
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Mode = GridViewPagerMode.ShowPager;
settings.SettingsPager.PageSize = 50;
settings.Settings.VerticalScrollableHeight = 300;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowHeaderFilterButton = true;//Hien thi bo loc cho column
//Tao cot gia de tranh tinh trang hien thi lai cac Column an khi Callback
MVCxGridViewColumn fakeco = new MVCxGridViewColumn();
fakeco.Visible = false;
fakeco.Width = 0;
fakeco.EditFormSettings.Visible = DefaultBoolean.False;
settings.Columns.Add(fakeco);
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.DataBound = (sender, e) =>
{
//Build Column Tool Automatic
((MVCxGridView)sender).Columns.Insert(0, CreateCommandColumn(Model.AllowEdit,Model.AllowAdd));
//Add custom Column
foreach (var child in Model.ModelForDisplayColumnList)
{
MVCxGridViewColumn dc = new MVCxGridViewColumn();
dc.Caption = child.Caption;
dc.FieldName = child.ColumnName;
if(child.IsHidden)//Neu de an hoan toan se khong lay duoc du lieu da chinh sua
{ dc.Width = 0; }
//dc.Visible = !child.IsHidden;
dc.ReadOnly = child.IsReadOnly;
switch (child.DataType)
{
case "datetime":
dc.ColumnType = MVCxGridViewColumnType.DateEdit;
var DateEditProperties = dc.PropertiesEdit as DateEditProperties;
DateEditProperties.DisplayFormatString = "dd/MM/yyyy hh:mm tt";
//Cho phep chinh ngay, gio
DateEditProperties.UseMaskBehavior = true;
//Dinh dang hien thi khi chinh sua
DateEditProperties.EditFormat = EditFormat.Custom;
DateEditProperties.EditFormatString = "dd/MM/yyyy hh:mm tt";
DateEditProperties.TimeSectionProperties.Visible = true;//Hien khung chinh gio
break;
case "combobox":
dc.ColumnType = MVCxGridViewColumnType.ComboBox;
var DropDownEditProperties = dc.PropertiesEdit as ComboBoxProperties;
DropDownEditProperties.DataSource = child.DataSourceForComboBoxColumn;
DropDownEditProperties.ValueField = child.DataSourceForComboBoxColumn.Columns[0].ColumnName;
DropDownEditProperties.TextFormatString = "{0}";
foreach (DataColumn childcolumn in child.DataSourceForComboBoxColumn.Columns)
{
DropDownEditProperties.Columns.Add(childcolumn.ColumnName, childcolumn.ColumnName);
}
break;
case "boolean":
case "bit":
dc.ColumnType = MVCxGridViewColumnType.CheckBox;
break;
case "byte[]":
dc.ColumnType = MVCxGridViewColumnType.BinaryImage;
//var ImageEditProperties = dc.PropertiesEdit as BinaryImageEditProperties;
//ImageEditProperties.ImageWidth = 50;
//ImageEditProperties.ImageHeight = 50;
break;
//case "string":
// dc.ColumnType = MVCxGridViewColumnType.ComboBox;
// var ComboBoxEditProperties = dc.PropertiesEdit as ComboBoxProperties;
// ComboBoxEditProperties.DataSource = ModelForDisplayColumnList;
// ComboBoxEditProperties.TextField = "DataType";
// ComboBoxEditProperties.ValueField = "Caption";
// break;
}
((MVCxGridView)sender).Columns.Add(dc);
}
};
settings.KeyFieldName = Model.PrimaryKeyCollection;
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.Bind(Model.DataSourceForGrid).GetHtml()

Editing PresentationML using openxml

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.

Resources