call Api from server side not in client side - asp.net

How Can I call the Request Get (Api) from server side.
Here is the Server side
public string GetAllBook()
{
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
}
And here is the Api Request
public List<Book> Get()
{
BookAssembly searchallbook = new BookAssembly();
return searchallbook.GetBooks();
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in bookList)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}
i want remove bookList = bookassembleur.GetBooks() ana call api

You have to access it using HttpClient.
e.g.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("<your_api_path>");
var response= client.GetAsync("GetAllBook");
response.Wait();
BookAssembly searchallbook = response.Result;
}
P.S. this is not running code, just an idea.

public string GetAllBook()
{
DataTable dt = new DataTable();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6735/api/book");
//HTTP GET
var responseTask = client.GetAsync("Book");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Book[]>();
readTask.Wait();
var Books = readTask.Result;
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in Books)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
}
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}

Related

Dealing with Empty cells from Excel export

I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
This is how my code looks like:
My GetData methode from the Database:
public void GetData()
{
try
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["GS1connectionString"].ConnectionString);
connection.Open();
using (SqlCommand sqlCmd = new SqlCommand("DAtabase.dbo.SP_EXPORT", connection)) //Extract data: no cons first and cons after
{
sqlCmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["TaskTable"] = dt;
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found, try again');", true);
}
}
Clean dataTable methode:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
The Export to excel button:
protected void Button_Export_DS_Click(object sender, EventArgs e)
{
GetData();
DataTable dat = new DataTable();
DataTable dtNew = new DataTable();
dat = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dat);
//Export to excel from datatable stored in a session
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=DS_Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
}
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
You copy and paste this function:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count ; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
And then use the function like this:
DataTable dt = new DataTable();
DataTable dtNew = new DataTable();
dt = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dt);
After that, use this dtNew in this:
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}

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"

Issues on converting the java code to c#

