MvcxGridview with datatype System.Byte[] - devexpress

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

Related

How to style Excel cell using Open XML

I have a requirement for export data to excel using open Xml plug in. And I want to style excel head boarder colour. I tried different method to achieve my requirement. Its done, But I couldn't not style particular cells (or columns). I have to add boarder and background to my excel cell.
My Code as following
public ActionResult exxx()
{
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
//First cell
SheetData sd = new SheetData();
Row r1 = new Row() { RowIndex = (UInt32Value)1u };
Cell c1 = new Cell();
c1.DataType = CellValues.String;
c1.CellValue = new CellValue("some value");
r1.Append(c1);
// Second cell
Cell c2 = new Cell();
c2.CellReference = "C1";
c2.DataType = CellValues.String;
c2.CellValue = new CellValue("other value");
r1.Append(c2);
sd.Append(r1);
//third cell
Row r2 = new Row() { RowIndex = (UInt32Value)2u };
Cell c3 = new Cell();
c3.DataType = CellValues.String;
c3.CellValue = new CellValue("some string");
Cell c4 = new Cell();
c4.DataType = CellValues.String;
c4.CellValue = new CellValue("some car");
r2.Append(c3);
r2.Append(c4);
sd.Append(r2);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "first sheet";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
string fileName = "getdata.xlsx";
Response.Clear();
byte[] dt = ms.ToArray();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
Response.BinaryWrite(dt);
Response.End();
return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "getdata.xlsx");
}
My expected result:
enter image description here
You need to create the style part and reference it by Cell c1 = new Cell() { StyleIndex = (UInt32Value)1U };.
Check
public ActionResult CreateExcel()
{
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorkbookStylesPart workbookStylesPart1 = wbp.AddNewPart<WorkbookStylesPart>("rId3");
GenerateWorkbookStylesPart1Content(workbookStylesPart1);
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
//First cell
SheetData sd = new SheetData();
Row r1 = new Row() { RowIndex = (UInt32Value)1u };
Cell c1 = new Cell() { StyleIndex = (UInt32Value)1U };
c1.DataType = CellValues.String;
c1.CellValue = new CellValue("some value");
r1.Append(c1);
// Second cell
Cell c2 = new Cell() { StyleIndex = (UInt32Value)1U };
c2.CellReference = "C1";
c2.DataType = CellValues.String;
c2.CellValue = new CellValue("other value");
r1.Append(c2);
sd.Append(r1);
//third cell
Row r2 = new Row() { RowIndex = (UInt32Value)2u };
Cell c3 = new Cell();
c3.DataType = CellValues.String;
c3.CellValue = new CellValue("some string");
Cell c4 = new Cell();
c4.DataType = CellValues.String;
c4.CellValue = new CellValue("some car");
r2.Append(c3);
r2.Append(c4);
sd.Append(r2);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "first sheet";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
string fileName = "getdata.xlsx";
Response.Clear();
byte[] dt = ms.ToArray();
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
//Response.BinaryWrite(dt);
//Response.End();
return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "getdata.xlsx");
}
private void GenerateWorkbookStylesPart1Content(WorkbookStylesPart workbookStylesPart1)
{
Stylesheet stylesheet1 = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac x16r2" } };
stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
stylesheet1.AddNamespaceDeclaration("x16r2", "http://schemas.microsoft.com/office/spreadsheetml/2015/02/main");
Fonts fonts1 = new Fonts() { Count = (UInt32Value)2U, KnownFonts = true };
Font font1 = new Font();
FontSize fontSize1 = new FontSize() { Val = 11D };
Color color1 = new Color() { Theme = (UInt32Value)1U };
FontName fontName1 = new FontName() { Val = "Calibri" };
FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering() { Val = 2 };
FontScheme fontScheme1 = new FontScheme() { Val = FontSchemeValues.Minor };
font1.Append(fontSize1);
font1.Append(color1);
font1.Append(fontName1);
font1.Append(fontFamilyNumbering1);
font1.Append(fontScheme1);
Font font2 = new Font();
FontSize fontSize2 = new FontSize() { Val = 11D };
Color color2 = new Color() { Theme = (UInt32Value)0U };
FontName fontName2 = new FontName() { Val = "Calibri" };
FontFamilyNumbering fontFamilyNumbering2 = new FontFamilyNumbering() { Val = 2 };
FontScheme fontScheme2 = new FontScheme() { Val = FontSchemeValues.Minor };
font2.Append(fontSize2);
font2.Append(color2);
font2.Append(fontName2);
font2.Append(fontFamilyNumbering2);
font2.Append(fontScheme2);
fonts1.Append(font1);
fonts1.Append(font2);
Fills fills1 = new Fills() { Count = (UInt32Value)3U };
Fill fill1 = new Fill();
PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None };
fill1.Append(patternFill1);
Fill fill2 = new Fill();
PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };
fill2.Append(patternFill2);
Fill fill3 = new Fill();
PatternFill patternFill3 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor1 = new ForegroundColor() { Rgb = "FF0070C0" };
BackgroundColor backgroundColor1 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill3.Append(foregroundColor1);
patternFill3.Append(backgroundColor1);
fill3.Append(patternFill3);
fills1.Append(fill1);
fills1.Append(fill2);
fills1.Append(fill3);
Borders borders1 = new Borders() { Count = (UInt32Value)2U };
Border border1 = new Border();
LeftBorder leftBorder1 = new LeftBorder();
RightBorder rightBorder1 = new RightBorder();
TopBorder topBorder1 = new TopBorder();
BottomBorder bottomBorder1 = new BottomBorder();
DiagonalBorder diagonalBorder1 = new DiagonalBorder();
border1.Append(leftBorder1);
border1.Append(rightBorder1);
border1.Append(topBorder1);
border1.Append(bottomBorder1);
border1.Append(diagonalBorder1);
Border border2 = new Border();
LeftBorder leftBorder2 = new LeftBorder() { Style = BorderStyleValues.Double };
Color color3 = new Color() { Auto = true };
leftBorder2.Append(color3);
RightBorder rightBorder2 = new RightBorder() { Style = BorderStyleValues.Double };
Color color4 = new Color() { Auto = true };
rightBorder2.Append(color4);
TopBorder topBorder2 = new TopBorder() { Style = BorderStyleValues.Double };
Color color5 = new Color() { Auto = true };
topBorder2.Append(color5);
BottomBorder bottomBorder2 = new BottomBorder() { Style = BorderStyleValues.Double };
Color color6 = new Color() { Auto = true };
bottomBorder2.Append(color6);
DiagonalBorder diagonalBorder2 = new DiagonalBorder();
border2.Append(leftBorder2);
border2.Append(rightBorder2);
border2.Append(topBorder2);
border2.Append(bottomBorder2);
border2.Append(diagonalBorder2);
borders1.Append(border1);
borders1.Append(border2);
CellStyleFormats cellStyleFormats1 = new CellStyleFormats() { Count = (UInt32Value)1U };
CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U };
cellStyleFormats1.Append(cellFormat1);
CellFormats cellFormats1 = new CellFormats() { Count = (UInt32Value)2U };
CellFormat cellFormat2 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U };
CellFormat cellFormat3 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true };
cellFormats1.Append(cellFormat2);
cellFormats1.Append(cellFormat3);
CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U };
CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U };
cellStyles1.Append(cellStyle1);
DifferentialFormats differentialFormats1 = new DifferentialFormats() { Count = (UInt32Value)0U };
TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
StylesheetExtensionList stylesheetExtensionList1 = new StylesheetExtensionList();
StylesheetExtension stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
X14.SlicerStyles slicerStyles1 = new X14.SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" };
stylesheetExtension1.Append(slicerStyles1);
StylesheetExtension stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
X15.TimelineStyles timelineStyles1 = new X15.TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" };
stylesheetExtension2.Append(timelineStyles1);
stylesheetExtensionList1.Append(stylesheetExtension1);
stylesheetExtensionList1.Append(stylesheetExtension2);
stylesheet1.Append(fonts1);
stylesheet1.Append(fills1);
stylesheet1.Append(borders1);
stylesheet1.Append(cellStyleFormats1);
stylesheet1.Append(cellFormats1);
stylesheet1.Append(cellStyles1);
stylesheet1.Append(differentialFormats1);
stylesheet1.Append(tableStyles1);
stylesheet1.Append(stylesheetExtensionList1);
workbookStylesPart1.Stylesheet = stylesheet1;
}

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

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

