How to add Category names in search in Nopcommerce 3.8 - nopcommerce

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'.

Related

send data to RoutingSlipCompleted consume method from activity

I have some data in activity which I want to get it in RoutingSlipCompleted consume method. I know we can send data with CompletedWithVariables from a activity to b activity. But I was wondering how it is possible to get data from activity in RoutingSlipCompleted. so this is my activity:
public class CheckInventoryActivity : IActivity<ICheckInventoryRequest, CheckInventoryRequestCompensate>
{
private readonly IInventoryService _inventoryService;
private readonly IEndpointNameFormatter _formatter;
public CheckInventoryActivity(IInventoryService inventoryService, IEndpointNameFormatter formatter)
{
_inventoryService = inventoryService;
_formatter = formatter;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ICheckInventoryRequest> context)
{
CheckInventoryRequest model = new CheckInventoryRequest()
{
PartCode = context.Arguments.PartCode
};
var response = await _inventoryService.CheckInventory(model);
var checkInventoryResponse = new CheckInventoryResponse()
{
PartCode = response.Data.PartCode ?? model.PartCode,
Id = response.Data.Id ?? 0,
InventoryCount = response.Data.InventoryCount ?? 0
};
var checkInventoryCustomActionResult = new CustomActionResult<CheckInventoryResponse>()
{
Data = checkInventoryResponse,
IsSuccess = true,
ResponseDesc = "success",
ResponseType = 0
};
var result = response.IsSuccess;
if (!result)
return context.CompletedWithVariables<CheckInventoryRequestCompensate>(
new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
}, new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
});
var queueName = _formatter.ExecuteActivity<CallSuccessActivity, ISuccessRequest>();
var uri = new Uri($"queue:{queueName}");
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so by the following line of codes I can get data in CallSuccessActivity:
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so I can get this data here:
public class CallSuccessActivity : IExecuteActivity<ISuccessRequest>
{
private readonly IRequestClient<ISuccessRequest> _requestClient;
public CallSuccessActivity(IRequestClient<ISuccessRequest> requestClient)
{
_requestClient = requestClient;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ISuccessRequest> context)
{
var iModel = context.Arguments;
var model = new SuccessRequest()
{
LogDate = iModel.LogDate,
MethodName = iModel.MethodName,
CheckInventoryCustomActionResult = iModel.CheckInventoryCustomActionResult
};
//CustomActionResult< CheckInventoryResponse > CheckInventoryResponse = new ();
var rabbitResult = await _requestClient.GetResponse<CustomActionResult<SuccessResponse>>(model);
return context.Completed();
}
}
I want to get this iModel.CheckInventoryCustomActionResult in RoutingSlipCompleted :
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
var requestId =
context.Message.GetVariable<Guid?>(nameof(ConsumeContext.RequestId));
var checkInventoryResponseModel = context.Message.Variables["CheckInventoryResponse"];
var responseAddress =
context.Message.GetVariable<Uri>(nameof(ConsumeContext.ResponseAddress));
var request =
context.Message.GetVariable< ICheckInventoryRequest > ("Model");
throw new NotImplementedException();
}
Instead of putting the value into the activity arguments, add it as a variable:
return context.ReviseItinerary(x =>
{
x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity"
});
x.AddVariable("CheckInventoryCustomActionResult", checkInventoryCustomActionResult);
});

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

import excel file to database using EPPlus

