Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Hiding and Storing/caching of Application Specific data in MS Word 2003 documents

, 9 Oct 2008 CPOL
Proof of concept on how the application specific (small/large amount of) data can be stored in ms word document as well as how it can be made hidden from end user’s eye.
Proof_Of_Concept.zip
Common
Common
bin
Debug
Release
Common.dll
Common.pdb
obj
Debug
TempPE
Release
Common.dll
Common.pdb
TempPE
Properties
Common.suo
DocumentIDReader
DocumentIDReader
bin
Debug
Release
DocumentIDReader.exe
DocumentIDReader.pdb
DocumentIDReader.vshost.exe
DocumentIDReader.csproj.user
obj
Debug
TempPE
Release
DocumentIDReader.csproj.GenerateResource.Cache
DocumentIDReader.exe
DocumentIDReader.Form1.resources
DocumentIDReader.pdb
DocumentIDReader.Properties.Resources.resources
TempPE
Properties
Settings.settings
DocumentIDReader.suo
FileStorage
FileStorage
FileStorage.def
FileStorage.vcproj.NECHCLDC01.atul.suyal.user
FileStorage.vcproj.NECHCLDC01.vinita.batra.user
FileStorage.vcproj.RAIREKI.mahendra.gupta.user
res
vssver2.scc
vssver2.scc
FileStorage.suo
SocketServer
SocketServer
bin
Release
Common.dll
Common.pdb
SocketServer.exe
SocketServer.pdb
SocketServer.vshost.exe
obj
Debug
SocketServer.exe
SocketServer.pdb
TempPE
Release
SocketServer.exe
SocketServer.pdb
TempPE
Properties
SocketServer.csproj.user
SocketServer.suo
WordAddIn1
WordAddIn1
bin
Debug
Common.dll
Common.pdb
WordAddIn1.dll
WordAddIn1.dll.manifest
WordAddIn1.pdb
obj
Debug
TempPE
WordAddIn1.csproj.GenerateResource.Cache
WordAddIn1.csproj.ResolveComReference.cache
WordAddIn1.dll
WordAddIn1.pdb
WordAddIn1.Properties.Resources.resources
Properties
Settings.settings
WordAddIn1.csproj.user
WordAddIn1.suo
WordAddIn1Setup
Debug
Release
WordAddIn1Setup
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Common;
using System.IO;
using System.Runtime.InteropServices;
//This program creates a server that receives connection requests 
//from clients. The server is built with an asynchronous socket, 
//so execution of the server application is not suspended 
//while it waits for a connection from a client.

//The client which sends the request to this server is VSTO addin.
//If VSTO addin finds that the DocumentID is removed, 
//it re-adds the same ID in the office file by sending the request to this server.


namespace SocketServer
{
   public class ServerApplication
    {
        public const int STRINGDATA_DOCUMENTID = 100;
        private static ManualResetEvent connectDone = new ManualResetEvent(false);
        private const int queueSize = 10;
        private const int defaultPort = 11000;
        private static int port;
        private static IPAddress ipAddress;
        private const string endOfData = "<EOF>";
        private static LingerOption lingerOption = new LingerOption(true, 1);
             
        public static Boolean Initialize()
        {
            Boolean retVal = true;
            try
            {
                string ip = "127.0.0.1";
                ipAddress = IPAddress.Parse(ip);
                port = 11000;
            }
            catch (Exception e)
            {
            }
            return retVal;
        }

        public static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            
            //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            try
            {
                Boolean res = Initialize();
                if (res)
                {
                    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
                    // Create a TCP/IP socket.
                    Socket listener = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

                    // Bind the socket to the local endpoint and listen for incoming connections.
                    listener.Bind(localEndPoint);
                    listener.Listen(queueSize);
                    listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                    while (true)
                    {
                        // Set the event to nonsignaled state.
                        connectDone.Reset();
                        // Start an asynchronous socket to listen for connections.
                        Console.WriteLine("Waiting for a connection...");
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
                        // Wait until a connection is made before continuing.
                        connectDone.WaitOne();
                    }
                }
            }
            catch (Exception e)
            {
            }
            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            try
            {
                connectDone.Set();
                Console.WriteLine("AcceptCallback...");
                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                handler.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                Receive(handler);
            }
            catch (Exception e)
            {
            }
        }

