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

                    //Insert a Document at Any Location
/**
 * Inserts content of the external document after the specified node.
 * Section breaks and section formatting of the inserted document are ignored.
 *
 * @param insertAfterNode Node in the destination document after which the content
 * should be inserted. This node should be a block level node (paragraph or table).
 * @param srcDoc The document to insert.
 */
public static void insertDocument(Node insertAfterNode, Document srcDoc) throws Exception
{
    // Make sure that the node is either a paragraph or table.
    if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH) &
      (insertAfterNode.getNodeType() != NodeType.TABLE))
        throw new IllegalArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.getParentNode();

    // This object will be translating styles and lists during the import.
    NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);

    // Loop through all sections in the source document.
    for (Section srcSection : srcDoc.getSections())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        for (Node srcNode : (Iterable<Node>) srcSection.getBody())
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.getNodeType() == (NodeType.PARAGRAPH))
            {
                Paragraph para = (Paragraph)srcNode;
                if (para.isEndOfSection() && !para.hasChildNodes())
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.importNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.insertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

//Insert a Document During Mail Merge

//This example relies on the InsertDocument method shown at the beginning of the article to insert a document into a merge field during mail merge execution. This code demonstrates how to use the InsertDocument method to insert a document into a merge field during mail merge.

public void insertDocumentAtMailMerge() throws Exception
{
    // Open the main document.
    Document mainDoc = new Document(getMyDir() + "InsertDocument1.doc");

    // Add a handler to MergeField event
    mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler());

    // The main document has a merge field in it called "Document_1".
    // The corresponding data for this field contains fully qualified path to the document
    // that should be inserted to this field.
    mainDoc.getMailMerge().execute(
        new String[] { "Document_1" },
        new String[] { getMyDir() + "InsertDocument2.doc" });

    mainDoc.save(getMyDir() + "InsertDocumentAtMailMerge Out.doc");
}

private class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback
{
    /**
     * This handler makes special processing for the "Document_1" field.
     * The field value contains the path to load the document.
     * We load the document and insert it into the current merge field.
     */
    public void fieldMerging(FieldMergingArgs e) throws Exception
    {
        if ("Document_1".equals(e.getDocumentFieldName()))
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());
            builder.moveToMergeField(e.getDocumentFieldName());

            // The name of the document to load and insert is stored in the field value.
            Document subDoc = new Document((String)e.getFieldValue());

            // Insert the document.
            insertDocument(builder.getCurrentParagraph(), subDoc);

            // The paragraph that contained the merge field might be empty now and you probably want to delete it.
            if (!builder.getCurrentParagraph().hasChildNodes())
                builder.getCurrentParagraph().remove();

            // Indicate to the mail merge engine that we have inserted what we wanted.
            e.setText(null);
        }
    }

    public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
    {
        // Do nothing.
    }
}
 
//If a document to be inserted is stored as binary data in the database field (BLOB field), use the following example. A slight variation to the above example to load a document from a BLOB database field instead of a file.

private class InsertDocumentAtMailMergeBlobHandler implements IFieldMergingCallback
{
    /**
     * This handler makes special processing for the "Document_1" field.
     * The field value contains the path to load the document.
     * We load the document and insert it into the current merge field.
     */
    public void fieldMerging(FieldMergingArgs e) throws Exception
    {
        if ("Document_1".equals(e.getDocumentFieldName()))
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());
            builder.moveToMergeField(e.getDocumentFieldName());

            // Load the document from the blob field.
            ByteArrayInputStream inStream = new ByteArrayInputStream((byte[])e.getFieldValue());
            Document subDoc = new Document(inStream);
            inStream.close();

            // Insert the document.
            insertDocument(builder.getCurrentParagraph(), subDoc);

            // The paragraph that contained the merge field might be empty now and you probably want to delete it.
            if (!builder.getCurrentParagraph().hasChildNodes())
                builder.getCurrentParagraph().remove();

            // Indicate to the mail merge engine that we have inserted what we wanted.
            e.setText(null);
        }
    }
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
    {
        // Do nothing.
    }
}

//Insert a Document During Replace

//This example shows how to insert content of one document into another during a customized find and replace operation.

[Code Sample]

public void insertDocumentAtReplace() throws Exception
{
    Document mainDoc = new Document(getMyDir() + "InsertDocument1.doc");
    mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.save(getMyDir() + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler implements IReplacingCallback
{
    public int replacing(ReplacingArgs e) throws Exception
    {
        Document subDoc = new Document(getMyDir() + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.getMatchNode().getParentNode();
        insertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.remove();

        return ReplaceAction.SKIP;
    }
}
                
                    <script type="text/javascript">
    window.onload = showTheTime;
    function showTheTime() {
        var now = new Date();
        document.getElementById("showTime").innerHTML = showTheHours(now.getHours()) + showZeroFilled(now.getMinutes()) + showZeroFilled(now.getSeconds()) + showAmPm();
        setTimeout(showTheTime, 1000);
        function showTheHours(theHour) {
            if (show24Hour() || (theHour > 0 && theHour < 13)) {
                return theHour;
            }
            if (theHour == 0) {
                return 12;
            }
            return theHour - 12;
        }
        function showZeroFilled(inValue) {
            if (inValue > 9) {
                return ":" + inValue;
            }
            return ":0" + inValue;
        }
        function show24Hour() {
            return document.getElementById("show24").checked;
        }
        function showAmPm() {
            if (show24Hour()) {
                return "";
            }
            if ((now.getHours() < 12)) {
                return " AM";
            }
            return " PM";
        }
    }
    
    </script>                
                    //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()