Пример #1
0
        /// <summary>
        /// Populate a LocalEvents object and add it to the event job queue for
        /// further processing.
        /// </summary>
        /// <param name="e">is the actual event supplied by fileWatcher.</param>
        /// <param name="isRename">is set to True if this event is a RenamedEventArgs.</param>
        /// <param name="eventType">is a LocalEvents.EventsType value so that others know what action generated the event.</param>
        public void FillEventsQueue(EventArgs e,bool isRename, LocalEvents.EventsType eventType)
        {
            LocalEvents lEvent = new LocalEvents();
            DateTime eventTime = DateTime.Now;

            if(isRename)
            {
                RenamedEventArgs rArgs=(RenamedEventArgs)e;
                lEvent.FileName = rArgs.Name;
                lEvent.FullPath = rArgs.FullPath;
                lEvent.OldFileName = rArgs.OldName;
                lEvent.OldFullPath = rArgs.OldFullPath;
                lEvent.EventType = eventType;
                lEvent.EventTimeStamp = eventTime;
            }
            else
            {
                FileSystemEventArgs rArgs = (FileSystemEventArgs)e;
                lEvent.FileName = rArgs.Name;
                lEvent.FullPath = rArgs.FullPath;
                lEvent.OldFileName = "";
                lEvent.OldFullPath = "";
                lEvent.EventType = eventType;
                lEvent.EventTimeStamp = eventTime;
            }

            EventQueue.Add(lEvent);
        }
 private void UpdateDBForStatus(LocalEvents lEvent, string strStatus)
 {
     dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.STATUS , strStatus , DbHandler.KEY , lEvent.FileName );
 }
        private void AddInDBForRename(LocalEvents lEvent)
        {
            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.KEY , lEvent.FileName , DbHandler.KEY , lEvent.OldFileName);

            // Now that the key has been updated, let's update the name as well.
            string fileName = lEvent.FileName.Substring(lEvent.FileName.LastIndexOf("\\") + 1);
            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.FILE_NAME, fileName, DbHandler.KEY, lEvent.FileName);
            UpdateDBForStatus(lEvent, DB_STATUS_IN_PROGRESS);
        }
        public LocalEvents GetLocalEvent()
        {
            string query = "SELECT * FROM " + EVENT_TABLE_NAME + " WHERE " + EVENT_ORIGIN + " = 'L' ORDER BY " + EVENT_INDEX + " LIMIT 1;";
            LogWrapper.LogMessage("DBHandler - GetLocalEvent", "Running query: " + query);
            LocalEvents item = null;

            SQLiteConnection sqlConnection = OpenConnection();
            SQLiteCommand sqlCommand = new SQLiteCommand(query, sqlConnection);
            SQLiteDataReader sqlDataReader = null;
            try
            {
                sqlDataReader = sqlCommand.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    item = new LocalEvents();
                    PopulateLocalEventFromReader(ref item, ref sqlDataReader);
                }
            }
            catch (Exception ex)
            {
                LogWrapper.LogMessage("DbHandler - GetLocalEvent", "Caught exception: " + ex.Message);
                item = null;
            }

            if (null != sqlDataReader)
                sqlDataReader.Close();
            sqlConnection.Close();

            return item;
        }
        /// <summary>
        /// Takes the given event and adds it to the candidate event list after some preprocessing.
        /// The preprocessing includes things like combining DELETE/ADD events into a single MOVE event
        /// when the time difference between the events is short enough to justify the guess.  It also
        /// ignores events for objects that are hidden or temporary since those objects are not synced
        /// with the server.
        /// </summary>
        /// <param name="newEvent">is the event information supplied by Watcher to be added to the event queue.</param>
        public static void Add(LocalEvents newEvent)
        {
            // Ignore events for anything that has .partial.m_strMacAdd or .original.m_strMacAdd in the name.
            if (newEvent.FileName.Contains(m_strOriginal) || newEvent.FileName.Contains(m_strPartial) ||
                newEvent.OldFileName.Contains(m_strOriginal) || newEvent.OldFileName.Contains(m_strPartial))
            {
                LogWrapper.LogMessage("EventQueue - Add", "Ignoring event: (" + newEvent.EventType + ") " + newEvent.FullPath);
                return;
            }

            int indexToRemove = -1;

            LogWrapper.LogMessage("EventQueue - Add", "Adding event: (" + newEvent.EventType + ") " + newEvent.FullPath);
            if (newEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
            {
                LogWrapper.LogMessage("EventQueue - Add", "              (" + newEvent.EventType + ") old path:" + newEvent.OldFullPath);
                LogWrapper.LogMessage("EventQueue - Add", "              (" + newEvent.EventType + ") new path:" + newEvent.FullPath);
            }

            // Only fill in this information if the event isn't a DELETE event.
            // Otherwise, the file/folder isn't there to get the info for.
            if (newEvent.EventType != LocalEvents.EventsType.FILE_ACTION_REMOVED)
            {
                FillInFileInfo(ref newEvent);

                // Ignore events for objects that are HIDDEN or TEMPORARY.
                if ((newEvent.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (newEvent.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
                    return;

                // Do some extra stuff for directories.
                if (newEvent.IsDirectory)
                {
                    bool foundEntry = false;
                    if (1 == newEvent.EventTimeStamp.Year)
                        newEvent.EventTimeStamp = DateTime.Now;

                    // If this is a MODIFIED event for a folder, then update the event time in the list.
                    lock (folderLock)
                    {
                        foreach (LocalEvents lId in eventListFolders)
                        {
                            if (lId.FullPath == newEvent.FullPath)
                            {
                                lId.EventTimeStamp = newEvent.EventTimeStamp;
                                foundEntry = true;
                                break;
                            }
                        }
                        if (false == foundEntry)
                            eventListFolders.Add(newEvent);
                    }
                }
            }

            lock (thisLock)
            {
                bool bAdd = true;

                // Only FILE_ACTION_MODIFIED events are possibly ignored, so they are the only ones that
                // we should spend the effort/time to loop through the list for.
                if (newEvent.EventType == LocalEvents.EventsType.FILE_ACTION_MODIFIED)
                {
                    foreach (LocalEvents id in eventListCandidates)
                    {
                        if (id.FileName == newEvent.FileName)
                        {
                            if (newEvent.IsFile)
                            {
                                // If a event type is added, removed, renamed, or moved, then go ahead and accept the event.
                                // If the new event is MODIFIED and the existing is ADDED, then update the timestamp of the
                                // existing event, but don't add it to the list.
                                if ((id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED) ||
                                    (id.EventType == LocalEvents.EventsType.FILE_ACTION_MODIFIED) ||
                                    (id.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
                                    )
                                {
                                    LogWrapper.LogMessage("EventQueue - Add", "Local event already exists for: " + newEvent.FullPath);
                                    id.EventTimeStamp = newEvent.EventTimeStamp;
                                    bAdd = false;
                                    break;
                                }
                            }
                            else
                            {
                                // For directories, ignore any FILE_ACTION_MODIFIED events.  They should not reset the time either.
                                LogWrapper.LogMessage("EventQueue - Add", "Local event already exists for: " + newEvent.FullPath);
                                bAdd = false;
                                break;
                            }
                        }
                    }
                }
                else if (newEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
                {
                    if (newEvent.IsFile)
                    {
                        // If something locally has been renamed, then look through the existing events
                        // and see if there is a 'created' event for the old path.  If so, then the
                        // existing event MUST be changed so the path reflects the new path.  Otherwise
                        // no file will be uploaded (the local file has been renamed) and the rename
                        // won't occur on the server since the file wasn't uploaded.
                        bool foundAddEvent = false;
                        foreach (LocalEvents id in eventListCandidates)
                        {
                            if ((id.FileName == newEvent.OldFileName) && (id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED))
                            {
                                // Set the path to the new path so the correct folder is created or file is uploaded.
                                // Set the event to FILE_ACTION_MODIFIED so that a new version of the file is uploaded.
                                LogWrapper.LogMessage("EventQueue - Add", "Local ADDED event already exists for: " + newEvent.FullPath);
                                LogWrapper.LogMessage("EventQueue - Add", "Changing existing path from " + id.FullPath + " to " + newEvent.FullPath);
                                LogWrapper.LogMessage("EventQueue - Add", "Changing existing event from " + id.EventType + " to FILE_ACTION_MODIFIED");
                                id.FullPath = newEvent.FullPath;
                                id.FileName = newEvent.FileName;
                                id.EventType = LocalEvents.EventsType.FILE_ACTION_MODIFIED;
                                bAdd = false;
                                foundAddEvent = true;
                            }
                            if (foundAddEvent)
                            {
                                // If a FILE_ACTION_ADDED event was modified, then we keep looking for a FILE_ACTION_REMOVED
                                // action as well and remove/change it to something else.
                                if ((id.FileName == newEvent.FileName) && (id.EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED))
                                {
                                    // The delete action for the file should be deleted since it would delete the file
                                    // that will now be uploaded.
                                    indexToRemove = eventListCandidates.IndexOf(id);
                                    LogWrapper.LogMessage("EventQueue - Add", "Removing delete action for: " + newEvent.FullPath);
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (newEvent.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
                {
                    // The 'Save As' from editors like Notepad execute a strange series of events.  Specifically,
                    // FILE_ACTION_ADDED, FILE_ACTION_REMOVED, FILE_ACTION_ADDED, and FILE_ACTION_MODIFIED.
                    // If the ADDED action finds both the ADDED and REMOVED actions earlier in the list, then
                    // modify the first ADDED event, remove the REMOVED, and throw this event away.
                    bool foundAdded = false;
                    bool foundRemoved = false;
                    int indexAdded = -1;
                    int indexRemoved = -1;
                    foreach (LocalEvents id in eventListCandidates)
                    {
                        if ((id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED) && (id.FullPath == newEvent.FullPath))
                        {
                            LogWrapper.LogMessage("EventQueue - Add", "Found existing FILE_ACTION_ADDED (save seq) for: " + newEvent.FullPath);
                            foundAdded = true;
                            indexAdded = eventListCandidates.IndexOf(id);
                        }
                        if (foundAdded)
                        {
                            if ((id.EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED) && (id.FullPath == newEvent.FullPath))
                            {
                                LogWrapper.LogMessage("EventQueue - Add", "Found existing FILE_ACTION_REMOVED (save seq) for: " + newEvent.FullPath);
                                foundRemoved = true;
                                indexRemoved = eventListCandidates.IndexOf(id);
                            }
                        }

                        // We found what we were looking for so we can exit the loop.
                        if (foundAdded && foundRemoved)
                            break;
                    }

                    if (foundAdded && foundRemoved)
                    {
                        // If I found the two events (in the correct order), then I need to modify
                        // the Added entry, remove the Removed entry, and throw this entry away.
                        bAdd = false;
                        indexToRemove = indexRemoved;
                        eventListCandidates[indexAdded].EventTimeStamp = newEvent.EventTimeStamp;
                        eventListCandidates[indexAdded].IsDirectory = newEvent.IsDirectory;
                        eventListCandidates[indexAdded].IsFile = newEvent.IsFile;
                        eventListCandidates[indexAdded].Attributes = newEvent.Attributes;
                        LogWrapper.LogMessage("EventQueue - Add", "Updating existing FILE_ACTION_ADD for: " + newEvent.FullPath);
                        LogWrapper.LogMessage("EventQueue - Add", "Removing existing FILE_ACTION_REMOVED for: " + newEvent.FullPath);
                        LogWrapper.LogMessage("EventQueue - Add", "Ignoring new FILE_ACTION_ADDED for: " + newEvent.FullPath);
                    }
                    else // Look for a move event.
                    {
                        string fileName = newEvent.FileName.Substring(newEvent.FileName.LastIndexOf("\\") + 1);

                        foundRemoved = false;
                        indexRemoved = -1;
                        LogWrapper.LogMessage("EventQueue - Add", "Looking for a MOVE sequence.");
                        for (int loopIndex = eventListCandidates.Count - 1; loopIndex >= 0; loopIndex--)
                        {
                            string eventFileName = eventListCandidates[loopIndex].FileName.Substring(eventListCandidates[loopIndex].FileName.LastIndexOf("\\") + 1);
                            LogWrapper.LogMessage("EventQueue - Add", "Comparing (" + eventListCandidates[loopIndex].EventType.ToString() + ") " + eventFileName + " to " + fileName);
                            if ((eventListCandidates[loopIndex].EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED) && (0 == eventFileName.CompareTo(fileName)))
                            {
                                LogWrapper.LogMessage("EventQueue - Add", "Found existing FILE_ACTION_REMOVED (move seq) for: " + newEvent.FullPath);
                                indexRemoved = loopIndex;
                                foundRemoved = true;

                                // We found what we were looking for so we can exit the loop.
                                break;
                            }
                        }

                        if (foundRemoved)
                        {
                            // If an item has an ADDED and REMOVED action within a VERY short time
                            // period then the item was probably MOVED/RENAMED.  Adjust the existing
                            // REMOVED action accordingly and ignore the ADDED action.
                            TimeSpan diff = newEvent.EventTimeStamp - eventListCandidates[indexRemoved].EventTimeStamp;

                            LogWrapper.LogMessage("EventQueue - Add", "Time diff (move seq) is : " + diff.TotalMilliseconds + "ms");
                            if (100 >= diff.TotalMilliseconds)
                            {
                                LogWrapper.LogMessage("EventQueue - Add", "Time diff is small so Assuming " + eventListCandidates[indexRemoved].FullPath + " was MOVED to " + newEvent.FullPath);
                                // Change the REMOVED event to a MOVE.
                                eventListCandidates[indexRemoved].EventType = LocalEvents.EventsType.FILE_ACTION_MOVE;

                                // Update the old path, full path, and time.
                                eventListCandidates[indexRemoved].OldFileName = eventListCandidates[indexRemoved].FileName;
                                eventListCandidates[indexRemoved].FileName = newEvent.FileName;
                                eventListCandidates[indexRemoved].OldFullPath = eventListCandidates[indexRemoved].FullPath;
                                eventListCandidates[indexRemoved].FullPath = newEvent.FullPath;
                                eventListCandidates[indexRemoved].IsDirectory = newEvent.IsDirectory;
                                eventListCandidates[indexRemoved].IsFile = newEvent.IsFile;
                                eventListCandidates[indexRemoved].Attributes = newEvent.Attributes;

                                // Ignore this event since it's really a move.
                                bAdd = false;

                                LogWrapper.LogMessage("EventQueue - Add", "Updating existing FILE_ACTION_REMOVED for: " + eventListCandidates[indexRemoved].FullPath + " to be FILE_ACTION_MOVE.");
                                LogWrapper.LogMessage("EventQueue - Add", "Ignoring new FILE_ACTION_ADDED for: " + newEvent.FullPath);
                            }
                        }
                    }
                }

                if (-1 != indexToRemove)
                {
                    eventListCandidates.RemoveAt(indexToRemove);
                }

                if (bAdd)
                {
                    if (1 == newEvent.EventTimeStamp.Year)
                        newEvent.EventTimeStamp = DateTime.Now;
                    eventListCandidates.Add(newEvent);
                }
            }
        }
        /// <summary>
        /// This function will return localeventlist 
        /// </summary>
        /// <returns></returns>
        public static List<LocalEvents> ListeventListFolders()
        {
            DateTime curTime = DateTime.Now;

            List<LocalEvents> localeventList = new List<LocalEvents>();
            List<LocalEvents> eventsToRemove = new List<LocalEvents>();

            lock (folderLock)
            {
                foreach(LocalEvents li in eventListFolders)
                {
                    TimeSpan diff = curTime - li.EventTimeStamp;
                    if (diff.TotalMilliseconds >= TIME_WITHOUT_EVENTS)
                    {
                        LocalEvents lEvent = new LocalEvents();
                        lEvent = li;
                        lEvent.EventTimeStamp = li.EventTimeStamp;
                        localeventList.Add(lEvent);
                        eventsToRemove.Add(li);
                    }
                }

                foreach (LocalEvents id in eventsToRemove)
                {
                    eventListFolders.Remove(id);
                }

                eventsToRemove.Clear();
            }

            return localeventList;
        }
        /// <summary>
        /// Collate the events before finally releasing them to be acted on.
        /// Go through the list of events and see what can be pruned out.
        /// For now, just look at items that are REMOVED.  If they don't
        /// exist in the database, then they were never created in the
        /// cloud and all related events can be removed as a NOOP.
        /// </summary>
        public static void CollateEvents()
        {
            if (0 < eventList.Count)
            {
                // Loop backwards theough the list.
                // If I find a REMOVED event, then keep track of it.
                List<LocalEvents> eventsToRemove = new List<LocalEvents>();
                for (int index = eventList.Count - 1; index >= 0; index--)
                {
                    if (eventList[index].EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED)
                    {
                        string strCheck = GetDbHandler().GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY }, new string[] { eventList[index].FileName }, new DbType[] { DbType.String });
                        if (0 == strCheck.Length)
                        {
                            LogWrapper.LogMessage("EventQueue - CollateEvents", "Event for item no in the database: (" + eventList[index].EventType + ") " + eventList[index].FullPath + " name: " + eventList[index].FileName);
                            // Since this item isn't in the database (and so not on the cloud),
                            // then we can throw out any events for this item since in the
                            // end it was deleted anyway.
                            LocalEvents lEvent = new LocalEvents();
                            lEvent = eventList[index];
                            eventsToRemove.Add(lEvent);

                            // Now look for related events (before this event) and throw them out as well.
                            // TODO: Revisit this code and verify the logic.  I think this inner loop should be between the create and delete events only.  Not from the start of the list up to the create event.
                            for (int indexRemove = 0; indexRemove < index; indexRemove++)
                            {
                                if ((eventList[indexRemove].FileName == lEvent.FileName) && (eventList[indexRemove].FullPath == lEvent.FullPath))
                                {
                                    LogWrapper.LogMessage("EventQueue - CollateEvents", "Removing event: (" + eventList[indexRemove].EventType + ") " + eventList[indexRemove].FullPath);
                                    LocalEvents relatedEvent = new LocalEvents();
                                    relatedEvent = eventList[indexRemove];
                                    eventsToRemove.Add(relatedEvent);
                                }
                            }
                        }
                    }
                }

                if (0 != eventsToRemove.Count)
                {
                    // Each event that was moved to eventList must
                    // be removed from eventListCandidates.
                    foreach (LocalEvents id in eventsToRemove)
                    {
                        eventList.Remove(id);
                    }
                    eventsToRemove.Clear();
                }
            }
        }
        public void PrepareStructureList()
        {
            foreach(string dirs in Directory.GetDirectories(BasicInfo.SyncDirPath, "*.*", SearchOption.AllDirectories))
            {
                string name = dirs.Substring(BasicInfo.SyncDirPath.Length + 1);
                currentStructure.Add(name);
            }

            foreach (string files in Directory.GetFiles(BasicInfo.SyncDirPath, "*.*", SearchOption.AllDirectories))
            {
                string name = files.Substring(BasicInfo.SyncDirPath.Length + 1);
                currentStructure.Add(name);
            }

            List<string> dbKeys = dbHandler.GetKeyList();

            foreach (string localKeys in currentStructure)
            {
                FileInfo fInfo = null;
                DirectoryInfo dInfo = null;
                bool IsFile = false;

                if (Directory.Exists(BasicInfo.SyncDirPath + "\\" + localKeys))
                {
                    dInfo = new DirectoryInfo(BasicInfo.SyncDirPath + "\\" + localKeys);
                    if ((dInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (dInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
                        continue;
                }
                else
                {
                    IsFile = true;
                    fInfo = new FileInfo(BasicInfo.SyncDirPath + "\\" + localKeys);
                    if ((fInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (fInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
                        continue;
                }

                string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY, DbHandler.STATUS }, new string[] { localKeys, "SUCCESS" }, new System.Data.DbType[] { System.Data.DbType.String, System.Data.DbType.String });

                if(strCheck.Trim().Length != 0)
                {
                    DateTime dbModDate = dbHandler.GetDateTime(DbHandler.TABLE_NAME, DbHandler.MODIFIED_DATE , DbHandler.KEY , localKeys);

                    bool isModified = false;

                    if (IsFile)
                    {
                        DateTime lastWriteTime = fInfo.LastWriteTime;
                        lastWriteTime = lastWriteTime.AddMilliseconds(-lastWriteTime.Millisecond);

                        TimeSpan diff = lastWriteTime - dbModDate;

                        if (diff >= TimeSpan.FromSeconds(1))
                        {
                            isModified = true;
                        }
                    }

                    if (isModified)
                    {
                        LocalEvents lEvent = new LocalEvents();
                        lEvent.FileName = localKeys;
                        if (IsFile)
                            lEvent.FullPath = fInfo.FullName;
                        else
                            lEvent.FullPath = dInfo.FullName;

                        lEvent.OldFileName = "";
                        lEvent.OldFullPath = "";
                        lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_MODIFIED;

                        EventQueue.Add(lEvent);
                    }
                }
                else
                {
                    LocalEvents lEvent = new LocalEvents();
                    lEvent.FileName = localKeys;
                    if (IsFile)
                        lEvent.FullPath = fInfo.FullName;
                    else
                        lEvent.FullPath = dInfo.FullName;

                    lEvent.OldFileName = "";
                    lEvent.OldFullPath = "";
                    lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;

                    EventQueue.Add(lEvent);
                }
            }

            foreach (string key in dbKeys)
            {
                FileInfo fInfo = null;
                DirectoryInfo dInfo = null;
                bool IsFile = false;
                String strPath = BasicInfo.SyncDirPath + "\\" + key;

                try
                {
                    if (Directory.Exists(strPath))
                    {
                        dInfo = new DirectoryInfo(strPath);
                    }
                    else
                    {
                        IsFile = true;
                        fInfo = new FileInfo(strPath);
                    }
                }
                catch (System.IO.PathTooLongException ex)
                {
                    // Skip this item.
                    LogWrapper.LogMessage("OfflineWatcher - PrepareStructureList", "Caught exception: " + ex.Message);
                    continue;
                }

                if(!currentStructure.Contains(key))
                {
                    LocalEvents lEvent = new LocalEvents();
                    lEvent.FileName = key;
                    if (IsFile)
                        lEvent.FullPath = fInfo.FullName;
                    else
                        lEvent.FullPath = dInfo.FullName;

                    lEvent.OldFileName = "";
                    lEvent.OldFullPath = "";
                    lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_REMOVED;

                    EventQueue.Add(lEvent);
                }
            }
        }
        private int HandleEvent(BackgroundWorker caller, LocalEvents localEvent)
        {
            int returnCode = 1;
            LogWrapper.LogMessage("frmSyncManager - HandleEvent", "Enter");

            if (null == localEvent)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent", "Leave (localEvent was null)");
                return returnCode;
            }

            bool RemoveIndexes = false;

            if (caller.CancellationPending)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent ", "Cancelled called");
                caller.CancelAsync();
                return USER_CANCELLED;
            }

            bool bRet = true;

            LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath);

            FileAttributes attr = localEvent.Attributes;

            bool isDirectory = localEvent.IsDirectory;
            bool isFile = localEvent.IsFile;
            if (!isFile && !isDirectory)
            {
                // An optimization to keep from making disk calls all the time.
                isFile = File.Exists(localEvent.FullPath);
                if (!isFile)
                    isDirectory = Directory.Exists(localEvent.FullPath);
                if (isFile || isDirectory)
                    attr = File.GetAttributes(localEvent.FullPath);
            }

            if (!isFile && !isDirectory)
            {
                if ((localEvent.EventType != LocalEvents.EventsType.FILE_ACTION_REMOVED) && (localEvent.EventType != LocalEvents.EventsType.FILE_ACTION_RENAMED) && (localEvent.EventType != LocalEvents.EventsType.FILE_ACTION_MOVE))
                {
                    dbHandler.DeleteEvent(localEvent.EventDbId);
                    return 1;
                }
            }
            else if (isFile)
            {
                // Make sure the attributes are up to date.
                FileInfo fileInfo = new FileInfo(localEvent.FullPath);
                if (fileInfo.Exists)
                    attr = fileInfo.Attributes;
                else if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
                {
                    // If the file doesn't exist, then we can't upload it.
                    return 1;
                }
            }

            if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_MODIFIED)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Enter");

                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                    bRet = false;
                else
                {
                    int nRet = CheckForModifyEvent(localEvent);
                    if (nRet == 0)
                        bRet = false;
                    else if (nRet == 1)
                        bRet = true;
                    else if (nRet == 2)
                    {
                        // If the event was queued up as a MODIFY instead
                        // of an ADDED by mistake, then change it back.
                        LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - Changed from FILE_ACTION_MODIFIED to " + localEvent.EventType.ToString());
                        localEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;
                        bRet = false;
                    }
                }
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Leave");
            }

            if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED || localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Enter");

                string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY, DbHandler.STATUS }, new string[] { localEvent.FileName, DB_STATUS_SUCCESS }, new DbType[] { DbType.String, DbType.String });

                if (strCheck.Trim().Length == 0)
                    bRet = true;
                else
                    bRet = false;

                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Leave");
            }

            if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Enter");

                string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY }, new string[] { localEvent.OldFileName }, new DbType[] { DbType.String });
                if (strCheck.Trim().Length == 0)
                {
                    string strCheck1 = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY, DbHandler.STATUS }, new string[] { localEvent.FileName, DB_STATUS_SUCCESS }, new DbType[] { DbType.String, DbType.String });
                    if (strCheck1.Trim().Length == 0)
                    {
                        localEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;
                    }
                }

                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Leave");
            }

            if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Enter");

                string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY }, new string[] { localEvent.FileName }, new DbType[] { DbType.String });
                if (strCheck.Trim().Length == 0)
                    bRet = false;
                else
                    bRet = true;

                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - " + localEvent.EventType.ToString() + " - Leave");
            }

            if ((attr & FileAttributes.Hidden) == FileAttributes.Hidden || (attr & FileAttributes.Temporary) == FileAttributes.Temporary)
                bRet = false;

            if (bRet)
            {
                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - AddinDB Enter");

                if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_MODIFIED)
                {
                    UpdateDBForStatus(localEvent, DB_STATUS_IN_PROGRESS);
                }
                else if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
                {
                    AddInDBForAdded(localEvent);
                }
                else if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
                {
                    AddInDBForRename(localEvent);
                }

                LogWrapper.LogMessage("frmSyncManager - HandleEvent - localEvent - ", localEvent.FullPath + " - AddinDB Leave");
            }

            if (!bRet)
            {
                if (!RemoveIndexes)
                {
                    RemoveIndexes = true;
                    if (localEvent.EventType == LocalEvents.EventsType.FILE_ACTION_REMOVED)
                    {
                        MarkParentsStatus(localEvent.FullPath, DB_STATUS_SUCCESS);
                        UpdateDBForRemoveSuccess(localEvent);
                    }
                    dbHandler.DeleteEvent(localEvent.EventDbId);
                }
            }

            if (caller != null)
            {
                caller.ReportProgress(SYNC_STARTED);
            }

            LogWrapper.LogMessage("frmSyncManager - HandleEvent", " ProcessLocalEvent Going");

            // If we didn't remove the item, then process it.
            if (!RemoveIndexes)
                returnCode = ProcessLocalEvent(caller, ref localEvent);

            LogWrapper.LogMessage("frmSyncManager - HandleEvent", " ProcessLocalEvent Exit");

            LogWrapper.LogMessage("frmSyncManager - HandleEvent", "Leave");
            return returnCode;
        }
        private void GetNextEvent(ref LocalEvents lEvent, ref NQDetails nqEvent, ref LocalItemDetails localItemDetails, ref string strDisplayName)
        {
            bool usePriorityQueueLogic = false;
            if (usePriorityQueueLogic)
            {
                // See if there are any events in the queue.
                // Local events take priority over NQ.
                // localItemDetails (initial sync events) take priority over local events.
                localItemDetails = dbHandler.GetLocalItemDetailsEvent();
                if (localItemDetails == null)
                {
                    lEvent = dbHandler.GetLocalEvent();
                    if (lEvent == null)
                        nqEvent = dbHandler.GetNQEvent();
                }
            }
            else
            {
                // See if there are any events in the queue.
                // localItemDetails (initial sync events) take priority over other events.
                // If there are no 'I'nitial sync events, just get the item with the
                // lowest index, determine the type, populate it, and return it.
                // The GetXEvent() functions sort by index so we just have to know
                // the type of event before calling the appropriate function.
                localItemDetails = dbHandler.GetLocalItemDetailsEvent();
                if (localItemDetails == null)
                {
                    string eventType = "";
                    Int64 eventId = dbHandler.GetNextEventId(ref eventType);
                    if (-1 != eventId)
                    {
                        switch (eventType)
                        {
                            case "I":    // The 'I'nitial events should already be handled.
                                break;

                            case "L":    // 'L'ocal event.
                                lEvent = dbHandler.GetLocalEvent();
                                break;

                            case "N":    // 'N'otification queue event.
                                nqEvent = dbHandler.GetNQEvent();
                                break;
                        }
                    }
                }
            }

            if (null != lEvent)
                strDisplayName = lEvent.FullPath;
            else if (null != nqEvent)
                strDisplayName = nqEvent.StrObjectName;
            else if (null != localItemDetails)
                strDisplayName = localItemDetails.Path;
        }
        private int CheckForModifyEvent(LocalEvents lEvent)
        {
            LogWrapper.LogMessage("frmSyncManager - CheckForModifyEvent", "enter");
            string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
            if (strCheck.Trim().Length == 0)
            {
                LogWrapper.LogMessage("frmSyncManager - CheckForModifyEvent", "leave");
                return 2;
            }
            else
            {
                if (false == File.Exists(lEvent.FullPath))
                {
                    LogWrapper.LogMessage("frmSyncManager - CheckForModifyEvent", "leave - physical file " + lEvent.FullPath + " no longer exists.");
                    return 0;
                }

                DateTime DBModTime = dbHandler.GetDateTime(DbHandler.TABLE_NAME, DbHandler.MODIFIED_DATE, DbHandler.KEY, lEvent.FileName);

                DateTime ActualModTime = File.GetLastWriteTime(lEvent.FullPath);
                ActualModTime = ActualModTime.AddMilliseconds(-ActualModTime.Millisecond);
                TimeSpan diff = ActualModTime - DBModTime;
                if (ActualModTime < DBModTime)
                    diff = DBModTime - ActualModTime;

                if (diff >= TimeSpan.FromSeconds(1) || diff.CompareTo(TimeSpan.Zero) < 0)
                {
                    LogWrapper.LogMessage("frmSyncManager - CheckForModifyEvent", "leave");
                    return 1;
                }
                else
                {
                    LogWrapper.LogMessage("frmSyncManager - CheckForModifyEvent", "leave");
                    return 0;
                }
            }
        }
        private bool CheckForConflicts(LocalEvents lEvent, string strContentUrl)
        {
            //LogWrapper.LogMessage("SyncManager - CheckForConflicts", "Enter, content uri " + strContentUrl);
            int nStatusCode = 0;
            bool bRet = false;
            string strEtag;
            switch (lEvent.EventType)
            {
                case LocalEvents.EventsType.FILE_ACTION_MODIFIED:
                    {
                        strEtag = cMezeoFileCloud.GetETag(strContentUrl, ref nStatusCode);
                        string strDBETag = GetETag(lEvent.FileName);
                        if (strEtag.Trim().Length != 0)
                        {
                            if (strEtag != strDBETag)
                            {
                                ReportConflict(lEvent, IssueFound.ConflictType.CONFLICT_MODIFIED);
                                return true;
                            }
                            else
                            {
                                string URL = "";
                                if (strContentUrl.Substring(strContentUrl.Length - 9).Equals("/contents") ||
                                    strContentUrl.Substring(strContentUrl.Length - 8).Equals("/content"))
                                {
                                    URL = strContentUrl.Substring(0, strContentUrl.LastIndexOf("/"));
                                }

                                ItemDetails IDetails = cMezeoFileCloud.GetContinerResult(URL, ref nStatusCode);
                                string FileName = lEvent.FileName.Substring((lEvent.FileName.LastIndexOf("\\") + 1));
                                if (FileName != IDetails.strName)
                                {
                                    string FileReName = lEvent.FullPath.Substring(0, lEvent.FullPath.LastIndexOf("\\") + 1);
                                    FileReName += IDetails.strName;

                                    bRet = cMezeoFileCloud.OverWriteFile(lEvent.FullPath, strContentUrl, ref nStatusCode);
                                    if (bRet)
                                    {
                                        UpdateDBForModifiedSuccess(lEvent, strContentUrl);
                                    }

                                    if (File.Exists(lEvent.FullPath))
                                        File.Move(lEvent.FullPath, FileReName);

                                    lEvent.OldFullPath = lEvent.FullPath;
                                    lEvent.FullPath = FileReName;
                                    lEvent.OldFileName = lEvent.FileName;
                                    lEvent.FileName = lEvent.FileName.Substring(0, lEvent.FileName.LastIndexOf("\\") + 1);
                                    lEvent.FileName += IDetails.strName;

                                    dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.KEY, lEvent.FileName, DbHandler.KEY, lEvent.OldFileName);
                                    UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);

                                    return false;
                                }
                                else
                                    return true;
                            }
                        }
                        else
                        {
                            string strParentURL = GetParentURI(lEvent.FileName);
                            string strURL = cMezeoFileCloud.UploadingFile(lEvent.FullPath, strParentURL, ref nStatusCode);
                            string strEtagNew = cMezeoFileCloud.GetETag(strURL, ref nStatusCode);

                            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, strURL, DbHandler.KEY, lEvent.FileName);
                            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, strEtagNew, DbHandler.KEY, lEvent.FileName);

                            return false;
                        }
                    }
                // break;
                case LocalEvents.EventsType.FILE_ACTION_REMOVED:
                    {
                        strEtag = cMezeoFileCloud.GetETag(strContentUrl, ref nStatusCode);
                        string strDBETag = GetETag(lEvent.FileName);
                        string FileName = lEvent.FileName.Substring((lEvent.FileName.LastIndexOf("\\") + 1));

                        string URL = "";
                        if (strContentUrl.Substring(strContentUrl.Length - 9).Equals("/contents") ||
                            strContentUrl.Substring(strContentUrl.Length - 8).Equals("/content"))
                        {
                            URL = strContentUrl.Substring(0, strContentUrl.LastIndexOf("/"));
                        }

                        ItemDetails IDetails = cMezeoFileCloud.GetContinerResult(URL, ref nStatusCode);

                        if (strEtag.Trim().Length != 0)
                        {
                            if ((strEtag != strDBETag) || (FileName != IDetails.strName))
                            {
                                lEvent.FullPath = lEvent.FullPath.Substring(0, lEvent.FullPath.LastIndexOf("\\") + 1);
                                lEvent.FullPath += IDetails.strName;

                                bRet = cMezeoFileCloud.DownloadFile(strContentUrl + "/" + IDetails.strName, lEvent.FullPath, IDetails.dblSizeInBytes, ref nStatusCode);

                                if (bRet)
                                {
                                    UpdateDBForRemoveSuccess(lEvent);
                                    if (FileName != IDetails.strName)
                                    {
                                        lEvent.FileName = lEvent.FileName.Substring(0, lEvent.FileName.LastIndexOf("\\") + 1);
                                        lEvent.FileName += IDetails.strName;
                                    }
                                    AddInDBForAdded(lEvent);
                                    UpdateDBForAddedSuccess(strContentUrl, lEvent);

                                    return false;
                                }
                                return true;
                            }
                            return true;
                        }
                        else
                        {
                            UpdateDBForRemoveSuccess(lEvent);
                            return false;
                        }
                    }
                //  break;
                case LocalEvents.EventsType.FILE_ACTION_RENAMED:
                    {
                        strEtag = cMezeoFileCloud.GetETag(strContentUrl, ref nStatusCode);

                        // If the item doesn't exist, then it doesn't conflict.
                        if (nStatusCode == ResponseCode.NOTFOUND)
                            return true;

                        string strDBETag = GetETag(lEvent.FileName);
                        string FileName = lEvent.FileName.Substring((lEvent.FileName.LastIndexOf("\\") + 1));

                        string URL = "";
                        if (strContentUrl.Substring(strContentUrl.Length - 9).Equals("/contents") ||
                            strContentUrl.Substring(strContentUrl.Length - 8).Equals("/content"))
                        {
                            URL = strContentUrl.Substring(0, strContentUrl.LastIndexOf("/"));
                        }

                        ItemDetails IDetails = cMezeoFileCloud.GetContinerResult(URL, ref nStatusCode);

                        if (strEtag.Trim().Length != 0)
                        {
                            if (strEtag != strDBETag)
                            {
                                bRet = cMezeoFileCloud.DownloadFile(strContentUrl + "/" + lEvent.FileName, lEvent.FullPath, IDetails.dblSizeInBytes, ref nStatusCode);
                                if (bRet)
                                {
                                    string strEtagNew = cMezeoFileCloud.GetETag(strContentUrl, ref nStatusCode);
                                    dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, strEtagNew, DbHandler.KEY, lEvent.FileName);

                                    FileInfo fInfo = new FileInfo(lEvent.FullPath);
                                    dbHandler.UpdateModifiedDate(fInfo.LastWriteTime, lEvent.FileName);
                                    return true;
                                }
                            }
                            return true;
                        }
                        else
                        {
                            string strParentUri = GetParentURI(lEvent.FileName);
                            string strUri = cMezeoFileCloud.UploadingFile(lEvent.FullPath, strParentUri, ref nStatusCode);
                            if (strUri.Trim().Length != 0)
                            {
                                dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.KEY, lEvent.FileName, DbHandler.KEY, lEvent.OldFileName);
                                dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, strUri, DbHandler.KEY, lEvent.FileName);

                                string strEtagUpload = cMezeoFileCloud.GetETag(strUri, ref nStatusCode);

                                dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, strEtagUpload, DbHandler.KEY, lEvent.FileName);

                                UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);
                                return false;
                            }
                            return true;
                        }
                    }
                //   break;
            }

            //LogWrapper.LogMessage("SyncManager - CheckForConflicts", "Leave");
            return true;
        }
        private int checkfoOverwrite(ItemDetails item, LocalEvents lEvent)
        {
            int nStatusCode = 0;
            if (!checkFileTooLarge(lEvent.FullPath))
               //cMezeoFileCloud.OverWriteFile(lEvent.FullPath, item.szContentUrl, ref nStatusCode);
                cMezeoFileCloud.UploadingFileOnResume(lEvent.FullPath, item.szContentUrl, ref nStatusCode);
            else
                nStatusCode = 200;

            if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
            {
                return LOGIN_FAILED;
            }
            else if (nStatusCode != ResponseCode.OVERWRITEFILE)
            {
                if (ResponseCode.NOTFOUND == nStatusCode)
                    return ITEM_NOT_FOUND;
                return SERVER_INACCESSIBLE;
            }
            else
            {
                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                UpdateDBForModifiedSuccess(lEvent, item.szContentUrl);
                dbHandler.DeleteEvent(lEvent.EventDbId);
            }

            return nStatusCode;
        }
        private string CheckAndCreateForEventsParentDir(string strKeyEvent)
        {
            string strKey = strKeyEvent.Substring(0, strKeyEvent.LastIndexOf("\\"));

            //bool bIsDir = Directory.Exists(strpath);
            string strCheck = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL, new string[] { DbHandler.KEY }, new string[] { strKey }, new DbType[] { DbType.String });
            if (strCheck.Trim().Length == 0)
            {
                string strpath = BasicInfo.SyncDirPath + "\\" + strKey;
                LocalEvents levent = new LocalEvents();
                levent.FullPath = strpath;
                levent.FileName = strKey;
                levent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;

                AddInDBForAdded(levent);

                string strUrl = "";
                int nStatusCode = 0;

                string strParentURi = GetParentURI(levent.FileName);
                string folderName = levent.FullPath.Substring((levent.FullPath.LastIndexOf("\\") + 1));
                strUrl = cMezeoFileCloud.NewContainer(folderName, strParentURi, ref nStatusCode);
                strUrl += "/contents";

                if ((strUrl.Trim().Length != 0) && (nStatusCode == 201))
                {
                    UpdateDBForAddedSuccess(strUrl, levent);

                    dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, strUrl, DbHandler.KEY, strKeyEvent);
                }

                return strUrl;
            }

            return "";
        }
        private void WalkDirectoryTreeforAddFolder(System.IO.DirectoryInfo root, string lEventOldPath, ref List<LocalEvents> addEvents, ref List<LocalEvents> events)
        {
            System.IO.FileInfo[] files = null;
            System.IO.DirectoryInfo[] subDirs = null;
            bool bIsAlreadyAdded = false;
            // First, process all the files directly under this folder
            try
            {
                files = root.GetFiles("*.*");
            }
            // This is thrown if even one of the files requires permissions greater
            // than the application provides.
            catch (UnauthorizedAccessException e)
            {
                LogWrapper.LogMessage("frmSyncManager - WalkDirectoryTreeforAddFolder", "Caught exception (UnauthorizedAccessException): " + e.Message);
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                LogWrapper.LogMessage("frmSyncManager - WalkDirectoryTreeforAddFolder", "Caught exception (DirectoryNotFoundException): " + e.Message);
            }

            if (files != null)
            {
                foreach (System.IO.FileInfo fi in files)
                {
                    bIsAlreadyAdded = false;
                    foreach (LocalEvents id in events)
                    {
                        if (id.FileName == lEventOldPath + "\\" + fi.Name && id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
                            bIsAlreadyAdded = true;
                    }

                    try
                    {
                        FileAttributes attr = File.GetAttributes(fi.FullName);
                        if ((attr & FileAttributes.Hidden) == FileAttributes.Hidden || (attr & FileAttributes.Temporary) == FileAttributes.Temporary)
                            bIsAlreadyAdded = true;
                    }
                    catch (Exception ex)
                    {
                        LogWrapper.LogMessage("frmSyncManager - WalkDirectoryTreeforAddFolder", "Caught exception: " + ex.Message);
                        bIsAlreadyAdded = true;
                    }

                    if (!bIsAlreadyAdded)
                    {
                        LocalEvents lEvent = new LocalEvents();
                        lEvent.FileName = lEventOldPath + "\\" + fi.Name;
                        lEvent.FullPath = fi.FullName;
                        lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;

                        addEvents.Add(lEvent);
                    }
                }

                // Now find all the subdirectories under this directory.
                subDirs = root.GetDirectories();

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    bIsAlreadyAdded = false;
                    // Resursive call for each subdirectory.
                    foreach (LocalEvents id in events)
                    {
                        if (id.FileName == lEventOldPath + "\\" + dirInfo.Name && id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
                            bIsAlreadyAdded = true;
                    }

                    if (!bIsAlreadyAdded)
                    {
                        LocalEvents lEvent = new LocalEvents();
                        lEvent.FileName = lEventOldPath + "\\" + dirInfo.Name;
                        lEvent.FullPath = dirInfo.FullName;
                        lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;

                        addEvents.Add(lEvent);
                    }

                    WalkDirectoryTreeforAddFolder(dirInfo, lEventOldPath + "\\" + dirInfo.Name, ref addEvents, ref events);
                }
            }
        }
        private int ProcessLocalEvent(BackgroundWorker caller, ref LocalEvents lEvent)
        {
            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Enter");
            string strUrl = "";
            bool bRetConflicts = true;
            bool wasSuccessful = false;

            if (caller != null)
            {
                caller.ReportProgress(PROCESS_LOCAL_EVENTS_STARTED, 1);
            }

            if (caller.CancellationPending)
            {
                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Canceled Called");
                caller.CancelAsync();
                return USER_CANCELLED;
            }

            if (caller != null)
            {
                caller.ReportProgress(PROGRESS_CHANGED_WITH_FILE_NAME, lEvent.FullPath);
            }

            FileAttributes attr = lEvent.Attributes;
            bool isDirectory = lEvent.IsDirectory;
            bool isFile = lEvent.IsFile;

            if (isFile && lEvent.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED)
            {
                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Check for file lock - Enter");
                FileInfo fInfo = new FileInfo(lEvent.FullPath);
                bool IsLocked = IsFileLocked(fInfo);
                while (IsLocked && fInfo.Exists)
                {
                    IsLocked = IsFileLocked(fInfo);
                }
                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Check for file lock - Leave");
            }

            if (!isFile && !isDirectory)
            {
                attr = FileAttributes.Normal;
                if (lEvent.EventType == LocalEvents.EventsType.FILE_ACTION_RENAMED)
                {
                    isFile = lEvent.IsFile;
                    isDirectory = lEvent.IsDirectory;
                }
                else if (lEvent.EventType != LocalEvents.EventsType.FILE_ACTION_REMOVED)
                {
                    dbHandler.DeleteEvent(lEvent.EventDbId);
                    LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "SKIPPING EVENT - For the path " + lEvent.FullPath + ".  Unable to find a file/directory at the given location for the event type " + lEvent.EventType + ".");
                    return 1;
                }
            }

            int nStatusCode = 0;
            bool bRet = true;

            switch (lEvent.EventType)
            {
                case LocalEvents.EventsType.FILE_ACTION_MOVE:
                    {
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_MOVE - Enter for file path " + lEvent.FullPath);
                        string strContentURi = GetContentURI(lEvent.FileName);
                        if (strContentURi.Trim().Length == 0)
                        {
                            strContentURi = GetContentURI(lEvent.OldFileName);
                        }
                        if (strContentURi.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetContentURI for length ZERO");
                            return 1;
                        }

                        if (strContentURi.Substring(strContentURi.Length - 9).Equals("/contents") ||
                            strContentURi.Substring(strContentURi.Length - 8).Equals("/content"))
                        {
                            strContentURi = strContentURi.Substring(0, strContentURi.LastIndexOf("/"));
                        }

                        string strParentUri = GetParentURI(lEvent.FileName);
                        if (strParentUri.Trim().Length == 0)
                        {
                            strParentUri = GetParentURI(lEvent.OldFileName);
                        }
                        if (strParentUri.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetParentURI for length ZERO");
                            return 1;
                        }

                        if (strParentUri.Substring(strParentUri.Length - 9).Equals("/contents") ||
                            strParentUri.Substring(strParentUri.Length - 8).Equals("/content"))
                        {
                            strParentUri = strParentUri.Substring(0, strParentUri.LastIndexOf("/"));
                        }

                        string strName = lEvent.FullPath.Substring(lEvent.FullPath.LastIndexOf("\\") + 1);
                        ItemDetails iDetails = cMezeoFileCloud.GetContinerResult(strContentURi, ref nStatusCode);

                        if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                        {
                            return LOGIN_FAILED;
                        }
                        else if (nStatusCode == ResponseCode.NOTFOUND)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Remote object no longer exists.  Remove local object.");
                            nqEventCdmiDelete(lEvent.FullPath, lEvent.OldFileName);
                            return 1;
                        }
                        else if (nStatusCode != ResponseCode.GETCONTINERRESULT)
                        {
                            if (ResponseCode.NOTFOUND == nStatusCode)
                                return ITEM_NOT_FOUND;
                            return SERVER_INACCESSIBLE;
                        }

                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PUBLIC, iDetails.bPublic, DbHandler.KEY, lEvent.FileName);
                        AddInDBForRename(lEvent);
                        string mimeType = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.MIMIE_TYPE, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                        if (0 == mimeType.Length)
                            mimeType = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.MIMIE_TYPE, new string[] { DbHandler.KEY }, new string[] { lEvent.OldFileName }, new DbType[] { DbType.String });

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            bRet = cMezeoFileCloud.ContainerMove(strContentURi, strName, mimeType, iDetails.bPublic, strParentUri, ref nStatusCode);
                        }
                        else
                        {
                            if (!checkFileTooLarge(lEvent.FullPath))
                                bRet = cMezeoFileCloud.FileMove(strContentURi, strName, mimeType, iDetails.bPublic, strParentUri, ref nStatusCode);
                            else
                                nStatusCode = 200;
                        }

                        if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                        {
                            return LOGIN_FAILED;
                        }
                        else if (nStatusCode != ResponseCode.CONTAINERMOVE)
                        {
                            if (ResponseCode.NOTFOUND == nStatusCode)
                                return ITEM_NOT_FOUND;
                            return SERVER_INACCESSIBLE;
                        }
                        else
                        {
                            // Update the key for the children if this was a container.
                            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                                dbHandler.UpdateRenamedOrMovedKey(lEvent.FileName, lEvent.OldFileName);

                            // Since the item could have a new parent, it needs to be updated.
                            // Change this for renames as well as moves....
                            UpdateParent(lEvent.FileName, lEvent.FullPath);

                            wasSuccessful = true;
                            UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);
                            MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                            dbHandler.DeleteEvent(lEvent.EventDbId);
                        }

                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_MOVE - Leave for file path " + lEvent.FullPath);
                    }
                    break;
                case LocalEvents.EventsType.FILE_ACTION_ADDED:
                    {
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_ADDED - Enter for file path " + lEvent.FullPath);
                        MarkParentsStatus(lEvent.FullPath, DB_STATUS_IN_PROGRESS);
                        string strParentURi = GetParentURI(lEvent.FileName);
                        if (strParentURi.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetParentURI for length ZERO");
                            return 1;
                        }

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            string folderName = lEvent.FullPath.Substring((lEvent.FullPath.LastIndexOf("\\") + 1));

                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Create new container for folder " + folderName);

                            // Defect 273 - If somehow, someway the same folder name exists locally and on the cloud,
                            //              do not create a new folder in the cloud with this name.  Just use the existing
                            //              container and upload files/containers into it.
                            ItemDetails[] itemDetails;
                            bool bCreateCloudContainer = true;

                            // Grab a list of files and containers for the parent.
                            itemDetails = cMezeoFileCloud.DownloadItemDetails(strParentURi, ref nStatusCode, folderName);
                            if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                            {
                                return LOGIN_FAILED;
                            }
                            else if (nStatusCode == ResponseCode.INTERNAL_SERVER_ERROR)
                            {
                                // Don't do anything, just keep on chugging.
                            }
                            else if (nStatusCode != ResponseCode.DOWNLOADITEMDETAILS)
                            {
                                if (ResponseCode.NOTFOUND == nStatusCode)
                                    return ITEM_NOT_FOUND;
                                return SERVER_INACCESSIBLE;
                            }
                            else if (nStatusCode == ResponseCode.DOWNLOADITEMDETAILS)
                            {
                                // Look through each item for a container with the same name.
                                if (itemDetails != null)
                                {
                                    foreach (ItemDetails item in itemDetails)
                                    {
                                        if ("DIRECTORY" == item.szItemType)
                                        {
                                            if (folderName == item.strName)
                                            {
                                                // Don't create a new/duplicate folder.
                                                bCreateCloudContainer = false;
                                                // Populate the url with this folder.
                                                strUrl = item.szContentUrl;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            if (bCreateCloudContainer)
                            {
                                strUrl = cMezeoFileCloud.NewContainer(folderName, strParentURi, ref nStatusCode);
                                if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                                {
                                    return LOGIN_FAILED;
                                }
                                else if (nStatusCode != ResponseCode.NEWCONTAINER)
                                {
                                    if (ResponseCode.NOTFOUND == nStatusCode)
                                        return ITEM_NOT_FOUND;
                                    return SERVER_INACCESSIBLE;
                                }
                                else if ((strUrl.Trim().Length != 0) && (nStatusCode == ResponseCode.NEWCONTAINER))
                                {
                                    strUrl += "/contents";
                                    wasSuccessful = true;
                                    dbHandler.DeleteEvent(lEvent.EventDbId);
                                    bRet = true;

                                    string strParent = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                                    if (strParent.Trim().Length == 0)
                                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, strParentURi, DbHandler.KEY, lEvent.FileName);

                                    MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                    UpdateDBForAddedSuccess(strUrl, lEvent);
                                }
                            }
                            else
                            {
                                wasSuccessful = true;
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                                bRet = true;

                                string strParent = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                                if (strParent.Trim().Length == 0)
                                    dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, strParentURi, DbHandler.KEY, lEvent.FileName);

                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                UpdateDBForAddedSuccess(strUrl, lEvent);
                            }

                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Container URI for folder " + folderName + " is " + strUrl);
                        }
                        else
                        {
                            //if (strParentURi.Trim().Length == 0)
                            //    strParentURi = CheckAndCreateForEventsParentDir(lEvent.FileName);

                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Start uploading file for " + lEvent.FullPath + ", at parent URI " + strParentURi);

                            string fileName = lEvent.FullPath.Substring((lEvent.FullPath.LastIndexOf("\\") + 1));
                            ItemDetails[] itemDetailsfile;
                            bool buploadfileToCloud = true;

                            // Grab a list of files for the parent.
                            itemDetailsfile = cMezeoFileCloud.DownloadItemDetails(strParentURi, ref nStatusCode, fileName);

                            if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                            {
                                return LOGIN_FAILED;
                            }
                            else if (nStatusCode == ResponseCode.INTERNAL_SERVER_ERROR)
                            {
                                // Don't do anything, just keep on chugging.
                            }
                            else if (nStatusCode != ResponseCode.DOWNLOADITEMDETAILS)
                            {
                                if (ResponseCode.NOTFOUND == nStatusCode)
                                    return ITEM_NOT_FOUND;
                                return SERVER_INACCESSIBLE;
                            }
                            else if (nStatusCode == ResponseCode.DOWNLOADITEMDETAILS)
                            {
                                // Look through each item for a file with the same name.
                                if (itemDetailsfile != null)
                                {
                                    foreach (ItemDetails item in itemDetailsfile)
                                    {
                                        if ("FILE" == item.szItemType)
                                        {
                                            if (fileName == item.strName)
                                            {
                                                // Don't create a new/duplicate file.
                                                buploadfileToCloud = false;
                                                // Populate the url with this file.
                                                strUrl = item.szContentUrl;
                                                checkfoOverwrite(item, lEvent);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            if (buploadfileToCloud)
                            {
                                if (!checkFileTooLarge(lEvent.FullPath))
                                    strUrl = cMezeoFileCloud.UploadingFile(lEvent.FullPath, strParentURi, ref nStatusCode);
                                else
                                    nStatusCode = 201;

                                if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                                {
                                    return LOGIN_FAILED;
                                }
                                else if (nStatusCode != ResponseCode.UPLOADINGFILE)
                                {
                                    // Apparently, the -4 from a file upload is ONLY when
                                    // the upload was interrupted/canceled by the user.
                                    if ((ResponseCode.NOTFOUND == nStatusCode) || (nStatusCode == -4))
                                        return ITEM_NOT_FOUND;
                                    return SERVER_INACCESSIBLE;
                                }
                                else if ((strUrl.Trim().Length != 0) && (nStatusCode == ResponseCode.UPLOADINGFILE))
                                {
                                    strUrl += "/content";
                                    wasSuccessful = true;
                                    dbHandler.DeleteEvent(lEvent.EventDbId);
                                    bRet = true;

                                    string strParent = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                                    if (strParent.Trim().Length == 0)
                                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, strParentURi, DbHandler.KEY, lEvent.FileName);

                                    MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                    UpdateDBForAddedSuccess(strUrl, lEvent);
                                }
                            }
                            else
                            {
                                wasSuccessful = true;
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                                bRet = true;

                                string strParent = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                                if (strParent.Trim().Length == 0)
                                    dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PARENT_URL, strParentURi, DbHandler.KEY, lEvent.FileName);

                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                UpdateDBForAddedSuccess(strUrl, lEvent);
                            }
                        }

                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_ADDED - Leave for file path " + lEvent.FullPath);
                    }
                    break;

                case LocalEvents.EventsType.FILE_ACTION_MODIFIED:
                    {
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_MODIFIED - Enter for file path " + lEvent.FullPath);

                        // If the physical file no longer exists, then skip this event.
                        if (false == File.Exists(lEvent.FullPath))
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Physical file is no longer available.");
                            return 1;
                        }

                        MarkParentsStatus(lEvent.FullPath, DB_STATUS_IN_PROGRESS);
                        string strContentURi = GetContentURI(lEvent.FileName);
                        if (strContentURi.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetContentURI for length ZERO");
                            return 1;
                        }

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                            bRet = false;
                        else
                        {
                            bRetConflicts = CheckForConflicts(lEvent, strContentURi);
                            if (bRetConflicts)
                            {
                                if (!checkFileTooLarge(lEvent.FullPath))
                                    bRet = cMezeoFileCloud.OverWriteFile(lEvent.FullPath, strContentURi, ref nStatusCode);
                                else
                                    nStatusCode = 200;

                                if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                                {
                                    return LOGIN_FAILED;
                                }
                                else if (nStatusCode != ResponseCode.OVERWRITEFILE)
                                {
                                    if (ResponseCode.NOTFOUND == nStatusCode)
                                        return ITEM_NOT_FOUND;
                                    return SERVER_INACCESSIBLE;
                                }
                                else
                                {
                                    wasSuccessful = true;
                                    MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                    UpdateDBForModifiedSuccess(lEvent, strContentURi);
                                    dbHandler.DeleteEvent(lEvent.EventDbId);
                                }
                            }
                            else
                            {
                                wasSuccessful = true;
                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                UpdateDBForModifiedSuccess(lEvent, strContentURi);
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                            }
                        }

                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_MODIFIED - Leave for file path " + lEvent.FullPath);
                    }
                    break;
                case LocalEvents.EventsType.FILE_ACTION_REMOVED:
                    {
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_REMOVED - Enter for file path " + lEvent.FullPath);

                        string strContentURi = GetContentURI(lEvent.FileName);
                        if (strContentURi.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetContentURI for length ZERO");
                            return 1;
                        }

                        MarkParentsStatus(lEvent.FullPath, DB_STATUS_IN_PROGRESS);

                        if (isFile)
                            bRetConflicts = CheckForConflicts(lEvent, strContentURi);

                        if (bRetConflicts)
                        {
                            if (strContentURi.Substring(strContentURi.Length - 9).Equals("/contents") ||
                                strContentURi.Substring(strContentURi.Length - 8).Equals("/content"))
                            {
                                strContentURi = strContentURi.Substring(0, strContentURi.LastIndexOf("/"));
                            }

                            if (!checkFileTooLarge(lEvent.FullPath))
                                bRet = cMezeoFileCloud.Delete(strContentURi, ref nStatusCode, lEvent.FullPath);
                            else
                                nStatusCode = 200;

                            if (nStatusCode == ResponseCode.LOGINFAILED1)
                            {
                                return LOGIN_FAILED;
                            }
                            else if (nStatusCode == ResponseCode.NOTFOUND || nStatusCode == ResponseCode.LOGINFAILED2)
                            {
                                // If it doesn't exist on the server, then it's the same thing as far as we're concerned.
                                wasSuccessful = true;
                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                UpdateDBForRemoveSuccess(lEvent);
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                            }
                            else if (nStatusCode != ResponseCode.DELETE)
                            {
                                if (ResponseCode.NOTFOUND == nStatusCode)
                                    return ITEM_NOT_FOUND;
                                return SERVER_INACCESSIBLE;
                            }
                            else
                            {
                                wasSuccessful = true;
                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                UpdateDBForRemoveSuccess(lEvent);
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                            }
                        }

                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "FILE_ACTION_REMOVED - Leave for file path " + lEvent.FullPath);
                    }
                    break;
                case LocalEvents.EventsType.FILE_ACTION_RENAMED:
                    {
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "case FILE_ACTION_RENAMED");
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetContentURI for " + lEvent.FileName);

                        string strContentURi = GetContentURI(lEvent.FileName);
                        if (strContentURi.Trim().Length == 0)
                        {
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "GetContentURI for length ZERO");
                            return 1;
                        }

                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "MarkParentsStatus DB_STATUS_IN_PROGRESS for " + lEvent.FullPath);
                        MarkParentsStatus(lEvent.FullPath, DB_STATUS_IN_PROGRESS);

                        string changedName = lEvent.FileName.Substring((lEvent.FileName.LastIndexOf("\\") + 1));
                        LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "changedName " + changedName);

                        if (isFile)
                        {
                            bRetConflicts = CheckForConflicts(lEvent, strContentURi);
                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "isFile bRetConflicts " + bRetConflicts.ToString());
                        }
                        if (strContentURi.Substring(strContentURi.Length - 9).Equals("/contents") ||
                            strContentURi.Substring(strContentURi.Length - 8).Equals("/content"))
                        {
                            strContentURi = strContentURi.Substring(0, strContentURi.LastIndexOf("/"));
                        }

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            bRet = cMezeoFileCloud.ContainerRename(strContentURi, changedName, ref nStatusCode);
                            //dbHandler.UpdateRenamedOrMovedKey(lEvent.FileName, lEvent.OldFileName);

                            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Directory bRet " + bRet.ToString());
                            if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                            {
                                return LOGIN_FAILED;
                            }
                            else if (nStatusCode != ResponseCode.CONTAINERRENAME)
                            {
                                if (ResponseCode.NOTFOUND == nStatusCode)
                                    return ITEM_NOT_FOUND;
                                return SERVER_INACCESSIBLE;
                            }
                            else
                            {
                                wasSuccessful = true;
                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "MarkParentsStatus DB_STATUS_SUCCESS for  " + lEvent.FullPath);
                                MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Calling for UpdateDBForRenameSuccess");
                                UpdateDBForRenameSuccess(lEvent);
                                dbHandler.DeleteEvent(lEvent.EventDbId);
                            }
                        }
                        else
                        {
                            if (bRetConflicts)
                            {
                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "isFile bRetConflicts " + bRetConflicts.ToString());
                                ItemDetails iDetails = cMezeoFileCloud.GetContinerResult(strContentURi, ref nStatusCode);

                                if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                                {
                                    return LOGIN_FAILED;
                                }
                                else if (nStatusCode != ResponseCode.GETCONTINERRESULT)
                                {
                                    if (ResponseCode.NOTFOUND == nStatusCode)
                                        return ITEM_NOT_FOUND;
                                    return SERVER_INACCESSIBLE;
                                }

                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "updating DB   DbHandler.PUBLIC to " + iDetails.bPublic + " for DbHandler.KEY " + lEvent.FileName);

                                dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.PUBLIC, iDetails.bPublic, DbHandler.KEY, lEvent.FileName);
                                //bool bPublic = dbHandler.GetBoolean(DbHandler.TABLE_NAME, DbHandler.PUBLIC, DbHandler.KEY + " = '" + lEvent.FileName + "'");

                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "getting mime type from DB");
                                string mimeType = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.MIMIE_TYPE, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "mime type " + mimeType);

                                LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Calling cMezeoFileCloud.FileRename for content uri " + strContentURi + " with new name " + changedName);

                                if (!checkFileTooLarge(lEvent.FullPath))
                                    bRet = cMezeoFileCloud.FileRename(strContentURi, changedName, mimeType, iDetails.bPublic, ref nStatusCode);
                                else
                                    nStatusCode = 200;

                                if (nStatusCode == ResponseCode.LOGINFAILED1 || nStatusCode == ResponseCode.LOGINFAILED2)
                                {
                                    return LOGIN_FAILED;
                                }
                                else if (nStatusCode != ResponseCode.FILERENAME)
                                {
                                    if (ResponseCode.NOTFOUND == nStatusCode)
                                        return ITEM_NOT_FOUND;
                                    return SERVER_INACCESSIBLE;
                                }
                                else
                                {
                                    wasSuccessful = true;
                                    LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "MarkParentsStatus " + lEvent.FullPath + " to DB_STATUS_SUCCESS");
                                    MarkParentsStatus(lEvent.FullPath, DB_STATUS_SUCCESS);
                                    LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Calling UpdateDBForRenameSuccess");
                                    UpdateDBForRenameSuccess(lEvent);
                                    dbHandler.DeleteEvent(lEvent.EventDbId);
                                }
                            }
                        }
                    }
                    break;
            }

            int returnCode = 0;
            if (wasSuccessful)
                returnCode = 1;

            LogWrapper.LogMessage("SyncManager - ProcessLocalEvent", "Leave");

            return returnCode;
        }
        private void ReportConflict(LocalEvents lEvent, IssueFound.ConflictType cType)
        {
            //LogWrapper.LogMessage("SyncManager - ReportConflict", "Enter");
            FileInfo fInfo = new FileInfo(lEvent.FullPath);

            IssueFound iFound = new IssueFound();

            iFound.LocalFilePath = lEvent.FullPath;
            iFound.LocalIssueDT = fInfo.LastWriteTime;
            iFound.LocalSize = FormatSizeString(fInfo.Length);
            iFound.ConflictTimeStamp = DateTime.Now;
            iFound.cType = cType;

            string Description = "";
            switch (cType)
            {
                case IssueFound.ConflictType.CONFLICT_MODIFIED:
                    {
                        iFound.IssueTitle = LanguageTranslator.GetValue("ConflictDetectedModified");

                        Description += LanguageTranslator.GetValue("ErrorBlurbConflict1");
                        Description += LanguageTranslator.GetValue("ErrorBlurbConflict2") + "\n";
                        Description += LanguageTranslator.GetValue("ErrorBlurbConflict3") + "\n";
                        Description += LanguageTranslator.GetValue("ErrorBlurbConflict4");
                        Description += LanguageTranslator.GetValue("ErrorBlurbConflict5");

                        iFound.IssueDescripation = Description;
                    }
                    break;
                case IssueFound.ConflictType.CONFLICT_UPLOAD:
                    {
                        iFound.IssueTitle = LanguageTranslator.GetValue("ConflictDetectedError");

                        Description += LanguageTranslator.GetValue("ErrorBlurbUpload1");
                        Description += LanguageTranslator.GetValue("ErrorBlurbUpload2");
                        Description += LanguageTranslator.GetValue("ErrorBlurbUpload3");

                        iFound.IssueDescripation = Description;
                    }
                    break;
            }

            // cMezeoFileCloud.AppEventViewer(AboutBox.AssemblyTitle, Description, 3);

            int nStatusCode = 0;
            string strContentURi = GetContentURI(lEvent.FileName);
            if (strContentURi.Substring(strContentURi.Length - 9).Equals("/contents") ||
               strContentURi.Substring(strContentURi.Length - 8).Equals("/content"))
            {
                strContentURi = strContentURi.Substring(0, strContentURi.LastIndexOf("/"));
            }

            ItemDetails iDetails = cMezeoFileCloud.GetContinerResult(strContentURi, ref nStatusCode);

            iFound.ServerSize = FormatSizeString(iDetails.dblSizeInBytes);
            iFound.ServerIssueDT = iDetails.dtModified;
            iFound.ServerFileInfo = lEvent.FileName;
            iFound.ServerFileUri = iDetails.szContentUrl;

               // frmIssuesFound.AddIssueToList(iFound);
            dbHandler.StoreConflict(iFound);
            // Issue Fix for Conflicts
            IssueFoundBalloonMessage();

            //LogWrapper.LogMessage("SyncManager - ReportConflict", "Leave");
        }
        public static void AddToQueue(string filesEntry)
        {
            string keyname = filesEntry.Substring(BasicInfo.SyncDirPath.Length + 1);

            string result = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.KEY, DbHandler.KEY + " = '" + keyname + "';");

            LocalEvents lEvent = new LocalEvents();
            lEvent.FileName = keyname;

            lEvent.FullPath = filesEntry;

            lEvent.OldFileName = "";
            lEvent.OldFullPath = "";
            lEvent.EventTimeStamp = DateTime.Now;

            if (result == null || result == "")
            {
                //create or add event
                lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;
            }
            else
            {
                lEvent.EventType = LocalEvents.EventsType.FILE_ACTION_MODIFIED;
            }

            Add(lEvent);
        }
        private void UpdateDBForAddedSuccess(string strContentUri, LocalEvents lEvent)
        {
            int nStatusCode = 0;
            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.CONTENT_URL , strContentUri , DbHandler.KEY , lEvent.FileName);

            string strEtag = cMezeoFileCloud.GetETag(strContentUri, ref nStatusCode);
            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG , strEtag , DbHandler.KEY , lEvent.FileName );

            UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);
        }
        /// <summary>
        /// Fill in the file and directory information for the given event.  Sets the IsDirectory and IsFile
        /// flags and the Attributes as well so that the information doesn't have to be looked up later.  This
        /// is especially useful if the object is being moved around or renamed.
        /// The function also makes sure the FullPath and FileName are in the long format rather than the older
        /// 8.3 name format so that all of the database keys and paths are in a single format.
        /// </summary>
        /// <param name="theEvent">is populated with all of the event information</param>
        public static void FillInFileInfo(ref LocalEvents theEvent)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(theEvent.FullPath);

                theEvent.Attributes = fileInfo.Attributes;

                // Make sure the path is the long style and not the 8.3.  Expanding zip files creates
                // old style 8.3 paths in events for files, but not always folders.
                theEvent.FullPath = fileInfo.DirectoryName + "\\" + fileInfo.Name;
                theEvent.FileName = theEvent.FullPath.Substring(BasicInfo.SyncDirPath.Length+1);

                LogWrapper.LogMessage("EventQueue - FillInFileInfo", "File " + theEvent.FullPath + " attributes are: " +
            fileInfo.Attributes.ToString());

                if (fileInfo.Exists)
                {
                    if (0 == (fileInfo.Attributes & FileAttributes.Directory))
                    {
                        theEvent.IsDirectory = false;
                        theEvent.IsFile = true;
                    }
                    else
                    {
                        theEvent.IsDirectory = true;
                        theEvent.IsFile = false;
                    }
                }
                else
                {
                    theEvent.IsDirectory = true;
                    theEvent.IsFile = false;
                }
            }
            catch (Exception ex)
            {
                LogWrapper.LogMessage("EventQueue - FillInFileInfo", "Caught exception: " + ex.Message);
            }
        }
        private void UpdateDBForModifiedSuccess(LocalEvents lEvent, string strContentURi)
        {
            int nStatusCode = 0;
            string strEtag = cMezeoFileCloud.GetETag(strContentURi, ref nStatusCode);
            dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, strEtag, DbHandler.KEY, lEvent.FileName);

            FileInfo fileInfo = new FileInfo(lEvent.FullPath);
            if (fileInfo.Exists)
                dbHandler.UpdateModifiedDate(fileInfo.LastWriteTime, lEvent.FileName);

            UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);
        }
        /// <summary>
        /// The callback for the timer when TIME_WITHOUT_EVENTS has passed.  The callback will then look
        /// through the eventListCandidates list looking for events older than TIME_WITHOUT_EVENTS and
        /// move them into the eventList list to be processed by CollateEvents().  Any events left in
        /// eventList after the CollateEvents() call are then persisted to the database to be processed
        /// at a later time by the sync thread.
        /// 
        /// If events were persisted to the job queue in the database, or other events exist there already,
        /// then the WatchCompletedEvent() delegate is called to notify it that events are waiting to be
        /// processed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            bool bNewEventExists = false;
            DateTime currTime = DateTime.Now;
            List<LocalEvents> eventsToRemove = new List<LocalEvents>();

            // Check the event candidate list and see which events should be moved.
            lock (thisLock)
            {
                bool copyEvent = true;
                // If the resource has not had an event in the last X timespan,
                // move it from the eventListCandidates to eventList.
                foreach (LocalEvents id in eventListCandidates)
                {
                    copyEvent = false;
                    TimeSpan diff = currTime - id.EventTimeStamp;
                    if (TIME_WITHOUT_EVENTS <= diff.TotalMilliseconds)
                    {
                        // If this is a file that's going to be uploaded, then make sure it isn't locked.
                        if (id.IsFile && ((id.EventType == LocalEvents.EventsType.FILE_ACTION_ADDED) || (id.EventType == LocalEvents.EventsType.FILE_ACTION_MODIFIED)))
                        {
                            if (!IsFileLocked(id.FullPath))
                                copyEvent = true;
                        }
                        else
                            copyEvent = true;

                        if (copyEvent)
                        {
                            LocalEvents lEvent = new LocalEvents();
                            lEvent = id;
                            lEvent.EventTimeStamp = id.EventTimeStamp;
                            eventList.Add(lEvent);
                            eventsToRemove.Add(id);
                            //dbHandler.AddEvent(lEvent);
                        }
                    }
                }

                // Each event that was moved to eventList must
                // be removed from eventListCandidates.
                foreach (LocalEvents id in eventsToRemove)
                {
                    eventListCandidates.Remove(id);
                }

                eventsToRemove.Clear();

                // Collate the events before finally releasing them to be acted on.
                CollateEvents();

                // If there is anything left after collating the events, then
                // move them from the list to the database.
                if (0 < eventList.Count())
                {
                    // Move the events to the database.
                    foreach (LocalEvents item in eventList)
                    {
                        bNewEventExists = true;
                        GetDbHandler().AddEvent(item);
                    }

                    // Empty the list.
                    eventList.Clear();
                }
            }

            // If something was added to the list, trigger the event.
            if (bNewEventExists)
            {
                if (WatchCompletedEvent != null)
                {
                    if (EventQueue.QueueNotEmpty())
                        WatchCompletedEvent();
                }
            }

            //start checkingDirectoryThread if it is not running
            if(checkingDirectoryThread == null || checkingDirectoryThread.IsAlive == false)
            {
                checkingDirectoryThread = new Thread(checkingDirectoryThread_DoWork);
                checkingDirectoryThread.Start();
            }
        }
        private void UpdateDBForRemoveSuccess(LocalEvents lEvent)
        {
            string strType = dbHandler.GetString(DbHandler.TABLE_NAME, DbHandler.TYPE, new string[] { DbHandler.KEY }, new string[] { lEvent.FileName }, new DbType[] { DbType.String });
            dbHandler.Delete(DbHandler.TABLE_NAME, DbHandler.KEY , lEvent.FileName);

            if (strType == "DIRECTORY")
            {
                UpdateDBForRemoveDir(lEvent.FileName);
            }
        }
 public void PopulateLocalEventFromReader(ref LocalEvents item, ref SQLiteDataReader sqlDataReader)
 {
     item.EventDbId = (Int64)sqlDataReader[EVENT_INDEX];
     item.FileName = (string)sqlDataReader[EVENT_LOCAL_FILE_NAME];
     item.OldFileName = (string)sqlDataReader[EVENT_LOCAL_OLD_FILE_NAME];
     item.FullPath = (string)sqlDataReader[EVENT_LOCAL_FULL_PATH];
     item.OldFullPath = (string)sqlDataReader[EVENT_LOCAL_OLD_FULL_PATH];
     item.IsDirectory = (bool)sqlDataReader[EVENT_LOCAL_IS_DIRECTORY];
     item.IsFile = (bool)sqlDataReader[EVENT_LOCAL_IS_FILE];
     item.EventTimeStamp.AddTicks((Int64)sqlDataReader[EVENT_LOCAL_TIMESTAMP]);
     Int64 test = (Int64)sqlDataReader[EVENT_LOCAL_FILE_ATTRIBUTES];
     item.Attributes = (System.IO.FileAttributes)test;
     switch ((string)sqlDataReader[EVENT_LOCAL_TYPE])
     {
         case "FILE_ACTION_ADDED":
             item.EventType = LocalEvents.EventsType.FILE_ACTION_ADDED;
             break;
         case "FILE_ACTION_MODIFIED":
             item.EventType = LocalEvents.EventsType.FILE_ACTION_MODIFIED;
             break;
         case "FILE_ACTION_REMOVED":
             item.EventType = LocalEvents.EventsType.FILE_ACTION_REMOVED;
             break;
         case "FILE_ACTION_RENAMED":
             item.EventType = LocalEvents.EventsType.FILE_ACTION_RENAMED;
             break;
         case "FILE_ACTION_MOVE":
             item.EventType = LocalEvents.EventsType.FILE_ACTION_MOVE;
             break;
     }
 }
        private void UpdateDBForRenameSuccess(LocalEvents lEvent)
        {
            UpdateDBForStatus(lEvent, DB_STATUS_SUCCESS);

            if (Directory.Exists(lEvent.FullPath))
            {
                DirectoryInfo rootDir = new DirectoryInfo(lEvent.FullPath);
                WalkDirectoryTree(rootDir, lEvent.OldFullPath);
            }
        }
        public int AddEvent(LocalEvents newEvent)
        {
            int result = -1;
            string query = "insert into " + EVENT_TABLE_NAME + " (" +
                            EVENT_ORIGIN + ", " +
                            EVENT_LOCAL_FILE_NAME + ", " +
                            EVENT_LOCAL_OLD_FILE_NAME + ", " +
                            EVENT_LOCAL_FULL_PATH + ", " +
                            EVENT_LOCAL_OLD_FULL_PATH + ", " +
                            EVENT_LOCAL_TYPE + ", " +
                            EVENT_LOCAL_TIMESTAMP + ", " +
                            EVENT_LOCAL_IS_DIRECTORY + ", " +
                            EVENT_LOCAL_IS_FILE + ", " +
                            EVENT_LOCAL_FILE_ATTRIBUTES + ") values ('L', '" +
                            EscapeString(newEvent.FileName) + "','" +
                            EscapeString(newEvent.OldFileName) + "','" +
                            EscapeString(newEvent.FullPath) + "','" +
                            EscapeString(newEvent.OldFullPath) + "','" +
                            newEvent.EventType + "','" +
                            newEvent.EventTimeStamp + "','" +
                            ((newEvent.IsDirectory) ? 1 : 0) + "','" +
                            ((newEvent.IsFile) ? 1 : 0) + "','" +
                            (long)newEvent.Attributes + "');";

            SQLiteConnection sqlConnection = OpenConnection();
            SQLiteCommand sqlCommand = new SQLiteCommand(query, sqlConnection);
            LogWrapper.LogMessage("DBHandler - AddEvent", "Running query: " + query);

            result = sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();

            // Increment the job count.
            if (0 < result)
                IncrementJobCount();

            // A result of 1 is success (# of rows affected and we should
            // only have 1), not the index of the newly created entry.
            return result;
        }
        private void AddInDBForAdded(LocalEvents lEvent)
        {
            FileFolderInfo fInfo = new FileFolderInfo();

            FileInfo fileInfo = new FileInfo(lEvent.FullPath);

            fInfo.Key = lEvent.FileName;
            fInfo.ContentUrl = "";
            fInfo.ParentUrl = GetParentURI(lEvent.FileName);
            fInfo.CreatedDate = fileInfo.CreationTime;
            fInfo.ModifiedDate = fileInfo.LastWriteTime;
            fInfo.MimeType = "";
            fInfo.IsPublic = false;
            fInfo.IsShared = false;
            fInfo.Status = DB_STATUS_IN_PROGRESS;

            fInfo.ETag = "";

            if (lEvent.FileName.LastIndexOf("\\") == -1)
            {
                fInfo.FileName = lEvent.FileName;
                fInfo.ParentDir = "";
            }
            else
            {
                fInfo.FileName = lEvent.FileName.Substring(lEvent.FileName.LastIndexOf("\\") + 1);
                fInfo.ParentDir = lEvent.FileName.Substring(0, lEvent.FileName.LastIndexOf("\\"));
                fInfo.ParentDir = fInfo.ParentDir.Substring(fInfo.ParentDir.LastIndexOf("\\") +1);
            }

            if ((fileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                fInfo.Type = "DIRECTORY";
                fInfo.FileSize = 0;
            }
            else
            {
                fInfo.Type = "FILE";
                fInfo.FileSize = fileInfo.Length;
            }

            dbHandler.Write(fInfo);
        }