ASP.Net - Conditions within a public class

I have this public class below and I want to include a condition which placed it inside and it doesn't work. Any suggestions?
public SummaryDates GetSummaryDates()
{
SummaryDates result = new SummaryDates();
var getDay = 3;
DateTime now = DateTime.UtcNow.Date;
var getMonth = 0;
var getQuarter = 0;
var quarterNow = now.AddMonths(3 * getQuarter);
var quarterNumber = Math.Ceiling(quarterNow.Month / 3m);
var quarterLabel2 = 0;
var quarterLabel1 = 0;
var quarterLabelA = 0;
var quarterLabelB = 0;
result.summaryDates = new SummaryDates
{
startOfQuarter2 = now,
endOfQuarter2 = now,
endOfQuarter2Plus1Day = now,
endOfQuarter1Plus1Day = now,
startOfQuarter1 = now,
endOfQuarter1 = now,
startOfQuarterA = now,
startOfQuarterB = now,
endOfQuarterA = now,
endOfQuarterB = now,
endOfQuarterAPlus1Day = now,
endOfQuarterBPlus1Day = now,
if (quarterNumber == 4)
{
startOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 10, 01);
endOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 12, 31);
endOfQuarter2Plus1Day = getSummaryDates.endOfQuarter2.AddDays(1);
quarterLabel2 = Convert.ToInt16(Math.Ceiling(getSummaryDates.endOfQuarter2.Month / 3m));
}
return result;
}
}
I've placed the conditions inside. It doesn't work.

