DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    //Saving a Raster Image to TIFF with Deflate/Adobe Deflate Compression

// [C# Code Sample]

string sourceFilePath = myDir + "sample.bmp";
string destinationFilePath = myDir + "output.tiff";

//Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions();
options.BitsPerSample = new ushort[] { 8, 8, 8 };
options.Photometric = TiffPhotometrics.Rgb;
options.Xresolution = new TiffRational(72);
options.Yresolution = new TiffRational(72);
options.ResolutionUnit = TiffResolutionUnits.Inch;
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous;

//Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate;
//Or Deflate
//options.Compression = TiffCompressions.Deflate;

//Load an existing image in an instance of RasterImage
using (RasterImage image = (RasterImage)Image.Load(sourceFilePath))
{
    //Create a new TiffImage from the RasterImage
    using (TiffImage tiffImage = new TiffImage(new TiffFrame(image)))
    {
        //Save the resultant image while passing the instance of TiffOptions
        tiffImage.Save(destinationFilePath, options);
    }
}

//[VB.NET Code Sample]

Dim sourceFilePath As String = myDir & "sample.bmp"
Dim destinationFilePath As String = myDir & "output.tiff"

'Create an instance of TiffOptions and set its various properties
Dim options As New TiffOptions()
options.BitsPerSample = New UShort() { 8, 8, 8 }
options.Photometric = TiffPhotometrics.Rgb
options.Xresolution = New TiffRational(72)
options.Yresolution = New TiffRational(72)
options.ResolutionUnit = TiffResolutionUnits.Inch
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous

'Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate
'Or Deflate
'options.Compression = TiffCompressions.Deflate;

'Load an existing image in an instance of RasterImage
Using image As RasterImage = CType(Image.Load(sourceFilePath), RasterImage)
	'Create a new TiffImage from the RasterImage
	Using tiffImage As New TiffImage(New TiffFrame(image))
		'Save the resultant image while passing the instance of TiffOptions
		tiffImage.Save(destinationFilePath, options)
	End Using
End Using

//Creating TIFF Image with Deflate/Adobe Deflate Compression

//[C# Code Sample]

string destinationFilePath = myDir + "output.tiff";

//Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions();
options.BitsPerSample = new ushort[] { 8, 8, 8 };
options.Photometric = TiffPhotometrics.Rgb;
options.Xresolution = new TiffRational(72);
options.Yresolution = new TiffRational(72);
options.ResolutionUnit = TiffResolutionUnits.Inch;
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous;

//Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate;
//Or Deflate
//options.Compression = TiffCompressions.Deflate;

//Create a new TiffImage with specific size and TiffOptions settings
using (TiffImage tiffImage = new TiffImage(new TiffFrame(options, 100, 100)))
{
    //Loop over the pixels to set the color to red
    for (int i = 0; i < 100; i++)
    {
        tiffImage.ActiveFrame.SetPixel(i, i, Color.Red);
    }
    //Save resultant image
    tiffImage.Save(destinationFilePath);
}

//[VB.NET Code Sample]

Dim destinationFilePath As String = myDir & "output.tiff"

'Create an instance of TiffOptions and set its various properties
Dim options As New TiffOptions()
options.BitsPerSample = New UShort() { 8, 8, 8 }
options.Photometric = TiffPhotometrics.Rgb
options.Xresolution = New TiffRational(72)
options.Yresolution = New TiffRational(72)
options.ResolutionUnit = TiffResolutionUnits.Inch
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous

'Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate
'Or Deflate
'options.Compression = TiffCompressions.Deflate;

'Create a new TiffImage with specific size and TiffOptions settings
Using tiffImage As New TiffImage(New TiffFrame(options, 100, 100))
	'Loop over the pixels to set the color to red
	For i As Integer = 0 To 99
		tiffImage.ActiveFrame.SetPixel(i, i, Color.Red)
	Next i
	'Save resultant image
	tiffImage.Save(destinationFilePath)
End Using

//Loading TIFF with Deflate/Adobe Deflate Compression

//[C# Code Sample]

string filePath = "TIFF-Compression-Deflate.tif";

using (TiffImage tiffImage = (TiffImage)Image.Load(filePath))
{
   // do processing
}

//[VB.NET Code Sample]

Dim filePath As String = "TIFF-Compression-Deflate.tif"

