Microsoft Interop Outlook c# - invalidcastexception? - interop

Suddenly getting a System.invalidcastexception: unable to cast COM object of type 'system._object' to interface type 'Microsoft.office.interop.outlook.mailitem' ... to a program I wrote that was working fine and now BAM! Exception.
Not sure why... please note I'm a novice programmer.
Here's a snippet of coding where I'm using the Outlook things :
using Microsoft.Office.Interop.Outlook;
static Microsoft.Office.Interop.Outlook.Application app = null;
static _NameSpace ns = null;
static MailItem item = null;
static MAPIFolder inboxFolder = null;
static MAPIFolder dest = null;
static void SendMail(string mailSubject, string htmlMailBody, string mailTo)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
outlookNS.Logon(Missing.Value, Missing.Value, true, true);
MailItem oMsg = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
oMsg.To = mailTo;
oMsg.Recipients.ResolveAll();
StreamReader sr = new StreamReader(#"C:\Users\" + WindowsIdentity.GetCurrent().Name.Split('\\')[1] + #"\AppData\Roaming\Microsoft\Signatures\Default.htm");
string signature = sr.ReadToEnd();
oMsg.Subject = mailSubject;
oMsg.HTMLBody = htmlMailBody + "<br><br>" + signature + "</font>";
oMsg.Save();
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
oMsg = null;
outlookNS = null;
outlookApp = null;
}
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
#region match - convert - extract
foreach (string tifFile in Directory.GetFiles(workFolder, "*.tif", SearchOption.TopDirectoryOnly))
{
string currentFile = Path.GetFileNameWithoutExtension(tifFile);
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
//##############CODE CRASHES HERE##############
item = (MailItem)inboxFolder.Items[i];
// item = inboxFolder.Items[i];
if (item.Body != "")
{
if ((item.Body.Contains("Box Number =")) && (item.Body.Contains("Contract ID = ")) && (item.Body.Contains("Branch = ")) && (item.Body.Contains(currentFile.Replace('_', '/'))))
{
// matchFound = true;
MailStack current = new MailStack();
Console.WriteLine("________________________");
Console.WriteLine("File matched \t\t:\t" + currentFile + ".tif");
I've looked around but can't make much sense of the answers available.
any help appreciated.

Try this...
item = inboxFolder.Items[i] as MailItem;
if (item != null)
{
// ...
}

Related

Can't find way to debug Internal Server Error (500) caused by new class

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`
I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

Inserting image in PPTX using OpenXML does not work

I am trying to generate a PowerPoint file containing a image using OpenXML. Unfortunately it does not work. The image is not being displayed. I've checked the file generated with the OpenXML productivity tool and I respectively unzipped the file contents. The file itself contains the image in /ppt/media/image.png and it should be displayed in the second slide.
Here's my code:
private void InsertSlide(string chartString, int position, string title, string text = "")
{
if (m_presentation == null || title == null || m_presentation.PresentationPart == null)
return;
var slide = new Slide(new CommonSlideData(new ShapeTree()));
var nonVisualProperties =
slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
var slidePart = m_presentation.PresentationPart.AddNewPart<SlidePart>();
var imagePart = slidePart.AddImagePart(ImagePartType.Png, "irgendeinscheiss");
//var imageStream = new MemoryStream(Convert.FromBase64String(chartString));
using (var imageStream = new FileStream(#"C:\Users\DA\Desktop\Charts\1_Chart2_01.png", FileMode.Open))
{
imageStream.Position = 0;
imagePart.FeedData(imageStream);
}
slide.Save(slidePart);
var slideIdList = m_presentation.PresentationPart.Presentation.SlideIdList;
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
maxSlideId = slideId.Id;
position--;
if (position == 0)
prevSlideId = slideId;
}
maxSlideId++;
SlidePart lastSlidePart;
if (prevSlideId != null)
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(prevSlideId.RelationshipId);
else
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
if (lastSlidePart.SlideLayoutPart != null)
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
var newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = m_presentation.PresentationPart.GetIdOfPart(slidePart);
m_presentation.PresentationPart.Presentation.Save();
}
Am I missing something? Maybe the relationships? After looking up 232243 thousand different examples, I am still stuck at this point. Thank you!
I think you need to add the image into the slide.CommonSlideData
public Slide InsertSlide(PresentationPart presentationPart, string layoutName)
{
UInt32 slideId = 256U;
// Get the Slide Id collection of the presentation document
var slideIdList = presentationPart.Presentation.SlideIdList;
if (slideIdList == null)
{
throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
}
slideId += Convert.ToUInt32(slideIdList.Count());
// Creates an Slide instance and adds its children.
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
slide.Save(slidePart);
// Get SlideMasterPart and SlideLayoutPart from the existing Presentation Part
SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault
(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));
if (slideLayoutPart == null)
{
throw new Exception("The slide layout " + layoutName + " is not found");
}
slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
slidePart.Slide.CommonSlideData = (CommonSlideData)slideMasterPart.SlideLayoutParts.SingleOrDefault(
sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
// Create SlideId instance and Set property
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
return GetSlideByRelationShipId(presentationPart, newSlideId.RelationshipId);
}
/// <summary>
/// Get Slide By RelationShip ID
/// </summary>
/// <param name="presentationPart">Presentation Part</param>
/// <param name="relationshipId">Relationship ID</param>
/// <returns>Slide Object</returns>
private static Slide GetSlideByRelationShipId(PresentationPart presentationPart, StringValue relationshipId)
{
// Get Slide object by Relationship ID
SlidePart slidePart = presentationPart.GetPartById(relationshipId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
Public void InsertImageInLastSlide(Slide slide, string imagePath, string imageExt)
{
// Creates an Picture instance and adds its children.
P.Picture picture = new P.Picture();
string embedId = string.Empty;
embedId = "rId" + (slide.Elements().Count() + 915).ToString();
P.NonVisualPictureProperties nonVisualPictureProperties = new P.NonVisualPictureProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)4U, Name = "Picture 5" },
new P.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true }),
new ApplicationNonVisualDrawingProperties());
P.BlipFill blipFill = new P.BlipFill();
Blip blip = new Blip() { Embed = embedId };
// Creates an BlipExtensionList instance and adds its children
BlipExtensionList blipExtensionList = new BlipExtensionList();
BlipExtension blipExtension = new BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
UseLocalDpi useLocalDpi = new UseLocalDpi() { Val = false };
useLocalDpi.AddNamespaceDeclaration("a14",
"http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension.Append(useLocalDpi);
blipExtensionList.Append(blipExtension);
blip.Append(blipExtensionList);
Stretch stretch = new Stretch();
FillRectangle fillRectangle = new FillRectangle();
stretch.Append(fillRectangle);
blipFill.Append(blip);
blipFill.Append(stretch);
// Creates an ShapeProperties instance and adds its children.
P.ShapeProperties shapeProperties = new P.ShapeProperties();
A.Transform2D transform2D = new A.Transform2D();
A.Offset offset = new A.Offset() { X = 457200L, Y = 1524000L };
A.Extents extents = new A.Extents() { Cx = 8229600L, Cy = 5029200L };
transform2D.Append(offset);
transform2D.Append(extents);
A.PresetGeometry presetGeometry = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList = new A.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(transform2D);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.AppendChild(picture);
// Generates content of imagePart.
ImagePart imagePart = slide.SlidePart.AddNewPart<ImagePart>(imageExt, embedId);
FileStream fileStream = new FileStream(imagePath, FileMode.Open);
imagePart.FeedData(fileStream);
fileStream.Close();
}
Source Code

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

Add table to powerpoint slide using Open XML

I got the code for the Table in the powerpoint using the code generator, but I am not able to add the table to an existing powerpoint document.
I tried adding another table to the intended slide and doing the following:
Table table = slidePart.Slide.Descendants<Table>().First();
table.RemoveAllChildren();
Table createdTable = CreateTable();
foreach (OpenXmlElement childElement in createdTable.ChildElements)
{
table.AppendChild(childElement.CloneNode(true));
}
But that didn't work.
I am out of ideas on this issue.
My original target is to add a table with dynamic number of columns and fixed number of row to my presentation.
I know its been very long since this question is posted, but just in case if some one needs a working code to create table in pptx.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using System.IO;
namespace ANF.Slides.TestEngine
{
class Program
{
static int index = 1;
static void Main(string[] args)
{
Console.WriteLine("Preparing Presentation");
PopulateData();
// GeneratedClass cls=new GeneratedClass();
//cls.CreatePackage(#"E:\output.pptx");
Console.WriteLine("Completed Presentation");
Console.ReadLine();
}
private static void PopulateData()
{
var overflow = false;
const int pageBorder = 3000000;
var db = new AdventureWorksEntities();
var products = db.Products;//.Take(5);
const string outputFile = #"E:\openxml\output.pptx";
File.Copy(#"E:\OpenXml\Template.pptx", outputFile, true);
using (var myPres = PresentationDocument.Open(outputFile, true))
{
var presPart = myPres.PresentationPart;
var slideIdList = presPart.Presentation.SlideIdList;
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
var tableSlidePart = (SlidePart)list.Last();
var current = tableSlidePart;
long totalHeight = 0;
foreach (var product in products)
{
if (overflow)
{
var newTablePart = CloneSlidePart(presPart, tableSlidePart);
current = newTablePart;
overflow = false;
totalHeight = 0;
}
var tbl = current.Slide.Descendants<A.Table>().First();
var tr = new A.TableRow();
tr.Height = 200000;
tr.Append(CreateTextCell(product.Name));
tr.Append(CreateTextCell(product.ProductNumber));
tr.Append(CreateTextCell(product.Size));
tr.Append(CreateTextCell(String.Format("{0:00}", product.ListPrice)));
tr.Append(CreateTextCell(product.SellStartDate.ToShortDateString()));
tbl.Append(tr);
totalHeight += tr.Height;
if (totalHeight > pageBorder)
overflow = true;
}
}
}
static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)
{
//Create a new slide part in the presentation
SlidePart newSlidePart = presentationPart.AddNewPart<SlidePart>("newSlide" + index);
index++;
//Add the slide template content into the new slide
newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));
//make sure the new slide references the proper slide layout
newSlidePart.AddPart(slideTemplate.SlideLayoutPart);
//Get the list of slide ids
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
//Figure out where to add the next slide (find max slide)
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
prevSlideId = slideId;
}
}
maxSlideId++;
//Add new slide at the end of the deck
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
//Make sure id and relid is set appropriately
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
return newSlidePart;
}
private static A.TableCell CreateTextCell(string text)
{
var textCol = new string[2];
if (!string.IsNullOrEmpty(text))
{
if (text.Length > 25)
{
textCol[0] = text.Substring(0, 25);
textCol[1] = text.Substring(26);
}
else
{
textCol[0] = text;
}
}
else
{
textCol[0] = string.Empty;
}
A.TableCell tableCell3 = new A.TableCell();
A.TextBody textBody3 = new A.TextBody();
A.BodyProperties bodyProperties3 = new A.BodyProperties();
A.ListStyle listStyle3 = new A.ListStyle();
textBody3.Append(bodyProperties3);
textBody3.Append(listStyle3);
var nonNull = textCol.Where(t => !string.IsNullOrEmpty(t)).ToList();
foreach (var textVal in nonNull)
{
//if (!string.IsNullOrEmpty(textVal))
//{
A.Paragraph paragraph3 = new A.Paragraph();
A.Run run2 = new A.Run();
A.RunProperties runProperties2 = new A.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
A.Text text2 = new A.Text();
text2.Text = textVal;
run2.Append(runProperties2);
run2.Append(text2);
paragraph3.Append(run2);
textBody3.Append(paragraph3);
//}
}
A.TableCellProperties tableCellProperties3 = new A.TableCellProperties();
tableCell3.Append(textBody3);
tableCell3.Append(tableCellProperties3);
//var tc = new A.TableCell(
// new A.TextBody(
// new A.BodyProperties(),
// new A.Paragraph(
// new A.Run(
// new A.Text(text)))),
// new A.TableCellProperties());
//return tc;
return tableCell3;
}
}
}

Resources