I tried to convert java code into cSharp .I struct on how to encode the data so please help me how to do that..
I tried to pass the values directly without encoding then i got the error as
The remote server returned an error: (400) Bad Request.
if i removed the headers then the error is not coming and i placed the break point in the web site the execution sequence is not stopped at the break point
this is my java code
packagename=encodeData("some value");
username=encodeData("some value");
password=encodeData("some value");
hc= new DefaultHttpClient();
get= new HttpGet("http://techpalle.com/skillgun_App.svc/mobile/papers/"+chap_id+"/app");
get.setHeader(PaperActivity.this.getString(R.string.username),username);
get.setHeader(PaperActivity.this.getString(R.string.password),password);
get.setHeader(PaperActivity.this.getString(R.string.packagename),packagename);
Converted csharp code is
string username=null;
string password=null;
string packagename=null;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://localhost:2850/TechpalleNew/Skillgun_App.svc/mobile/chapters/" + "16" + "/app");
wr.Headers["username"] = "username";
wr.Headers["password"] = "password";
wr.Headers["packagename"] = "packagename";
WebResponse resp = wr.GetResponse();
StreamReader read = new StreamReader(resp.GetResponseStream());
string res = read.ReadToEnd();
My website code
namespace ISkillgun_App
{
[ServiceContract]
public interface ISkillgun_App
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/chapters/{sub_topic_id}/app")]
List<ChapterNames> Chapters_Names(string sub_topic_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/papers/{chapter_id}/app")]
List<Paper_Ids> Paper_ids(string chapter_id);
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, UriTemplate = "mobile/questions/{paper_id}/app")]
List<Qtions_data> Qtions_data(string paper_id);
}
}
namespace Skillgun_App:ISkillgun_App
{
public List<ChapterNames> Chapters_Names(string sub_topic_id)
Breakppoint {
List<ChapterNames> chptrsdetails = new List<ChapterNames>();
using (SqlConnection cn = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand("skillgun_mobile_app_Qtions_data", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlParameter p1 = new SqlParameter("#type", SqlDbType.VarChar, 20);
SqlParameter p2 = new SqlParameter("#topic_or_paper_id", SqlDbType.Int);
p1.Value = "chapters_data";
p2.Value = sub_topic_id;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add("#username", SqlDbType.VarChar, 40);
cmd.Parameters["#username"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 40);
cmd.Parameters["#password"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#package_name", SqlDbType.VarChar, 50);
cmd.Parameters["#package_name"].Direction = ParameterDirection.Output;
cn.Open();
SqlDataReader drtopics = cmd.ExecuteReader();
while (drtopics.Read())
{
ChapterNames qbsubchapter = new ChapterNames();
qbsubchapter.Qbc_id = (int)drtopics["qbc_id"];
qbsubchapter.Qbc_nameofChapter = drtopics["qbc_nameofChapter"].ToString();
qbsubchapter.Qbc_no_of_papers = (int)drtopics["qbc_no_of_papers"];
qbsubchapter.Qbc_no_of_questions = (int)drtopics["qbc_no_of_questions"];
chptrsdetails.Add(qbsubchapter);
}
drtopics.Close();
cn.Close();
string topic_username = cmd.Parameters["#username"].Value.ToString();
string topic_password = cmd.Parameters["#password"].Value.ToString();
string topic_package_name = cmd.Parameters["#package_name"].Value.ToString();
bool result = check_user(topic_username, topic_password, topic_package_name);
if (result == true)
return chptrsdetails;
else
return null;
}
catch (SqlException ex)
{
return null;
}
finally
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
}
}
}
}
public bool check_user(string topic_username, string topic_password, string topic_package_name)
{
string requestedUrl = OperationContext.Current.IncomingMessageHeaders.To.AbsoluteUri;
if (WebOperationContext.Current != null)
{
if (WebOperationContext.Current.IncomingRequest != null)
{
if (WebOperationContext.Current.IncomingRequest.Headers["username"] != null && WebOperationContext.Current.IncomingRequest.Headers["password"] != null && WebOperationContext.Current.IncomingRequest.Headers["packagename"] != null)
{
string username = WebOperationContext.Current.IncomingRequest.Headers["username"];
string pwd = WebOperationContext.Current.IncomingRequest.Headers["password"];
string pckgname = WebOperationContext.Current.IncomingRequest.Headers["packagename"];
bool result = Base64Decode(username, pwd, pckgname, topic_username, topic_password, topic_package_name);
if (result == true)
return true;
else
return false;
}
}
}
return false;
}
For html encoding (you don't specify other), use the static method
HttpUtility.HtmlEncode(string)
http://www.dotnetperls.com/httputility

How to call a function with struct as input?

Here is my struct definition, function and the portion calling the function.
public struct NewSigningRequest
{
public string SerialNumber;
//public string Requestor;
public string Sponsor;
public string Approver;
public string BusinessJustification;
public byte[] DebugFile;
public string DebugFileName;
public string FirmwareVersion;
public string FirmwareDescription;
public byte[] SmokeTestResult;
public string ProductName;
public string SigningType;
}
static public bool CreateSigningRequest(NewSigningRequest Request)
{
Request = new NewSigningRequest();
bool succeeded = false;
string sqlcmdString = sqlQueryNewSigningRequest;
SqlConnection con = new SqlConnection(connection);
SqlCommand Insertcmd = new SqlCommand(sqlcmdString, con);
SqlParameter SerialNumber = new SqlParameter("#SerialNumber", SqlDbType.NVarChar, 50);
SerialNumber.Value = Request.SerialNumber;
Insertcmd.Parameters.Add(SerialNumber);
SqlParameter Requestor = new SqlParameter("#Requestor", SqlDbType.NVarChar, 20);
Requestor.Value = GetRequestor.GetRequestorAlias();
Insertcmd.Parameters.Add(Requestor);
SqlParameter Sponsor = new SqlParameter("#Sponsor", SqlDbType.NVarChar, 20);
Sponsor.Value = Request.Sponsor;
Insertcmd.Parameters.Add(Sponsor);
SqlParameter BusinessJustification = new SqlParameter("#BusinessJustification", SqlDbType.NVarChar, 2000);
BusinessJustification.Value = Request.BusinessJustification;
Insertcmd.Parameters.Add(BusinessJustification);
SqlParameter DebugFile = new SqlParameter("#DebugFile", SqlDbType.VarBinary, 8000);
DebugFile.Value = Request.DebugFile;
Insertcmd.Parameters.Add(DebugFile);
SqlParameter DebugFileName = new SqlParameter("#DebugFileName", SqlDbType.NVarChar, 100);
DebugFileName.Value = Request.DebugFileName;
Insertcmd.Parameters.Add(DebugFileName);
SqlParameter ProductName = new SqlParameter("#ProductName", SqlDbType.NVarChar, 20);
ProductName.Value = Request.ProductName;
Insertcmd.Parameters.Add(ProductName);
SqlParameter SigningType = new SqlParameter("#SigningType", SqlDbType.NVarChar, 10);
SigningType.Value = Request.SigningType;
Insertcmd.Parameters.Add(SigningType);
SqlParameter FirmwareVersion = new SqlParameter("#FirmwareVersion", SqlDbType.NVarChar, 50);
FirmwareVersion.Value = Request.FirmwareVersion;
Insertcmd.Parameters.Add(FirmwareVersion);
SqlParameter FirmwareDescription = new SqlParameter("#FirmwareDescription", SqlDbType.NVarChar, 250);
FirmwareDescription.Value = Request.FirmwareDescription;
Insertcmd.Parameters.Add(FirmwareDescription);
SqlParameter SmokeTestResult = new SqlParameter("#SmokeTestResult", SqlDbType.VarBinary, 8000);
SmokeTestResult.Value = Request.SmokeTestResult;
Insertcmd.Parameters.Add(SmokeTestResult);
return succeeded;
}
this is how I am trying to call it
NewSigningRequest Request;
byte[] bin;
string FileName;
if (FileUpload.HasFile)
{
bin = new byte[FileUpload.PostedFile.ContentLength];
HttpPostedFile mybin = FileUpload.PostedFile;
FileName = mybin.FileName;
mybin.InputStream.Read(bin, 0, FileUpload.PostedFile.ContentLength);
}
else
{
bin = null;
FileName = "";
}
string NameAlias = #HttpContext.Current.User.Identity.Name;
int index = NameAlias.IndexOf("\\") + 1;
string sAlias = NameAlias.Substring(index);
byte[] SmokeTest;
if (FileUploadSTR.HasFile)
{
SmokeTest = new byte[FileUploadSTR.PostedFile.ContentLength];
HttpPostedFile mySmokeTest = FileUploadSTR.PostedFile;
mySmokeTest.InputStream.Read(SmokeTest, 0, FileUploadSTR.PostedFile.ContentLength);
}
else
{
SmokeTest = null;
}
Request.SerialNumber = TextBoxSerialNumber.Text;
Request.Sponsor = TextBoxSponsor.Text;
Request.BusinessJustification = TextBoxBJ.Text;
if (bin == null)
{
Request.DebugFile = new byte[0];
}
else
{
Request.DebugFile = bin;
}
Request.DebugFileName = FileName;
Request.FirmwareVersion = TextBoxFV.Text;
Request.FirmwareDescription = TextBoxFD.Text;
if (TextBoxSigningType.Text == string.Empty)
{
Request.SigningType = drp2.SelectedValue.ToString();
}
else
{
Request.SigningType = TextBoxSigningType.Text.ToUpper();
}
if (SmokeTest == null)
{
Request.SmokeTestResult = new byte[0];
}
else
{
Request.SmokeTestResult = SmokeTest;
}
SurfaceSignDBAccess.CreateSigningRequest(Request);
upon calling this function, gives error saying that "use of unassigned local variable 'Request'."
What should be the right way to call this function?
NewSigningRequest Request; - is never initialized in the method, before calling
SurfaceSignDBAccess.CreateSigningRequest(Request);
try this:
var request = new NewSigningRequest();// in the first line of code of the second code snippet.
And in the static method, remove the following code.
Request = new NewSigningRequest();

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