Using tiffImage As TiffImage = CType(Image.Load(filePath), TiffImage)
   ' do processing
End Using
                
                    //A link to a URL

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a hyperlink to a URL at "A1" cell
hyperlinks.add("A1",1,1,"http://www.aspose.com");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");
 
//In the above example, a URL is added to an empty cell, A1, as a hyperlink. When the cell is empty, the URL also becomes the link text. If a URL is added as a link to a cell that already contains text, then the hyperlink is added but the value of the cell looks like plain text. To make it look like a hyperlink, apply formatting on the cell.

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a hyperlink to a URL at "A1" cell
hyperlinks.add("A1",1,1,"http://www.aspose.com");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");
 
//Adding a Link to another Cell in the Same File

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding an internal hyperlink to the "B9" cell of the other worksheet "Sheet2" in
//the same Excel file

hyperlinks.add("B3",1 ,1, "Sheet2!B9");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");

//Adding a Link to an External File 

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a link to the external file
hyperlinks.add("A5", 1, 1, "C:\\book1.xls");

//Saving the Excel file
workbook.save(sdPath + "/book2.xls");
 
                
                    @OneToMany(mappedBy="SOMECOLUMN_NAME", fetch = FetchType.LAZY)
@Fetch(FetchMode.SELECT)
@LazyCollection(LazyCollectionOption.TRUE) //OR     @LazyCollection(LazyCollectionOption.EXTRA)
public List<OrderLineItems> getOrderLineItems(){
return orderLineItems;
}                
                    -showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm 
C:\java-home\jdk1.7.0_21\jre\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms40m
-Xmx1024m                
                    //Adding Attachments to a New Email Message

public static void main(String[] args)
{
    // Base folder for reading and writing files
    String strBaseFolder = "D:\\Data\\Aspose\\resources\\";

    //Initialize and Load an existing MSG file by specifying the MessageFormat
    MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());

    //Initialize a String variable to get the Email Subject
    String subject = email.getSubject();
    //Append some more information to Subject
    subject = subject + " This text is added to the existing subject";
    //Set the Email Subject
    email.setSubject(subject);

    //Initialize a String variable to get the Email's HTML Body
    String body = email.getHtmlBody();
    //Apppend some more information to the Body variable
    body = body + "<br> This text is added to the existing body";
    //Set the Email Body
    email.setHtmlBody(body);

    //Initialize MailAddressCollection object
    MailAddressCollection contacts = new MailAddressCollection();

    //Retrieve Email's TO list
    contacts = email.getTo();
    //Check if TO list has some values
    if (contacts.size() > 0)
    {
        //Remove the first email address
        contacts.remove(0);
        //Add another email address to collection
        contacts.add("to1@domain.com");
    }
    //Set the collection as Email's TO list
    email.setTo(contacts);

    //Initialize MailAddressCollection
    contacts = new MailAddressCollection();

    //Retrieve Email's CC list
    contacts = email.getCC();
    //Add another email address to collection
    contacts.add("cc2@domain.com");
    //Set the collection as Email's CC list
    email.setCC(contacts);

    //Save the Email message to disk by specifying the MessageFormat
    email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}

//Loading a Message with Load Options

//To load a message with specific load options, Aspose.Email provides the MessageLoadOptions class that can be used as follow:

MesageLoadOptions options = new MesageLoadOptions();
options.PrefferedTextEncoding = Encoding.getEncoding(1252);
options.setMessageFormat(MessageFormat.getMsg());
MailMessage eml = MailMessage.Load("EMAIL_497563\\test3.msg", options);

                
                    import java.io.IOException;
import java.util.Scanner;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class filter
 * @author prgrmmr.aben [at] gmail (dot) com
 * http://fivesnippets.blogspot.com/2014/08/servlet-filter-for-ddos-spam-etc.html
 * please give back a small donation if you find
 * this little educational snippet of code useful 
 */
@WebFilter("/filter")
public class filter implements Filter {

    /**
     * Default constructor. 
     */
    public filter() {
        // TODO Auto-generated constructor stub
    }

 /**
  * @see Filter#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }

 /**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpSession session;
  System.out.println("being filtered"); //you can use logging instead
  HttpServletRequest req = (HttpServletRequest)request;
  HttpServletResponse res = (HttpServletResponse)response;
                res.addHeader("X-FRAME-OPTIONS", "DENY" ); 
  String requestedPath = req.getRequestURI().substring(req.getContextPath().length());
                // I was using the test bellow when developing the app
  /*Scanner verify = new Scanner(System.in);
  if(verify.nextInt()==0){
   req.getSession().invalidate();
  }*/
  session = req.getSession(false);
  if(req.getSession(false) == null){
   session = req.getSession(true);
   sessionInit(session);
   req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
  }else{
   long timeElapsed =  System.currentTimeMillis() - (long) session.getAttribute("lastTime"); 
   System.out.println(timeElapsed);
   System.out.println("seen");
   if(session.getAttribute("spam").equals(true))
    System.out.println("spams are not allowed"); //you can use logging instead
   else if (timeElapsed<2000) {
    session.setAttribute("spam", true);
    System.out.println("spam need to be blocked");
   }else if (session.getAttribute("logged").equals(false)) {
    session.setAttribute("lastTime", System.currentTimeMillis());
    req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
   System.out.println(2);
   }else{//if session.getAttribute("logged").equals(true) which should be set to true after user is logged
    System.out.println(requestedPath);
    session.setAttribute("lastTime", System.currentTimeMillis());
    if(requestedPath.equals("/login.jsp"))
     req.getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
    else
     req.getServletContext().getRequestDispatcher(requestedPath).forward(request, response);
   }
  }
  