Display nom from another table in gridview

i want display not idchef but nomchef there a relation between table projet and table chef and when i use tolist it display the idchef
how can i display nom from table chef not idchef from table projet
and this is code controller:
public ActionResult ListeProjets()
{
GestionprojetEntities db = new GestionprojetEntities();
var model = db.Projet.ToList();
return View("ListeProjets", model);
}
and this is code view :
#using GestionProjet.Models;
#model List<GestionProjet.Models.Projet>
#{
ViewBag.Title = "ListeProjets";
}
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GridView";
settings.KeyFieldName = "Id";
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsBehavior.AllowFocusedRow = true;
settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
settings.ClientSideEvents.RowClick = "function(s, e){rowSelected(s, e)}";
settings.Columns.Add("Nom");
settings.Columns.Add("Description");
settings.Columns.Add("Datedebut");
settings.Columns.Add("Complexite");
settings.Columns.Add("Taille");
settings.Columns.Add("IdChef");
settings.Columns.Add("IdClient");
settings.CommandColumn.Visible = true;
settings.Width = Unit.Percentage(100);
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowTitlePanel = true;
settings.Settings.ShowFooter = true;
settings.CommandColumn.Width = System.Web.UI.WebControls.Unit.Pixel(160);
settings.Styles.GroupRow.Font.Bold = true;
settings.Styles.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#F7EEEE");
settings.SettingsText.Title = "Liste Des Projets";
settings.SettingsText.GroupPanel = "Liste Des Projets";
}).Bind(Model).GetHtml()
can someone help me fix this and thank you
How about like this:
BoundField col= new BoundField();
col.DataField = "IdChef";
col.Headertext = "nomChef";
settings.Columns.Add(col);

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