I am having a hard time understanding what should be a simple task. I am now using EPPlus to help me with this task. However, I am at a point of where I can't track what is going on. (per the comment below and days of google searching) I'm trying to read in an excel file and pass that to my EF model. It breaks down at line 159 where I am trying to put in the values from the excel file but keeps coming across as null. However when looking at the values past line 159 they all have the correct information. I am not sure how to even track a bug like this.
TruckController.cs
// POST: Trucks/Import
[HttpPost]
public ActionResult Import(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["file"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
file.SaveAs(Server.MapPath("~/" + "test.xlsx"));
//string fileName = file.FileName;
// string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
// var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
var MyImport = new List<string>();
MyImport = ImportDataRecords(new FileInfo(Server.MapPath("~/" ) + "test.xlsx"));
}
}
return View("Import");
}
public List<string> ImportDataRecords(FileInfo file)
{
var resultMessages = new List<string>();
var totalImported = 0;
try
{
using (var excelPackage = new ExcelPackage(file))
{
string DeliveryColumn,
ItemNoColumn,
MaterialColumn,
MaterialDescriptionColumn,
DeliveryQtytoPickColumn,
PickedQuantityColumn,
SalesUoMColumn,
BatchPickedColumn,
BinNoColumn,
BagWeightColumn,
PalletNoColumn,
PalletStackingNoColumn,
StageNoColumn,
SubStopNoColumn,
PickStatusColumn,
PackStatusColumn,
SoldToColumn,
SoldToNameColumn,
ShipToNameColumn;
if (!file.Name.EndsWith("xlsx"))
{
resultMessages.Add("File selected is not an Excel file");
return resultMessages;
}
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null)
{
resultMessages.Add("File was empty");
return resultMessages;
}
using (var headers = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
var expectedHeaders = new[]
{
"Delivery", "Item No.", "Material", "Material Description", "Delivery Qty to Pick",
"Picked Quantity", "Sales UoM", "Batch Picked", "BIN No.", "Bag Weight", "Pallet No.",
"Pallet Stacking No", "Stage No", "Sub Stop No", "Pick Status", "Pack Status", "Sold-To",
"Sold-To Name", "Ship-To Name"
};
if (!expectedHeaders.All(e => headers.Any(h => h.Value.Equals(e))))
{
resultMessages.Add("Some columns are missing from the file");
return resultMessages;
}
DeliveryColumn = headers.First(h => h.Value.Equals("Delivery")).Address[0].ToString();
ItemNoColumn = headers.First(h => h.Value.Equals("Item No.")).Address[0].ToString();
MaterialColumn = headers.First(h => h.Value.Equals("Material")).Address[0].ToString();
MaterialDescriptionColumn = headers.First(h => h.Value.Equals("Material Description")).Address[0].ToString();
DeliveryQtytoPickColumn = headers.First(h => h.Value.Equals("Delivery Qty to Pick")).Address[0].ToString();
PickedQuantityColumn = headers.First(h => h.Value.Equals("Picked Quantity")).Address[0].ToString();
SalesUoMColumn = headers.First(h => h.Value.Equals("Sales UoM")).Address[0].ToString();
BatchPickedColumn = headers.First(h => h.Value.Equals("Batch Picked")).Address[0].ToString();
BinNoColumn = headers.First(h => h.Value.Equals("BIN No.")).Address[0].ToString();
BagWeightColumn = headers.First(h => h.Value.Equals("Bag Weight")).Address[0].ToString();
PalletNoColumn = headers.First(h => h.Value.Equals("Pallet No.")).Address[0].ToString();
PalletStackingNoColumn = headers.First(h => h.Value.Equals("Pallet Stacking No")).Address[0].ToString();
StageNoColumn = headers.First(h => h.Value.Equals("Stage No")).Address[0].ToString();
SubStopNoColumn = headers.First(h => h.Value.Equals("Sub Stop No")).Address[0].ToString();
PickStatusColumn = headers.First(h => h.Value.Equals("Pick Status")).Address[0].ToString();
PackStatusColumn = headers.First(h => h.Value.Equals("Pack Status")).Address[0].ToString();
SoldToColumn = headers.First(h => h.Value.Equals("Sold-To")).Address[0].ToString();
SoldToNameColumn = headers.First(h => h.Value.Equals("Sold-To Name")).Address[0].ToString();
ShipToNameColumn = headers.First(h => h.Value.Equals("Ship-To Name")).Address[0].ToString();
using (var context = new EPPlusTruckContext())
{
var lastRow = worksheet.Dimension.End.Row;
for (var row = 2; row <= lastRow; row++)
{
-----------Line 159-------------> var truck = new Truck()
{
Delivery = worksheet.Cells[DeliveryColumn + row].Value.ToString(),
ItemNo = worksheet.Cells[ItemNoColumn + row].Value.ToString(),
Material = worksheet.Cells[MaterialColumn + row].Value.ToString(),
MaterialDescription = worksheet.Cells[MaterialDescriptionColumn + row].Value.ToString(),
DeliveryQtyToPick = worksheet.Cells[DeliveryQtytoPickColumn + row].Value.ToString(),
PickedQuantity = worksheet.Cells[PickedQuantityColumn + row].Value.ToString(),
SalesUoM = worksheet.Cells[SalesUoMColumn + row].Value.ToString(),
BatchPicked = worksheet.Cells[BatchPickedColumn + row].Value.ToString(),
BinNo = worksheet.Cells[BinNoColumn + row].Value.ToString(),
BagWeight = worksheet.Cells[BagWeightColumn + row].Value.ToString(),
PalletNo = worksheet.Cells[PalletNoColumn + row].Value.ToString(),
PalletStackingNo = worksheet.Cells[PalletStackingNoColumn + row].Value.ToString(),
StageNo = worksheet.Cells[StageNoColumn + row].Value.ToString(),
SubStopNo = worksheet.Cells[SubStopNoColumn + row].Value.ToString(),
PickStatus = worksheet.Cells[PickStatusColumn + row].Value.ToString(),
PackStatus = worksheet.Cells[PackStatusColumn + row].Value.ToString(),
SoldTo = worksheet.Cells[SoldToColumn + row].Value.ToString(),
SoldToName = worksheet.Cells[SoldToNameColumn + row].Value.ToString(),
ShipToName = worksheet.Cells[ShipToNameColumn + row].Value.ToString(),
};
db.Trucks.Add(truck);
try
{
db.SaveChanges();
totalImported++;
}
catch (Exception ex)
{
resultMessages.Add(string.Format("Record on line#{0} failed: {1}\n", row, ex.Message));
}
}
}
}
resultMessages.Insert(0, string.Format("{0} records successfully imported.\n", totalImported));
return resultMessages;
}
}
catch (IOException ex)
{
resultMessages.Add("File still open. Please close Excel file before importing.");
return resultMessages;
}
}
A simple example here:
Reff: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}

null104Invalid MailChimp "Invalid MailChimp API key: xxxx.."

I am trying this code for creating new campaign using MailChimp API in ASP.NET
public string CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID = string.Empty;
MailChimpManager mc = new MailChimpManager("sampleAPIKeyXXXXXXXXXXXXXX-us12");
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "wisdomthnkrs#gmail.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
campaignCreateOpt.authenticate = true;
campaignCreateOpt.auto_footer = false;
campaignCreateOpt.tracking.opens = true;
campaignCreateOpt.tracking.html_clicks = true;
campaignCreateOpt.tracking.text_clicks = true;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2", "ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
//Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreateParms campaignCreateParms = new campaignCreateParms(mc.APIKey, EnumValues.campaign_type.regular, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campCreateInput);
//xyz();
//string abc = xxxxxxxxxxxxxxxxx;
campaignCreateOutput ccOutput = campaignCreate.Execute(campCreateInput);
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
string s = "null";
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
s = s + ae.code;
s = s + ae.error;
}
}
return s;
}
but it shows an error while I am giving the right key.
here is the error,
null104Invalid MailChimp "Invalid MailChimp API key:
6ea29f158xxxxxxxxxxxx"

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