  //chain.doFilter(request, response);
 }

 private void sessionInit(HttpSession session) {
  // TODO Auto-generated method stub
  System.out.println("init");
  session.setAttribute("spam", false);
  session.setAttribute("logged", true);
  session.setAttribute("lastTime", System.currentTimeMillis());
  
 }

 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  // TODO Auto-generated method stub

 }

}                
                    CREATE TABLE IF NOT EXISTS `session` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  /*`refUser` int(11) DEFAULT NULL COMMENT 'references user number',*/
  `IP` int(39) DEFAULT NULL,
  `creation` datetime NOT NULL TIMESTAMP DEFAULT CURRENT_TIMESTAMP  COMMENT 'creation time',
  `expiry` datetime DEFAULT NULL  COMMENT 'expiry time',
  `secretToken` varchar(10) NOT NULL,
  `type` enum('guest','client') NOT NULL DEFAULT 'guest',
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='don''t need to be a real session in memory' AUTO_INCREMENT=1 ;
CREATE TABLE cachedSession ENGINE=MEMORY SELECT * FROM session;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cacheSessions`()
    NO SQL
BEGIN
DELETE FROM cachedsession WHERE 1;
INSERT INTO cachedsession SELECT * FROM session WHERE `expiry`<NOW();
SELECT row_count();
end$$
 
CREATE DEFINER=`root`@`localhost` PROCEDURE `cleanSession`()
    NO SQL
    COMMENT 'clean sessions expired @hours ago'
BEGIN
DELETE FROM `session` WHERE  TIMESTAMPDIFF(MINUTE, expiry, NOW())>0;
SELECT row_count();
end$$                
                    //Shows how to setup a connection to a database and execute commands.

//[C# Code Sample]

// Create a connection to the database.
mConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName);

// Open the database connection.
mConnection.Open();

//[VB Code Sample]

' Create a connection to the database.
mConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbName)

' Open the database connection.
mConnection.Open()

//Stores a document to the specified database

//[C# Code Sample]
 

public static void StoreToDatabase(Document doc)
{
    // Save the document to a MemoryStream object.
    MemoryStream stream = new MemoryStream();
    doc.Save(stream, SaveFormat.Doc);

    // Get the filename from the document.
    string fileName = Path.GetFileName(doc.OriginalFileName);

    // Create the SQL command.
    string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Doc)";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Add the @Doc parameter.
    command.Parameters.AddWithValue("Doc", stream.ToArray());

    // Write the document to the database.
    command.ExecuteNonQuery();

}
 
//[VB.NET Code Sample]
 

Public Shared Sub StoreToDatabase(ByVal doc As Document)
    ' Save the document to a MemoryStream object.
    Dim stream As New MemoryStream()
    doc.Save(stream, SaveFormat.Doc)

    ' Get the filename from the document.
    Dim fileName As String = Path.GetFileName(doc.OriginalFileName)

    ' Create the SQL command.
    Dim commandString As String = "INSERT INTO Documents (FileName, FileContent) VALUES('" & fileName & "', @Doc)"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Add the @Doc parameter.
    command.Parameters.AddWithValue("Doc", stream.ToArray())

    ' Write the document to the database.
    command.ExecuteNonQuery()

End Sub

//Retrieves and returns the document from the specified database using the filename as a key to fetch the document.

//[C# Code Sample]
 

public static Document ReadFromDatabase(string fileName, string path)
{
    // Create the SQL command.
    string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Create the data adapter.
    OleDbDataAdapter adapter = new OleDbDataAdapter(command);

    // Fill the results from the database into a DataTable.
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);

    // Check there was a matching record found from the database and throw an exception if no record was found.
    if (dataTable.Rows.Count == 0)
        throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName));

    // The document is stored in byte form in the FileContent column.
    // Retrieve these bytes of the first matching record to a new buffer.
    byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"];

    // Wrap the bytes from the buffer into a new MemoryStream object.
    MemoryStream newStream = new MemoryStream(buffer);

    // Read the document from the stream.
    Document doc = new Document(newStream);

    // Return the retrieved document.
    return doc;

}
 
//[VB.NET Code Sample]
 

Public Shared Function ReadFromDatabase(ByVal fileName As String, ByVal path As String) As Document
    ' Create the SQL command.
    Dim commandString As String = "SELECT * FROM Documents WHERE FileName='" & fileName & "'"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Create the data adapter.
    Dim adapter As New OleDbDataAdapter(command)

    ' Fill the results from the database into a DataTable.
    Dim dataTable As New DataTable()
    adapter.Fill(dataTable)

    ' Check there was a matching record found from the database and throw an exception if no record was found.
    If dataTable.Rows.Count = 0 Then
        Throw New ArgumentException(String.Format("Could not find any record matching the document ""{0}"" in the database.", fileName))

    End If

    ' The document is stored in byte form in the FileContent column.
    ' Retrieve these bytes of the first matching record to a new buffer.
    Dim buffer() As Byte = CType(dataTable.Rows(0)("FileContent"), Byte())

    ' Wrap the bytes from the buffer into a new MemoryStream object.
    Dim newStream As New MemoryStream(buffer)

    ' Read the document from the stream.
    Dim doc As New Document(newStream)

    ' Return the retrieved document.
    Return doc

End Function

//Delete the document from the database, using filename to fetch the record.

//[C# Code Sample]
 

public static void DeleteFromDatabase(string fileName)
{
    // Create the SQL command.
    string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Delete the record.
    command.ExecuteNonQuery();

}
 
//[VB.NET Code Sample]
 

Public Shared Sub DeleteFromDatabase(ByVal fileName As String)
    ' Create the SQL command.
    Dim commandString As String = "DELETE * FROM Documents WHERE FileName='" & fileName & "'"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Delete the record.
    command.ExecuteNonQuery()
//Stores the document to a database, then reads the same document back again, and finally deletes the record containing the document from the database.

//[C# Code Sample]
 

// Store the document to the database.
StoreToDatabase(doc);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(fileName, dataDir);

// Save the retrieved document to disk.
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName);
dbDoc.Save(dataDir + newFileName);

// Delete the document from the database.
DeleteFromDatabase(fileName);

// Close the connection to the database.
mConnection.Close();
 
//[VB.NET Code Sample]
 
' Store the document to the database.
StoreToDatabase(doc)
' Read the document from the database and store the file to disk.
Dim dbDoc As Document = ReadFromDatabase(fileName, dataDir)

' Save the retrieved document to disk.
Dim newFileName As String = Path.GetFileNameWithoutExtension(fileName) & " from DB" & Path.GetExtension(fileName)
dbDoc.Save(dataDir & newFileName)

' Delete the document from the database.
DeleteFromDatabase(fileName)

' Close the connection to the database.
mConnection.Close()
                
                    //Load EML and Save to MSG and MHTML

public static void ConvertFromEML()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    //Initialize and Load an existing EML file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());

    //Save the Email message to disk by specifying the MSG and MHT MailMessageSaveType
    msg.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
    msg.save(strBaseFolder + "message.mhtml", MailMessageSaveType.getMHtmlFormat());
}

//Load MSG and Save to EML and MHTML

public static void ConvertFromMSG()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    //Initialize and Load an existing MSG file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.msg", MessageFormat.getMsg());

    //Save the Email message to disk by specifying the EML and MHT MailMessageSaveType
    msg.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    msg.save(strBaseFolder + "message.mhtml", MailMessageSaveType.getMHtmlFormat());
}

//Load MHTML and Save as EML and MSG

public static void ConvertFromMHTML()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

        //Initialize and Load an existing MHT file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.mhtml", MessageFormat.getMht());

    //Save the Email message to disk by specifying the EML and MSG MailMessageSaveType
    msg.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    msg.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}
                
                    //Code sample shows how to create content control of type rich text box.

//[C# code sample]

Document doc = new Document();
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block);

Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.Text = "Hello World";
run.Font.Color = Color.Green;
para.Runs.Add(run);
sdtRichText.ChildNodes.Add(para);
doc.FirstSection.Body.AppendChild(sdtRichText);

doc.Save(MyDir + "Out.docx");

//[VB Code Sample]

Dim doc As New Document()
Dim sdtRichText As New StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block)

Dim para As New Paragraph(doc)
Dim run As New Run(doc)
run.Text = "Hello World"
run.Font.Color = Color.Green
para.Runs.Add(run)
sdtRichText.ChildNodes.Add(para)
doc.FirstSection.Body.AppendChild(sdtRichText)

doc.Save(MyDir & "Out.docx")
 
//Code samples for how to create content control of type combo box.

//[C# code sample]

Document doc = new Document();
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block);

sdt.ListItems.Add(new SdtListItem("Choose an item", "-1"));
sdt.ListItems.Add(new SdtListItem("Item 1", "1"));
sdt.ListItems.Add(new SdtListItem("Item 2", "2"));
doc.FirstSection.Body.AppendChild(sdt);

doc.Save(MyDir + "Out.docx");
 
//[VB Code Sample]

Dim doc As New Document()
Dim sdt As New StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block)

sdt.ListItems.Add(New SdtListItem("Choose an item", "-1"))
sdt.ListItems.Add(New SdtListItem("Item 1", "1"))
sdt.ListItems.Add(New SdtListItem("Item 2", "2"))
doc.FirstSection.Body.AppendChild(sdt)

doc.Save(MyDir & "Out.docx")
 
//Code for how to modify content controls of type plain text box, drop down list and picture.

//[C# code sample]

Document doc = new Document(MyDir + "in.docx");

foreach (StructuredDocumentTag sdt in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    if (sdt.SdtType == SdtType.PlainText)
    {
        sdt.RemoveAllChildren();
        Paragraph para = sdt.AppendChild(new Paragraph(doc)) as Paragraph;
        Run run = new Run(doc, "new text goes here");
        para.AppendChild(run);
    }
    else if (sdt.SdtType == SdtType.DropDownList)
    {
        SdtListItem secondItem = sdt.ListItems[2];
        sdt.ListItems.SelectedValue = secondItem;
    }
    else if (sdt.SdtType == SdtType.Picture)
    {
        DrawingML dml = (DrawingML)sdt.GetChild(NodeType.DrawingML, 0, true);
        if (dml.HasImage)
        {
            dml.ImageData.SetImage(MyDir + "image.png");
        }
    }
}

doc.Save(MyDir + "Out.docx");
 
//[VB Code Sample]

Dim doc As New Document(MyDir & "in.docx")

For Each sdt As StructuredDocumentTag In doc.GetChildNodes(NodeType.StructuredDocumentTag, True)
    If sdt.SdtType = SdtType.PlainText Then
        sdt.RemoveAllChildren()
        Dim para As Paragraph = TryCast(sdt.AppendChild(New Paragraph(doc)), Paragraph)
        Dim run As New Run(doc, "new text goes here")
        para.AppendChild(run)
    ElseIf sdt.SdtType = SdtType.DropDownList Then
        Dim secondItem As SdtListItem = sdt.ListItems(2)
        sdt.ListItems.SelectedValue = secondItem
    ElseIf sdt.SdtType = SdtType.Picture Then
        Dim dml As DrawingML = DirectCast(sdt.GetChild(NodeType.DrawingML, 0, True), DrawingML)
        If dml.HasImage Then
            dml.ImageData.SetImage(MyDir & "image.png")
        End If
    End If
Next

doc.Save(MyDir & "Out.docx")