        public static void Receive(Socket handler)
        {
            try
            {
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
                       new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
            }
        }

        public static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket. 
                Console.WriteLine("before EndReceive");
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.Unicode.GetString(state.buffer, 0, bytesRead));
                    // Check for end-of-file tag. If it is not there, read 
                    // more data.
                    content = state.sb.ToString();
                    int index;
                    index = content.LastIndexOf("<EOF>");
                    if (index != -1)
                    {
                        Byte[] requestData = Encoding.Unicode.GetBytes(content);
                        doWork(ref requestData, handler);
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }

       private static void AddDocumentID(Common.Message message)
       {

           //bool fileOpened = false;

           //FileStream fstream = null;
           //fileOpened = GetFileHandle(message.fileName, ref fstream);
          
           //Adds the DocumentID in the file specified by message.fileName by calling 
           //fileOperation.AddData()

           //FileOperation class is present in assembly Common 
           //Common library is created by project named Common
           //See the references in solution explorer
           //It shows Common is added as c# library in this project.

           //if (!fileOpened)
           //{
           //    return;

           //}
           //else
           //{
               FileOperation fileOperation = new FileOperation();
           //    if (fstream != null)
           //        fstream.Close();
           //    Microsoft.Win32.SafeHandles.SafeFileHandle handle = fstream.SafeFileHandle;
           //    handle.
               
               bool success = fileOperation.AddData(message.fileName, STRINGDATA_DOCUMENTID, message.documentID);
               Console.WriteLine("success {0}", success);
               DocumentInfoHandler documentInfoHandler = new DocumentInfoHandler();
               documentInfoHandler.DeleteDocumentInfo(message.uniqueID);
           //}
       }

        private static void doWork(ref byte[] data, Socket handler)
        {
            //This function deserializes the message received from client application
            //and calls AddDocumentID() to add document ID

            byte[] responseData = null;
            try
            {
                Common.Message message = null;
                Serialization serialization = new Serialization();
                Boolean res = false;
                res=serialization.Deserialize(ref data, ref message);

                if ((res == true) && (message != null))
                {
                    Console.WriteLine("deserailization successfull");
                    AddDocumentID(message);
                }
                else
                {
                    Console.WriteLine("deserailization failed");
                }

            }
            catch (Exception e)
            {
            }
            finally
            {
            }
        }

       private static bool GetFileHandle(string fileFullPath, ref FileStream fStream)
        {
            // This funtion tries to capture the file handle as soon as 
            //it is freed by other process.
          

            bool success = false;
            int totalTry = 1;
            while(true)
            {
                try
                {
                   fStream = File.Open(fileFullPath, FileMode.Open,FileAccess.Read,FileShare.None);
                    //fStream.
                   // fStream.Close();
                    success = true;
                    break;
                }
                catch (Exception exp)
                {
                    Thread.Sleep(100);
                 }
            }
            Console.WriteLine("File Handle cpatured");
            return success;
        }

        private static void Send(Socket handler, ref byte[] responseData)
        {
            try
            {
                if (responseData.Length > 0)
                {
                    Console.WriteLine("send function called");

                    String temp = Encoding.Unicode.GetString(responseData);
                    temp = String.Concat(temp, endOfData);
                    responseData = Encoding.Unicode.GetBytes(temp);

                    //Begin sending the data to the remote device.
                    handler.BeginSend(responseData, 0, responseData.Length, 0,
                         new AsyncCallback(SendCallback), handler);
                }
            }
            catch (Exception e)
            {
              
            }
        }
        public static void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
               
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
            }
        }
        public static void Main()
        {
            StartListening();
        }
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 10 Oct 2008
Article Copyright 2008 by batra.vinita@gmail.com
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid