public void PrepareStructure(LocalItemDetails lItemdDetails)
        {
            LogWrapper.LogMessage("StructureDownloader - PrepareStructure", "Enter");

            //lock (lockObject)
            //{
            //    queue.Enqueue(lItemdDetails);
            //    if (isRootContainer)
            //    {
            //        LogWrapper.LogMessage("StructureDownloader - PrepareStructure", "Pulse");
            //        Monitor.PulseAll(lockObject);
            //    }
            //}
            dbhandler.AddLocalItemDetailsEvent(lItemdDetails);

            LogWrapper.LogMessage("StructureDownloader - PrepareStructure", "Leave");
        }
        public void analyseItemDetails(ItemDetails itemDetail,string strPath)
        {
            LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Enter");
            int refCode = 0;
            ItemDetails[] contents = cFileCloud.DownloadItemDetails(itemDetail.szContentUrl, ref refCode, null);

            if (refCode == ResponseCode.LOGINFAILED1 || refCode == ResponseCode.LOGINFAILED2)
            {
                //lockObject.StopThread = true;
                CancelAndNotify(CancelReason.LOGIN_FAILED);
                return;
            }
            else if (refCode == -1)
            {
                // The socket timed out or something else occured.  Let the normal timer
                // handle the online/offline mode stuff and just return as if normal
                // processing occured.  Otherwise, the sync will never progress past
                // this point.
                return;
            }
            else if (refCode != ResponseCode.DOWNLOADITEMDETAILS)
            {
                //lockObject.StopThread = true;
                CancelAndNotify(CancelReason.SERVER_INACCESSIBLE);
                return;
            }

            if (contents == null)
            {
                LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Contents Null");
                return;
            }

            foreach (ItemDetails iDetail in contents)
            {
                LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Checking KEY in DB for content url: " + iDetail.szContentUrl + " with SUCCESS");

                string strCheck = dbhandler.GetString(DbHandler.TABLE_NAME, DbHandler.KEY, new string[] { DbHandler.CONTENT_URL, DbHandler.STATUS }, new string[] { iDetail.szContentUrl, "SUCCESS" }, new System.Data.DbType[] { System.Data.DbType.String, System.Data.DbType.String });
                if (strCheck.Trim().Length == 0)
                {
                    LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "KEY for content url: " + iDetail.szContentUrl + " with SUCCESS not found in DB");
                    LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Creating a new LocalItemDetails with Path: " + iDetail.strName);
                    LocalItemDetails lItem = new LocalItemDetails();
                    lItem.ItemDetails = iDetail;
                    lItem.Path += strPath;
                    lItem.Path += "\\" + iDetail.strName;
                    totalFileCount++;
                    LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "totalFileCount: " + totalFileCount + "\n Calling PrepareStructure with lItem");
                    PrepareStructure(lItem);
                    LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "returned from PrepareStructure");
                }
            }

            LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Contents total item count: " + contents[0].nTotalItem);
            if (contents[0].nTotalItem > 0)
            {
                for (int n = 0; n < contents[0].nTotalItem; n++)
                {
                    //if (lockObject.StopThread /*|| refCode != 200*/)
                    //{
                    //    LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Stop thread requested Calling CancelAndNotify");
                    //    CancelAndNotify(CancelReason.USER_CANCEL);
                    //    break;
                    //}

                    if (contents[n].szItemType == "DIRECTORY")
                    {
                        LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Calling analyseItemDetails for DIR: " + contents[n].strName);
                        analyseItemDetails(contents[n], strPath + "\\" + contents[n].strName);
                    }
                }
            }

            LogWrapper.LogMessage("StructureDownloader - analyseItemDetails", "Leave");
        }
        public LocalItemDetails GetLocalItemDetailsEvent()
        {
            string query = "SELECT * FROM " + EVENT_TABLE_NAME + " WHERE " + EVENT_ORIGIN + " = 'I' ORDER BY " + EVENT_INDEX + " LIMIT 1;";
            LogWrapper.LogMessage("DBHandler - GetLocalItemDetailsEvent", "Running query: " + query);
            LocalItemDetails item = null;

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

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

            return item;
        }
        public int AddLocalItemDetailsEvent(LocalItemDetails iEvent)
        {
            int result = -1;
            string query = "insert into " + EVENT_TABLE_NAME + " (" +
                            EVENT_ORIGIN + ", " +
                            EVENT_INITIAL_SIZE + ", " +
                            EVENT_INITIAL_PUBLIC + ", " +
                            EVENT_INITIAL_SHARED + ", " +
                            EVENT_INITIAL_TOTAL + ", " +
                            EVENT_NQ_TIME + ", " +
                            EVENT_LOCAL_TIMESTAMP + ", " +
                            EVENT_LOCAL_OLD_FILE_NAME + ", " +
                            EVENT_LOCAL_FILE_NAME + ", " +
                            EVENT_LOCAL_FULL_PATH + ", " +
                            EVENT_INITIAL_TYPE + ", " +
                            EVENT_LOCAL_OLD_FULL_PATH + ", " +
                            EVENT_NQ_PARENT_URI + ") values ('I', " +
                            (Int64)iEvent.ItemDetails.dblSizeInBytes + ",'" +
                            ((iEvent.ItemDetails.bPublic) ? 1 : 0) + "','" +
                            ((iEvent.ItemDetails.bShared) ? 1 : 0) + "'," +
                            iEvent.ItemDetails.nTotalItem + ",'" +
                            iEvent.ItemDetails.dtCreated.Ticks + "'," +
                            iEvent.ItemDetails.dtModified.Ticks + ",'" +
                            iEvent.ItemDetails.strETag + "','" +
                            EscapeString(iEvent.ItemDetails.strName) + "','" +
                            iEvent.ItemDetails.szContentUrl + "','" +
                            iEvent.ItemDetails.szItemType + "','" +
                            EscapeString(iEvent.Path) + "','" +
                            iEvent.ItemDetails.szParentUrl + "');";

            SQLiteConnection sqlConnection = OpenConnection();
            SQLiteCommand sqlCommand = new SQLiteCommand(query, sqlConnection);
            LogWrapper.LogMessage("DBHandler - AddLocalItemDetailsEvent", "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;
        }
        public void PopulateLocalItemDetailsEventFromReader(ref LocalItemDetails item, ref SQLiteDataReader sqlDataReader)
        {
            try
            {
                ItemDetails itemDetails = new ItemDetails();
                item.EventDbId = (Int64)sqlDataReader[EVENT_INDEX];
                itemDetails.dblSizeInBytes = (Int64)sqlDataReader[EVENT_INITIAL_SIZE];
                itemDetails.bPublic = (bool)sqlDataReader[EVENT_INITIAL_PUBLIC];
                itemDetails.bShared = (bool)sqlDataReader[EVENT_INITIAL_SHARED];
                itemDetails.nTotalItem = (int)((Int64)sqlDataReader[EVENT_INITIAL_TOTAL]);
                itemDetails.dtCreated.AddTicks(Int64.Parse((string)sqlDataReader[EVENT_NQ_TIME]));
                itemDetails.dtModified.AddTicks((Int64)sqlDataReader[EVENT_LOCAL_TIMESTAMP]);
                itemDetails.strETag = (string)sqlDataReader[EVENT_LOCAL_OLD_FILE_NAME];
                itemDetails.strName = (string)sqlDataReader[EVENT_LOCAL_FILE_NAME];
                itemDetails.szParentUrl = (string)sqlDataReader[EVENT_NQ_PARENT_URI];
                item.Path = (string)sqlDataReader[EVENT_LOCAL_OLD_FULL_PATH];
                itemDetails.szContentUrl = (string)sqlDataReader[EVENT_LOCAL_FULL_PATH];
                itemDetails.szItemType = (string)sqlDataReader[EVENT_INITIAL_TYPE];
                //public string szMimeType;       // Always set to null/emtpy.
                //public DateTime dtAccessed;     // Never set or used.
                //public int nCurrentPosition;    // Never set or used.

                // Due to the class, I have to assign all the details at once instead of individually.
                item.ItemDetails = itemDetails;
            }
            catch (Exception ex)
            {
                LogWrapper.LogMessage("DbHandler - PopulateLocalItemDetailsEventFromReader", "Caught exception: " + ex.Message);
                item = null;
            }
        }
        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 ConsumeLocalItemDetail(LocalItemDetails itemDetail)
        {
            int nResultStatus = 1;
            LogWrapper.LogMessage("frmSyncManager - consume", "Enter");
            ItemDetails id = itemDetail.ItemDetails;
            LogWrapper.LogMessage("frmSyncManager - consume", "creating file folder info for " + id.strName);

            using (FileFolderInfo fileFolderInfo = new FileFolderInfo())
            {
                fileFolderInfo.Key = itemDetail.Path;

                fileFolderInfo.IsPublic = id.bPublic;
                fileFolderInfo.IsShared = id.bShared;
                fileFolderInfo.ContentUrl = id.szContentUrl;
                fileFolderInfo.CreatedDate = id.dtCreated;
                fileFolderInfo.FileName = id.strName;
                fileFolderInfo.FileSize = id.dblSizeInBytes;
                fileFolderInfo.MimeType = id.szMimeType;
                fileFolderInfo.ModifiedDate = id.dtModified;
                fileFolderInfo.ParentUrl = id.szParentUrl;
                fileFolderInfo.Status = "INPROGRESS";
                fileFolderInfo.Type = id.szItemType;

                int lastSepIndex = itemDetail.Path.LastIndexOf("\\");
                string parentDirPath = "";

                if (lastSepIndex != -1)
                {
                    parentDirPath = itemDetail.Path.Substring(0, itemDetail.Path.LastIndexOf("\\"));
                    parentDirPath = parentDirPath.Substring(parentDirPath.LastIndexOf("\\") + 1);
                }
                //else
                //{
                //    parentDirPath = itemDetail.Path;
                //}

                fileFolderInfo.ParentDir = parentDirPath;

                if (fileFolderInfo.ETag == null)
                {
                    fileFolderInfo.ETag = "";
                }
                if (fileFolderInfo.MimeType == null)
                {
                    fileFolderInfo.MimeType = "";
                }

                LogWrapper.LogMessage("frmSyncManager - consume", "writing file folder info for " + id.strName + " in DB");
                //if (!dbHandler.Write(fileFolderInfo))
                //    return 1;
                dbHandler.Write(fileFolderInfo);

                string downloadObjectName = BasicInfo.SyncDirPath + "\\" + itemDetail.Path;

                LogWrapper.LogMessage("frmSyncManager - consume", "download object " + downloadObjectName);

                LogWrapper.LogMessage("frmSyncManager - consume", "setting parent folders status DB_STATUS_IN_PROGRESS, bRet FALSE");
                MarkParentsStatus(downloadObjectName, DB_STATUS_IN_PROGRESS);
                bool bRet = false;
                int refCode = 0;

                if (id.szItemType == "DIRECTORY")
                {
                    LogWrapper.LogMessage("frmSyncManager - consume", id.strName + " is DIRECTORY");
                    System.IO.Directory.CreateDirectory(downloadObjectName);

                    if (id.strETag.Trim().Length == 0)
                    {
                        LogWrapper.LogMessage("frmSyncManager - consume", "Getting eTag for " + id.strName);
                        id.strETag = cMezeoFileCloud.GetETag(id.szContentUrl, ref refCode);
                        if (refCode == ResponseCode.LOGINFAILED1 || refCode == ResponseCode.LOGINFAILED2)
                        {
                            lockObject.StopThread = true;
                            return ResponseCode.LOGINFAILED1;  // CancelReason.LOGINFAILED
                        }
                        else if (refCode != ResponseCode.GETETAG)
                        {
                            lockObject.StopThread = true;
                            if (ResponseCode.NOTFOUND == refCode)
                                return ResponseCode.NOTFOUND;
                            return ResponseCode.SERVER_INACCESSIBLE; // CancelReason.SERVER_INACCESSIBLE
                        }
                    }

                    LogWrapper.LogMessage("frmSyncManager - consume", "eTag for " + id.strName + ": " + id.strETag + ", bRet TRUE");
                    bRet = true;
                }
                else
                {
                    LogWrapper.LogMessage("frmSyncManager - consume", id.strName + " is NOT DIRECTORY");
                    bRet = cMezeoFileCloud.DownloadFile(id.szContentUrl + '/' + id.strName,
                                            downloadObjectName, id.dblSizeInBytes, ref refCode);

                    if (refCode == ResponseCode.LOGINFAILED1 || refCode == ResponseCode.LOGINFAILED2)
                    {
                        //lockObject.StopThread = true;
                        return ResponseCode.LOGINFAILED1; // CancelReason.LOGIN_FAILED
                    }
                    else if (refCode == ResponseCode.NOTFOUND)
                    {
                        //lockObject.StopThread = true;
                        return ResponseCode.NOTFOUND;
                    }
                    else if (refCode != ResponseCode.DOWNLOADFILE)
                    {
                        //lockObject.StopThread = true;
                        return ResponseCode.SERVER_INACCESSIBLE; // CancelReason.SERVER_INACCESSIBLE
                    }

                    LogWrapper.LogMessage("frmSyncManager - consume", "bRet for " + id.strName + " is " + bRet.ToString());
                    if (refCode == ResponseCode.INSUFFICIENT_STORAGE_AVAILABLE)
                    {
                        LogWrapper.LogMessage("frmSyncManager - consume", "INSUFFICIENT_STORAGE_AVAILABLE, calling CancelAndNotify with reason INSUFFICIENT_STORAGE");
                        return ResponseCode.INSUFFICIENT_STORAGE_AVAILABLE;
                    }

                    LogWrapper.LogMessage("frmSyncManager - consume", "Getting eTag for " + id.strName);
                    id.strETag = cMezeoFileCloud.GetETag(id.szContentUrl, ref refCode);

                    if (refCode == ResponseCode.LOGINFAILED1 || refCode == ResponseCode.LOGINFAILED2)
                    {
                        //lockObject.StopThread = true;
                        return ResponseCode.LOGINFAILED1; // CancelReason.LOGIN_FAILED
                    }
                    else if (refCode != ResponseCode.GETETAG)
                    {
                        //lockObject.StopThread = true;
                        if (refCode == ResponseCode.NOTFOUND)
                            return ResponseCode.NOTFOUND;
                        return ResponseCode.SERVER_INACCESSIBLE; // CancelReason.SERVER_INACCESSIBLE
                    }
                    LogWrapper.LogMessage("frmSyncManager - consume", "eTag for " + id.strName + ": " + id.strETag);
                }

                if (!bRet)
                {
                    LogWrapper.LogMessage("frmSyncManager - consume", "bRet FALSE, writing to cFileCloud.AppEventViewer");
                    string Description = "";
                    Description += LanguageTranslator.GetValue("ErrorBlurbDownload1");
                    Description += LanguageTranslator.GetValue("ErrorBlurbDownload2");
                    Description += LanguageTranslator.GetValue("ErrorBlurbDownload3");
                    // cFileCloud.AppEventViewer(AboutBox.AssemblyTitle, Description, 3);
                }
                else
                {
                    LogWrapper.LogMessage("frmSyncManager - consume", "setting parent folders status to DB_STATUS_SUCCESS for " + downloadObjectName);
                    MarkParentsStatus(downloadObjectName, DB_STATUS_SUCCESS);
                    //fileFolderInfo.ETag = id.strETag;
                    if (id.szItemType == "DIRECTORY")
                    {
                        LogWrapper.LogMessage("frmSyncManager - consume", "updating DB for folder " + downloadObjectName);
                        DirectoryInfo dInfo = new DirectoryInfo(downloadObjectName);
                        dbHandler.UpdateModifiedDate(dInfo.LastWriteTime, fileFolderInfo.Key);
                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, id.strETag, DbHandler.KEY, fileFolderInfo.Key);
                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.STATUS, "SUCCESS", DbHandler.KEY, fileFolderInfo.Key);
                    }
                    else
                    {
                        LogWrapper.LogMessage("frmSyncManager - consume", "updating DB for file " + downloadObjectName);
                        FileInfo fInfo = new FileInfo(downloadObjectName);
                        dbHandler.UpdateModifiedDate(fInfo.LastWriteTime, fileFolderInfo.Key);
                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.E_TAG, id.strETag, DbHandler.KEY, fileFolderInfo.Key);
                        dbHandler.Update(DbHandler.TABLE_NAME, DbHandler.STATUS, "SUCCESS", DbHandler.KEY, fileFolderInfo.Key);
                    }

                    //if (downloadEvent != null)
                    //{
                    //    LogWrapper.LogMessage("frmSyncManager - consume", "calling  downloadEvent with " + downloadObjectName);
                    //    downloadEvent(this, new FileDownloaderEvents(downloadObjectName, 0));
                    //}
                }
            }

            //if (IsAnalysisCompleted && queue.Count == 0)
            //{
            //    LogWrapper.LogMessage("FileDownloader - consume", "Analysis completed and queue lenth is ZERO");
            //    if (fileDownloadCompletedEvent != null)
            //    {
            //        LogWrapper.LogMessage("FileDownloader - consume", "calling fileDownloadCompletedEvent");
            //        done = true;
            //        fileDownloadCompletedEvent();
            //    }
            //}

            LogWrapper.LogMessage("frmSyncManager - consume", "Leave");
            return nResultStatus;
        }