private FieldReflector <TimeRegistrationModel> BuildHourTypeField(ExactOnlineConnector connector)
        {
            var reflector = new FieldReflector <TimeRegistrationModel>(nameof(TimeRegistrationModel.HourType));

            reflector.SetType(null);
            reflector.SetDefine((state, field) =>
            {
                var recentHourTypes = _cacheService.RetrieveForUser <TimeAndBillingRecentHourCostType[]>(key_hourTypes, _userId);

                if (recentHourTypes == null)
                {
                    TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();
                    recentHourTypes = timeConnector.GetRecentHourCostTypes(connector).ToArray();

                    _cacheService.CacheForUser(key_hourTypes, recentHourTypes, _userId);
                }

                foreach (var recentHourType in recentHourTypes)
                {
                    field
                    .AddDescription(recentHourType.ItemId.ToString(), recentHourType.ItemDescription)
                    .AddTerms(recentHourType.ItemId.ToString(), recentHourType.ItemDescription);
                }

                return(Task.FromResult(true));
            });

            return(reflector);
        }
        private FieldReflector <TimeRegistrationModel> BuildCustomerField(ExactOnlineConnector connector)
        {
            var reflector = new FieldReflector <TimeRegistrationModel>(nameof(TimeRegistrationModel.Customer));

            reflector.SetType(null);
            reflector.SetDefine((state, field) =>
            {
                var recentAccounts = _cacheService.RetrieveForUser <TimeAndBillingRecentAccount[]>(key_customers, _userId);

                if (recentAccounts == null)
                {
                    TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();
                    recentAccounts = timeConnector.GetRecentAccounts(connector).ToArray();

                    _cacheService.CacheForUser(key_customers, recentAccounts, _userId);
                }

                foreach (var recentAccount in recentAccounts)
                {
                    field
                    .AddDescription(recentAccount.AccountId.ToString(), recentAccount.AccountName)
                    .AddTerms(recentAccount.AccountId.ToString(), recentAccount.AccountName);
                }

                return(Task.FromResult(true));
            });

            return(reflector);
        }
        public async Task MissingHours(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            if (await VerifyExactOnlineAuthorization(context, activity, ""))
            {
                DateTime startDate;
                DateTime endDate;
                string   weekString;

                var message = await activity;
                if (message.Text.ToLower().Contains("last week"))
                {
                    weekString = "last week";
                    DateTimeUtils.GetThisWeek(DateTime.Now.AddDays(-7), out startDate, out endDate);
                }
                else
                {
                    weekString = "this week";
                    DateTimeUtils.GetThisWeek(DateTime.Now, out startDate, out endDate);
                }

                await context.PostAsync($"Just a minute, going to check your hours for {weekString}...");

                ExactOnlineConnector      eolConnector = ExactOnlineHelper.GetConnector();
                TimeRegistrationConnector connector    = new TimeRegistrationConnector();

                double bookedHours = await connector.GetBookedHours(eolConnector.EmployeeId, startDate, endDate, eolConnector);

                await context.PostAsync($"For {weekString} I found {bookedHours} hours booked.");

                context.Wait(MessageReceived);
            }
        }
Esempio n. 4
0
        //*****************************************************************


        //*****************************************************************
        //*** Exact Online Files Grid Functions
        //*****************************************************************
        /// <summary>
        //*** Bind ExactOnline Data Grid
        /// </summary>
        /// <param name="ParentFolderGUID">Parent Folder GUID</param>
        /// <returns></returns>
        private void ExactOnlineGridDataBind(string ParentFolderGUID = "")
        {
            //*** Bind the Grid & Bread Crumb
            //**** Construct Exact Online Class
            ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

            if (Application["ExactOnlineAccessToken"] != null)
            {
                objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
            }

            //*** Get documents & Folders List
            List <ExactOnlineFile> lstExactOnlineFile = objExactOnlineConnector.ListDocumentsFolders(ParentFolderGUID);

            if (objExactOnlineConnector.MsgError != "")
            {   //*** If Error returned
                lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                //*** Show Error
                divExactOnlineAlert.Visible = true;

                return;
            }
            else
            {
                //**** Create Folder for test
                grdVWExactOnlineFilesFolderList.DataSource = lstExactOnlineFile;
                grdVWExactOnlineFilesFolderList.DataBind();
                divExactOnlineFileGrid.Visible = true;
                if (DivDropBoxFileGrid.Visible)
                {
                    divSync.Visible = true;
                }
            }
        }
        private async Task <TimeRegistrationModel> TimeRegistrationCompleted(IBotContext context, TimeRegistrationModel model)
        {
            var message = "Booking your hours in Exact, just a sec...";
            await context.PostAsync(message);

            ExactOnlineConnector connector = ExactOnlineHelper.GetConnector();

            TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();

            Guid projectId  = String.IsNullOrEmpty(model.Project) || model.Project == "none" ? Guid.Empty : new Guid(model.Project);
            Guid customerId = String.IsNullOrEmpty(model.Customer) ? Guid.Empty : new Guid(model.Customer);
            Guid hourTypeId = String.IsNullOrEmpty(model.HourType) ? Guid.Empty : new Guid(model.HourType);

            try
            {
                // the user will have booked time for either this week or for a specific date
                if (!model.ThisWeek)
                {
                    timeConnector.BookHours(connector.EmployeeId, customerId, hourTypeId, projectId, model.Date, model.Amount, connector);
                }
                else
                {
                    // if the hours were booked for the entire will, there will be 5 numbers in the string that need to be split
                    // out and entered for each day of the week individually
                    int      dayOfWeek  = DateTimeUtils.GetISODayOfWeek(DateTime.Now);
                    DateTime currentDay = DateTime.Now.AddDays((dayOfWeek - 1) * -1);

                    string[] hours = model.AmountPerDay.Trim().Split(' ');

                    for (int i = 0; i < 5; i++)
                    {
                        double amount = Double.Parse(hours[i]);

                        if (amount > 0)
                        {
                            timeConnector.BookHours(connector.EmployeeId, customerId, hourTypeId, projectId, currentDay, amount, connector);
                        }

                        currentDay = currentDay.AddDays(1);
                    }
                }
            }
            catch (RequestFailedException ex)
            {
                await context.PostAsync($"Hmm, that didn't work. The request failed, it returned the following:");

                await context.PostAsync($"\"{ ex.Message}\"");

                await context.PostAsync($"Sorry about that. Please try again or notify my maker.");

                return(null);
            }

            await context.PostAsync("All set! Anything else I can do for you?");

            return(model);
        }
        public IForm <TimeRegistrationModel> BuildForm()
        {
            ExactOnlineConnector connector = ExactOnlineHelper.GetConnector();

            var byDate       = new ActiveDelegate <TimeRegistrationModel>((state) => { return(state.ThisWeek == false); });
            var askPerDay    = new ActiveDelegate <TimeRegistrationModel>((state) => { return(state.ThisWeek == true); });
            var verifyPerDay = new ValidateAsyncDelegate <TimeRegistrationModel>(ValidateHoursPerDay);

            return(new FormBuilder <TimeRegistrationModel>()
                   .Field(nameof(TimeRegistrationModel.ThisWeek))
                   .Field(BuildCustomerField(connector))
                   .Field(BuildProjectField(connector))
                   .Field(BuildHourTypeField(connector))
                   .Field(nameof(TimeRegistrationModel.Date), byDate)
                   .Field(nameof(TimeRegistrationModel.Amount), byDate)
                   .Field(nameof(TimeRegistrationModel.AmountPerDay), askPerDay, ValidateHoursPerDay)
                   .OnCompletion(TimeRegistrationCompleted)
                   .Build());
        }
        public async Task SubmitHours(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            if (await VerifyExactOnlineAuthorization(context, activity, ""))
            {
                await context.PostAsync($"Let me check whether you're all set...");

                ExactOnlineConnector      eolConnector = ExactOnlineHelper.GetConnector();
                TimeRegistrationConnector connector    = new TimeRegistrationConnector();

                DateTime startDate, endDate;
                DateTimeUtils.GetThisWeek(DateTime.Now, out startDate, out endDate);

                double bookedHours = await connector.GetBookedHours(eolConnector.EmployeeId, startDate, endDate, eolConnector);

                ConfirmDialog.Text = $"You've registered a total number of {0} hours for this week. Do you want me to submit those?";
                var confirmationDialog = new FormDialog <ConfirmModel>(new ConfirmModel(), ConfirmDialog.BuildForm, FormOptions.PromptInStart);
                context.Call(confirmationDialog, this.ResumeAfterSubmitHoursDialog);
            }
        }
Esempio n. 8
0
        private async Task <double?> GetBookedHours(AuthenticationResult authenticationResult)
        {
            try
            {
                ExactOnlineConnector connector = new ExactOnlineConnector(authenticationResult.AccessToken);

                DateTime startDate, endDate;
                DateTimeUtils.GetThisWeek(DateTime.Now, out startDate, out endDate);

                TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();
                double bookedHours = await timeConnector.GetBookedHours(connector.EmployeeId, startDate, endDate, connector);

                return(bookedHours);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        private FieldReflector <TimeRegistrationModel> BuildProjectField(ExactOnlineConnector connector)
        {
            var reflector = new FieldReflector <TimeRegistrationModel>(nameof(TimeRegistrationModel.Project));

            reflector.SetType(null);
            reflector.SetDefine((state, field) =>
            {
                Guid?customerId = !String.IsNullOrEmpty(state.Customer) ? Guid.Parse(state.Customer) : (Guid?)null;

                if (customerId != null)
                {
                    string key         = key_hours + customerId.ToString();
                    var recentProjects = _cacheService.RetrieveForUser <RecentHours[]>(key, _userId);

                    if (recentProjects == null)
                    {
                        TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();
                        recentProjects = timeConnector.GetRecentProjects(connector, customerId).ToArray();

                        _cacheService.CacheForUser(key, recentProjects, _userId);
                    }

                    foreach (var recentProject in recentProjects)
                    {
                        field
                        .AddDescription(recentProject.ProjectId.ToString(), recentProject.ProjectDescription)
                        .AddTerms(recentProject.ProjectId.ToString(), recentProject.ProjectDescription);
                    }

                    // if there's only one option to select; select it!
                    if (recentProjects.Length == 1)
                    {
                        state.Project = recentProjects.First().ProjectId.ToString();
                        return(Task.FromResult(false));
                    }
                }

                return(Task.FromResult(true));
            });

            return(reflector);
        }
Esempio n. 10
0
        public static ExactOnlineConnector GetConnector()
        {
            var tokenCache = TokenCacheFactory.GetTokenCache();

            if (tokenCache == null)
            {
                throw new ArgumentException("Cannot create Connector instance when the tokencache is null.");
            }

            OAuthToken token = tokenCache.GetToken();

            if (token == null || String.IsNullOrEmpty(token.UserUniqueId))
            {
                throw new ArgumentException("Cannot create Connector instance when there's no cached token or the unique user id is empty. Set a cached token.");
            }

            ExactOnlineConnector connector = new ExactOnlineConnector(token.AccessToken);

            return(connector);
        }
        private async Task ResumeAfterSubmitHoursDialog(IDialogContext context, IAwaitable <ConfirmModel> result)
        {
            ConfirmModel message = await result;

            if (message.Confirmation)
            {
                DateTime startDate, endDate;
                DateTimeUtils.GetThisWeek(DateTime.Now, out startDate, out endDate);

                ExactOnlineConnector      eolConnector  = ExactOnlineHelper.GetConnector();
                TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();
                timeConnector.SubmitHours(eolConnector.EmployeeId, startDate, endDate, eolConnector);

                await context.PostAsync($"Thanks, I've closed your timesheet for this week. Have a nice weekend!");
            }
            else
            {
                await context.PostAsync($"Ok. Just give me a nudge when you're ready.");
            }

            context.Wait(MessageReceived);
        }
Esempio n. 12
0
        public async System.Threading.Tasks.Task <ActionResult> Index()

        {
            //*** Check Lock Variable First
            if (!(Boolean)HttpContext.Application["SyncInProgress"])
            {
                HttpContext.Application["SyncInProgress"] = true; //*** Set Lock Flag

                ViewBag.Title = "Sync Dropbox Files";

                //*** Initialization
                Session["lblDropBoxMsg"]      = "";
                Session["btnDropBoxbtnV"]     = "hidden";
                Session["btnExactOnlinebtnV"] = "hidden";
                Session["SyncAllNumbers"]     = "";
                Session["ResultNumbers"]      = "";

                strSiteBaseURL = Request.Url.Scheme + "://" + Request.Url.Host;
                if (Request.Url.Port > 0)
                {
                    strSiteBaseURL += ":" + Request.Url.Port.ToString();
                }
                ;

                //*** Adjust Drop Box Call Back URL for
                if (Session["dropBoxReturnBackURL"] == null)
                {
                    Session["dropBoxReturnBackURL"]  = strSiteBaseURL;
                    Session["dropBoxReturnBackURL"] += "/" + System.Configuration.ConfigurationManager.AppSettings["dropBoxAuthReturnPage"];
                }
                //******************************************************

                //*********************************************
                //*** Query on Files last Modified
                //*********************************************
                DateTime             dtLastModifiedDate      = new DateTime(2000, 1, 1);
                CloudStorageEntities objCloudStorageEntities = new CloudStorageEntities();

                //*** Check First if File Already exisit into DB
                DropboxWebhook objRecord = objCloudStorageEntities.DropboxWebhooks.Where(i => i.DW_Processed == 0).FirstOrDefault();
                if (objRecord != null)
                {
                    dtLastModifiedDate = Convert.ToDateTime(objRecord.DW_TimeStamp);
                }

                if (dtLastModifiedDate > Convert.ToDateTime("1/1/2000"))
                {
                    //******************************************************************************************************
                    //*** Dropbox Part
                    //******************************************************************************************************
                    //*** Check dropBox Aurhentication Token
                    if (Session["dropBoxAccessToken"] == null)
                    {
                        //***************************
                        //*** access token is empty
                        //***************************
                        //*** 1. Check first for dropBox App Key & App secret
                        if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["dropBoxAppKey"]) ||
                            String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["dropBoxAppSecret"]))
                        {
                            //*** Show Error Message
                            Session["lblDropBoxMsg"] = "Please set app key and secret in this project's Web.config file and restart. " +
                                                       "App key/secret can be found in the Dropbox App Console, here: " +
                                                       "https://www.dropbox.com/developers/apps";
                            goto lnIndexEnd;
                        }
                        else   //*** AppKey & secret exist
                        {
                            //*** Show Connect to DropBox button
                            Session["btnDropBoxbtnV"] = "visible";
                        }
                    }
                    else
                    {
                        //*** Get DropBox Client Object
                        Session["dropBoxClientObj"] = DropBoxConnector.getDropboxClient(Session["dropBoxAccessToken"].ToString());

                        if (DropBoxConnector.MsgError != "")    //*** If error
                        {
                            Session["lblDropBoxMsg"] = "Dropbox Error: " + DropBoxConnector.MsgError;
                        }
                        else
                        {
                            //******************************************************************************************************
                            //*** Exact Online Part
                            //******************************************************************************************************
                            //*** Adjust Drop Box Call Back URL for
                            if (Session["exactOnlineReturnBackURL"] == null)
                            {
                                Session["exactOnlineReturnBackURL"] = Request.Url.Scheme + "://" + Request.Url.Host;
                                if (Request.Url.Port > 0)
                                {
                                    Session["exactOnlineReturnBackURL"] += ":" + Request.Url.Port.ToString();
                                }
                                ;
                                Session["exactOnlineReturnBackURL"] += "/" + System.Configuration.ConfigurationManager.AppSettings["exactOnlineReturnPage"];
                            }

                            //*** Check If Code returned into Connection String
                            if (Session["ExactOnlineAccessToken"] == null && Session["ExactOnlineReturnCode"] != null)
                            {
                                //**** Initialize Session Folder Path
                                List <string> Dump = new List <string> {
                                };
                                Session["ExactOnlineFolderPath"] = Dump;

                                //**** Construct Exact Online Class
                                ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                                Session["ExactOnlineAccessToken"] = objExactOnlineConnector.GetAccessToken();

                                if (objExactOnlineConnector.MsgError != "")
                                {   //*** If Error returned
                                    Session["lblDropBoxMsg"] = "Exact Online Error: " + objExactOnlineConnector.MsgError;

                                    goto lnIndexEnd;
                                }
                            }

                            //*** Check ExactOnline Aurhentication Token
                            if (Session["ExactOnlineAccessToken"] == null && Session["ExactOnlineReturnCode"] == null)
                            {
                                //***************************
                                //*** access token is empty
                                //***************************
                                //*** 1. Check first for ExactOnline App Key & App secret
                                if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"]) ||
                                    String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"]) ||
                                    String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"]))
                                {
                                    //*** Show Error Message
                                    Session["lblDropBoxMsg"] = "Please set client id, client secret and end point URL into this project's Web.config file and restart. " +
                                                               "client id/secret can be found in the ExactOnline App Console, here: " +
                                                               "https://start.exactonline.co.uk";

                                    goto lnIndexEnd;
                                }
                                else   //*** AppKey & secret exist
                                {
                                    //*** Show Connect to ExactOnline button
                                    Session["btnExactOnlinebtnV"] = "visible";
                                }
                            }

                            if (Session["ExactOnlineReturnCode"] != null)
                            {
                                //*** 1. List all Dropbox Files
                                await getDropBoxFilesList((List <string>) Session["FolderPath"]);

                                //*** 2. Call Sync Function which Sync all Modified files with Exact Online Store
                                await SyncAllFilesFolders((List <DropBoxFile>) Session["lstDropBoxFile"]);

                                if (objRecord != null)
                                {
                                    //*** Update Flag of WebHook Table
                                    objRecord.DW_Processed        = 1;
                                    objRecord.DW_ProcessTimeStamp = DateTime.Now;
                                    objCloudStorageEntities.SaveChanges();
                                }
                            }
                        }
                    }
                }

lnIndexEnd:
                //*** GC
                objCloudStorageEntities.Dispose();
            }

            HttpContext.Application["SyncInProgress"] = false; //*** Release Lock Flag

            //*** Display Results
            if (Session["SyncAllNumbers"].ToString() != "")
            {
                string[] strAllResultNumbers = Session["SyncAllNumbers"].ToString().Split(',');

                Session["ResultNumbers"] = "Dropbox Files= " + strAllResultNumbers[0] + " ,Files Processed= " + strAllResultNumbers[1] + " ,Files Replaced Successfully= " + strAllResultNumbers[2] + " ,Failure= " + strAllResultNumbers[3];
            }

            try
            {
                return(View());
            }
            finally
            {
            }
        }
Esempio n. 13
0
        private async Task SyncAllFilesFolders()
        {
            try
            {
                //*** Set Variables
                int intCount = 0, intSuccess = 0, intFailed = 0;
                Session["SyncAllNumbers"] = "";
                string strFolderGUID = "";
                string strFolderpath = "";

                //*** Loop on All Objects on DropBox Grid View
                foreach (GridViewRow itemRow in grdVWDropBoxFilesFolderList.Rows)
                {
                    strFolderpath = "";

                    //*** Refresh Counts
                    intCount += 1;

                    //*** set Session Variable (Shared Variable)
                    Session["SyncAllNumbers"] = grdVWDropBoxFilesFolderList.Rows.Count.ToString() + "," + intCount.ToString() + "," + intSuccess.ToString() + "," + intFailed.ToString();

                    //*** Check on Drop Box Enity
                    if (bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text))   //**** If Folder
                    {
                        //************************************
                        //**** Create Folder on ExactOnline
                        //************************************
                        //**** Construct Exact Online Class
                        ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                        if (Application["ExactOnlineAccessToken"] != null)
                        {
                            objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                        }

                        strFolderGUID = objExactOnlineConnector.CreateDocumentFolder(((Label)itemRow.FindControl("lblFileName")).Text, Session["CurrentExactFolderGUID"].ToString());
                        if (strFolderGUID == "")
                        {
                            //*** If Error returned
                            intFailed += 1;
                        }
                        else
                        {
                            intSuccess += 1;
                        }
                    }
                    else  //**** If File
                    {
                        //******************************************************************
                        //**** Get File Stream then upload it to ExactOnline & Flush
                        //******************************************************************
                        //*** Construct Parent Folder Path String
                        string strParentFolderpath = "";
                        if ((List <string>)Session["FolderPath"] != null)
                        {
                            foreach (var item in (List <string>)Session["FolderPath"])
                            {
                                strParentFolderpath += "/" + item;
                            }
                        }

                        string strPath = strParentFolderpath + "/" + ((Label)itemRow.FindControl("lblFileName")).Text;
                        strFolderpath = strPath;

                        //*** Create Folder Function
                        Stream fnStreamResult = await DropBoxConnector.Download(Application["dropBoxClientObj"], strPath);

                        if (DropBoxConnector.MsgError != "")    //*** If error
                        {
                            intFailed += 1;
                        }
                        else
                        {
                            //*************************************************************
                            //*** Convert File to Byte Array and upload it to Exact Online
                            //*************************************************************
                            //**** Construct Exact Online Class
                            ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                            if (Application["ExactOnlineAccessToken"] != null)
                            {
                                objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                            }

                            strFolderGUID = objExactOnlineConnector.CreateDocumentWithAttachment(((Label)itemRow.FindControl("lblFileName")).Text, Session["CurrentExactFolderGUID"].ToString(), Common.ConvertStreamtoByteArr(fnStreamResult));
                            if (strFolderGUID == "")
                            {
                                intFailed += 1;
                            }
                            else
                            {
                                intSuccess += 1;
                            }
                        }
                        //******************************************************************
                    }

                    //*** The Add to update record into DB
                    if (bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text))    //*** If Folder
                    {
                        if ((List <string>)Session["FolderPath"] != null)
                        {
                            foreach (var item in (List <string>)Session["FolderPath"])
                            {
                                strFolderpath += "/" + item;
                            }
                        }
                        strFolderpath += "/" + ((Label)itemRow.FindControl("lblFileName")).Text;
                    }

                    FilesDocumentsEntities objFilesDocumentsEntities = new FilesDocumentsEntities();

                    //*** Check First if File Already exisit into DB
                    DropBoxExactOnline objRecord = objFilesDocumentsEntities.DropBoxExactOnlines.Where(i => i.DropBoxPath == strFolderpath).FirstOrDefault();
                    if (objRecord != null)
                    {
                        //**** Update DB
                        objRecord.DropBoxPath     = strFolderpath;
                        objRecord.ExactOnlineGUID = strFolderGUID;
                        if (bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text))
                        {
                            objRecord.isFile = 0;
                        }
                        else
                        {
                            objRecord.isFile = 1;
                        }

                        objFilesDocumentsEntities.SaveChanges();
                    }
                    else
                    {
                        //*** add to DB
                        DropBoxExactOnline objRecordNew = new DropBoxExactOnline();
                        objRecordNew.DropBoxPath     = strFolderpath;
                        objRecordNew.ExactOnlineGUID = strFolderGUID;
                        if (bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text))
                        {
                            objRecordNew.isFile = 0;
                        }
                        else
                        {
                            objRecordNew.isFile = 1;
                        }

                        objFilesDocumentsEntities.DropBoxExactOnlines.Add(objRecordNew);
                        objFilesDocumentsEntities.SaveChanges();
                    }
                    //*******************************************************************************

                    //*** set Session Variable (Shared Variable)
                    Session["SyncAllNumbers"] = grdVWDropBoxFilesFolderList.Rows.Count.ToString() + "," + intCount.ToString() + "," + intSuccess.ToString() + "," + intFailed.ToString();
                }

                //*** Rebind Exact Online Grid
                ExactOnlineGridDataBind(Session["CurrentExactFolderGUID"].ToString());
            }
            catch (Exception e)
            {
                lblExactOnlineMsg.Text = e.ToString();

                //*** Show Error
                divExactOnlineAlert.Visible = true;
            }
        }
Esempio n. 14
0
        //*** Upload File Button
        protected async void Uploader1_UploadCompleted(object sender, UploaderEventArgs[] args)
        {
            //*** Construct Parent Folder + File Path String
            string strUploadedFilePath = "";
            string strFolderName       = "";
            string DocumentGUID        = "";

            if ((List <string>)Session["FolderPath"] != null)
            {
                foreach (var item in (List <string>)Session["FolderPath"])
                {
                    strUploadedFilePath += "/" + item;
                    strFolderName        = item;
                }
            }
            strUploadedFilePath += "/" + args[0].FileName;

            //*** Upload File to DropBox Function
            bool blnUploadResult = await DropBoxConnector.Upload(Application["dropBoxClientObj"], strUploadedFilePath, args[0].OpenStream());

            if (!blnUploadResult)    //*** If error
            {
                lblDropBoxMsg.Text = DropBoxConnector.MsgError;

                //*** Show Error
                divDropBoxAlert.Visible = true;

                //*** Exit from function
                return;
            }
            else   //**** Success
            {
                //****************************************************************
                //**** Exact Online Part
                //****************************************************************
                if (divExactOnlineFileGrid.Visible)     //**** If Exact Online Grid Shown
                {
                    //*** Create Folder on Exact Online also
                    //**** Construct Exact Online Class
                    ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                    if (Application["ExactOnlineAccessToken"] != null)
                    {
                        objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                    }

                    DocumentGUID = objExactOnlineConnector.CreateDocumentWithAttachment(args[0].FileName, Session["CurrentExactFolderGUID"].ToString(), Common.ConvertStreamtoByteArr(args[0].OpenStream()));
                    if (DocumentGUID == "")
                    {
                        //*** If Error returned
                        lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                        //*** Show Error
                        divExactOnlineAlert.Visible = true;
                    }
                    else
                    {
                        //*** Add Entity to DB
                        FilesDocumentsEntities objFilesDocumentsEntities = new FilesDocumentsEntities();

                        //*** Check First if File Already exisit into DB
                        DropBoxExactOnline objRecord = objFilesDocumentsEntities.DropBoxExactOnlines.Where(i => i.DropBoxPath == strUploadedFilePath).FirstOrDefault();
                        if (objRecord != null)
                        {
                            //**** Update DB
                            objRecord.DropBoxPath     = strUploadedFilePath;
                            objRecord.ExactOnlineGUID = DocumentGUID;
                            objRecord.isFile          = 1;

                            objFilesDocumentsEntities.SaveChanges();
                        }
                        else
                        {
                            //*** add to DB
                            DropBoxExactOnline objRecordNew = new DropBoxExactOnline();
                            objRecordNew.DropBoxPath     = strUploadedFilePath;
                            objRecordNew.ExactOnlineGUID = DocumentGUID;
                            objRecordNew.isFile          = 1;

                            objFilesDocumentsEntities.DropBoxExactOnlines.Add(objRecordNew);
                            objFilesDocumentsEntities.SaveChanges();
                        }
                    }
                }
                //***************************************************************************

                //*** Rebind Data Grid Again
                DropBoxGridDataBind(((List <string>)Session["FolderPath"]));
            }
        }
Esempio n. 15
0
        //*** Delete Button
        protected async void lnkbtnDelete_Click(object sender, ImageClickEventArgs e)
        {
            //*** Construct Parent Folder Path String
            string strParentFolderpath = "";
            string strFolderName       = "";
            bool   isFolder            = false;

            if ((List <string>)Session["FolderPath"] != null)
            {
                foreach (var item in (List <string>)Session["FolderPath"])
                {
                    strParentFolderpath += "/" + item;
                }
            }

            //*** Loop on Items to see who is checked to delete
            foreach (GridViewRow row in grdVWDropBoxFilesFolderList.Rows)
            {
                if (((CheckBox)row.FindControl("chkItem")).Checked)
                {
                    //*** Check if file or Folder
                    isFolder = bool.Parse(((Label)row.FindControl("lblisFolder")).Text);

                    string strPath = strParentFolderpath + "/" + ((Label)row.FindControl("lblFileName")).Text;
                    strFolderName = ((Label)row.FindControl("lblFileName")).Text;

                    //*** Create Folder Function
                    bool fnResult = await DropBoxConnector.DeleteFileOrFolder(Application["dropBoxClientObj"], strPath);

                    if (!fnResult)    //*** If error
                    {
                        lblDropBoxMsg.Text = DropBoxConnector.MsgError;

                        //*** Show Error
                        divDropBoxAlert.Visible = true;

                        //*** Exit loop function
                        break;
                    }

                    //****************************************************************
                    //**** Exact Online Part
                    //****************************************************************
                    string strFileFolderGUID = "";
                    if (divExactOnlineFileGrid.Visible)     //**** If Exact Online Grid Shown
                    {
                        //*** 1. Get Folder Guid (If not root)
                        if (strFolderName != "")
                        {
                            //*** Fitch Grid to get GUID
                            foreach (GridViewRow itemRow in grdVWExactOnlineFilesFolderList.Rows)
                            {
                                if (isFolder)   //**** If Folder
                                {
                                    //*** Check if name & Is Folcder
                                    if (bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text) && ((Label)itemRow.FindControl("lblFileName")).Text.ToLower() == strFolderName.ToLower())
                                    {
                                        strFileFolderGUID = ((Label)itemRow.FindControl("lblFolderID")).Text;
                                        break;
                                    }
                                }
                                else
                                {
                                    //*** Check if name & Is File
                                    if (!bool.Parse(((Label)itemRow.FindControl("lblisFolder")).Text) && ((Label)itemRow.FindControl("lblFileName")).Text.ToLower() == strFolderName.ToLower())
                                    {
                                        strFileFolderGUID = ((Label)itemRow.FindControl("lblFolderID")).Text;
                                        break;
                                    }
                                }
                            }
                        }

                        if (strFileFolderGUID != "")
                        {
                            //*** Create Folder on Exact Online also
                            //**** Construct Exact Online Class
                            ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                            if (Application["ExactOnlineAccessToken"] != null)
                            {
                                objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                            }

                            if (isFolder)        //*** This is Folder
                            {
                                //*** Call Delete Folder
                                if (!objExactOnlineConnector.DeleteDocumentFolder(strFileFolderGUID))
                                {
                                    //*** If Error returned
                                    lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                                    //*** Show Error
                                    divExactOnlineAlert.Visible = true;
                                }
                            }
                            else  //**** If File
                            {
                                //**** Call Delete Document
                                if (!objExactOnlineConnector.DeleteDocument(strFileFolderGUID))
                                {
                                    //*** If Error returned
                                    lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                                    //*** Show Error
                                    divExactOnlineAlert.Visible = true;
                                }
                            }
                        }
                    }
                    //***************************************************************************

                    //*** Then Delete Records from DB
                    FilesDocumentsEntities objFilesDocumentsEntities = new FilesDocumentsEntities();

                    //*** Check First if File Already exisit into DB
                    DropBoxExactOnline objRecord = objFilesDocumentsEntities.DropBoxExactOnlines.Where(i => i.DropBoxPath == strPath).FirstOrDefault();
                    if (objRecord != null)
                    {
                        objFilesDocumentsEntities.DropBoxExactOnlines.Remove(objRecord);
                        objFilesDocumentsEntities.SaveChanges();
                    }
                }
            }

            //*** Rebind Data Grid Again
            DropBoxGridDataBind(((List <string>)Session["FolderPath"]));
        }
Esempio n. 16
0
        //**** Create Folder Button
        protected async void btnPanel2Yes_Click(object sender, EventArgs e)
        {
            //*** Check First if Folder Exist/ Fitsh
            foreach (GridViewRow row in grdVWDropBoxFilesFolderList.Rows)
            {
                if (((Label)row.FindControl("lblFileName")).Text.ToLower() == txtFolderName.Text.ToLower() && bool.Parse(((Label)row.FindControl("lblisFolder")).Text.ToLower()))
                {
                    //*** Folder Already Exist
                    lblDropBoxMsg.Text = "Folder already exists with same name";

                    //*** Show Error with grid
                    divDropBoxAlert.Visible    = true;
                    DivDropBoxFileGrid.Visible = true;

                    //*** Exit from function
                    return;
                }
            }

            //*** Construct Parent Folder Path String
            string strFolderpath = "";
            string strFolderName = "";

            if ((List <string>)Session["FolderPath"] != null)
            {
                foreach (var item in (List <string>)Session["FolderPath"])
                {
                    strFolderpath += "/" + item;
                    strFolderName  = item;
                }
            }
            strFolderpath += "/" + txtFolderName.Text;

            //*** Create Folder Function
            bool fnResult = await DropBoxConnector.CreateFolder(Application["dropBoxClientObj"], strFolderpath);

            if (!fnResult)    //*** If error
            {
                lblDropBoxMsg.Text = DropBoxConnector.MsgError;

                //*** Show Error
                divDropBoxAlert.Visible = true;
            }
            else
            {
                //****************************************************************
                //**** Exact Online Part
                //****************************************************************
                if (divExactOnlineFileGrid.Visible)     //**** If Exact Online Grid Shown
                {
                    //*** Create Folder on Exact Online also
                    //**** Construct Exact Online Class
                    ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                    if (Application["ExactOnlineAccessToken"] != null)
                    {
                        objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                    }

                    string strFolderGUID = objExactOnlineConnector.CreateDocumentFolder(txtFolderName.Text, Session["CurrentExactFolderGUID"].ToString());
                    if (strFolderGUID == "")
                    {
                        //*** If Error returned
                        lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                        //*** Show Error
                        divExactOnlineAlert.Visible = true;
                    }
                    else  //*** Add Entry To DB
                    {
                        FilesDocumentsEntities objFilesDocumentsEntities = new FilesDocumentsEntities();

                        DropBoxExactOnline objRecord = new DropBoxExactOnline();
                        objRecord.DropBoxPath     = strFolderpath;
                        objRecord.ExactOnlineGUID = strFolderGUID;
                        objRecord.isFile          = 0;

                        objFilesDocumentsEntities.DropBoxExactOnlines.Add(objRecord);
                        objFilesDocumentsEntities.SaveChanges();
                    }
                }
                //***************************************************************************

                //*** Success & Rebind Data Grid Again & Initialize
                txtFolderName.Text = "";
                DropBoxGridDataBind(((List <string>)Session["FolderPath"]));
            }
        }
Esempio n. 17
0
        protected async void Page_Load(object sender, EventArgs e)
        {
            //*** First Time
            if (!Page.IsPostBack)
            {
                //*** Initialization
                divDropBoxAlert.Visible         = false;
                lnkbtnConnectDropBox.Visible    = false;
                lnkbtnDisconnectDropBox.Visible = false;
                DivDropBoxFileGrid.Visible      = false;
                pnlDownload.Visible             = false;

                strSiteBaseURL = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host;
                if (HttpContext.Current.Request.Url.Port > 0)
                {
                    strSiteBaseURL += ":" + HttpContext.Current.Request.Url.Port.ToString();
                }
                ;

                //*** Adjust Drop Box Call Back URL for
                if (HttpContext.Current.Session["dropBoxReturnBackURL"] == null)
                {
                    HttpContext.Current.Session["dropBoxReturnBackURL"]  = strSiteBaseURL;
                    HttpContext.Current.Session["dropBoxReturnBackURL"] += "/" + System.Configuration.ConfigurationManager.AppSettings["dropBoxAuthReturnPage"];
                }
                //******************************************************


                //*** Check dropBox Aurhentication Token
                if (Application["dropBoxAccessToken"] == null)
                {
                    //***************************
                    //*** access token is empty
                    //***************************
                    //*** 1. Check first for dropBox App Key & App secret
                    if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["dropBoxAppKey"]) ||
                        String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["dropBoxAppSecret"]))
                    {
                        //*** Show Error Message
                        lblDropBoxMsg.Text = "Please set app key and secret in this project's Web.config file and restart. " +
                                             "App key/secret can be found in the Dropbox App Console, here: " +
                                             "https://www.dropbox.com/developers/apps";

                        //*** Show Error
                        divDropBoxAlert.Visible = true;

                        return;
                    }
                    else   //*** AppKey & secret exist
                    {
                        //*** Show Connect to DropBox button
                        lnkbtnConnectDropBox.Visible = true;
                    }
                }
                else
                {
                    //*** Get DropBox Client Object
                    Application["dropBoxClientObj"] = DropBoxConnector.getDropboxClient(Application["dropBoxAccessToken"].ToString());

                    if (DropBoxConnector.MsgError != "")    //*** If error
                    {
                        lblDropBoxMsg.Text = DropBoxConnector.MsgError;

                        //*** Show Error
                        divDropBoxAlert.Visible = true;
                    }
                    else
                    {
                        //*** Get User Info
                        await DropBoxConnector.getUserInfo(Application["dropBoxClientObj"]);

                        lblDropBoxAccountName.Text = DropBoxConnector.objDropBoxUser.AccountDisplayName;

                        DropBoxGridDataBind((List <string>)Session["FolderPath"]);
                    }
                }
            }

            //******************************************************************************************************
            //*** Exact Online Part
            //******************************************************************************************************
            //*** First Time
            if (!Page.IsPostBack)
            {
                //*** Initialization
                divExactOnlineAlert.Visible         = false;
                lnkbtnConnectExactOnline.Visible    = false;
                lnkbtnDisconnectExactOnline.Visible = false;
                DivDropBoxFileGrid.Visible          = false;

                //*** Adjust Drop Box Call Back URL for
                if (HttpContext.Current.Session["exactOnlineReturnBackURL"] == null)
                {
                    HttpContext.Current.Session["exactOnlineReturnBackURL"] = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host;
                    if (HttpContext.Current.Request.Url.Port > 0)
                    {
                        HttpContext.Current.Session["exactOnlineReturnBackURL"] += ":" + HttpContext.Current.Request.Url.Port.ToString();
                    }
                    ;
                    HttpContext.Current.Session["exactOnlineReturnBackURL"] += "/" + System.Configuration.ConfigurationManager.AppSettings["exactOnlineReturnPage"];
                }

                //*** Check If Code returned into Connection String
                if (Application["ExactOnlineAccessToken"] == null && Session["ExactOnlineReturnCode"] != null)
                {
                    //**** Initialize Session Folder Path
                    List <string> Dump = new List <string> {
                    };
                    Session["ExactOnlineFolderPath"] = Dump;

                    //**** Construct Exact Online Class
                    ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                    Application["ExactOnlineAccessToken"] = objExactOnlineConnector.GetAccessToken();

                    if (objExactOnlineConnector.MsgError != "")
                    {   //*** If Error returned
                        lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                        //*** Show Error
                        divExactOnlineAlert.Visible = true;

                        return;
                    }
                }
                //******************************************************

                //*** Check ExactOnline Aurhentication Token
                if (Application["ExactOnlineAccessToken"] == null)
                {
                    //***************************
                    //*** access token is empty
                    //***************************
                    //*** 1. Check first for ExactOnline App Key & App secret
                    if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"]) ||
                        String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"]) ||
                        String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"]))
                    {
                        //*** Show Error Message
                        lblExactOnlineMsg.Text = "Please set client id, client secret and end point URL into this project's Web.config file and restart. " +
                                                 "client id/secret can be found in the ExactOnline App Console, here: " +
                                                 "https://start.exactonline.co.uk";

                        //*** Show Error
                        divExactOnlineAlert.Visible = true;

                        return;
                    }
                    else   //*** AppKey & secret exist
                    {
                        //*** Set URL Parameters
                        //strExactOnlineAuthParam = "";

                        //*** Show Connect to ExactOnline button
                        lnkbtnConnectExactOnline.Visible = true;
                    }
                }

                if (Session["ExactOnlineReturnCode"] != null)
                {
                    //**** Construct Exact Online Class
                    ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(HttpContext.Current.Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                    if (Application["ExactOnlineAccessToken"] != null)
                    {
                        objExactOnlineConnector.AccessToken = Application["ExactOnlineAccessToken"].ToString();
                    }
                    //*** Get User Info
                    lblExactOnlineAccountName.Text = objExactOnlineConnector.getUserInfo().FullName;

                    if (objExactOnlineConnector.MsgError != "")
                    {   //*** If Error returned
                        lblExactOnlineMsg.Text = objExactOnlineConnector.MsgError;

                        //*** Show Error
                        divExactOnlineAlert.Visible = true;

                        return;
                    }
                    else
                    {
                        //*** Bind Folder Grid View
                        ExactOnlineGridDataBind();
                    }
                }
            }
            //*********************************************************************************************************
        }
Esempio n. 18
0
        //*****************************************************************
        //*** Major Sync Function with Exact online store
        //*****************************************************************
        /// <summary>
        /// *** Sync Function which Sync all Modified files with Exact Online Store
        /// </summary>
        /// <param name="lstDropBoxFile">Dropbox files in List Format</param>
        /// <returns></returns>
        private async Task SyncAllFilesFolders(List <DropBoxFile> lstDropBoxFile)
        {
            //System.Threading.Thread.Sleep(30000);

            try
            {
                //*** Set Variables
                int intCount = 0, intSuccess = 0, intFailed = 0;
                Session["SyncAllNumbers"] = "";
                string strExactFileGUID    = "";
                string strFolderpath       = "";
                string strParentFolderpath = "";
                CloudStorageEntities objCloudStorageEntities = new CloudStorageEntities();

                //**** Construct Exact Online Class
                ExactOnlineConnector objExactOnlineConnector = new ExactOnlineConnector(System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientId"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineClientSecret"], System.Configuration.ConfigurationManager.AppSettings["exactOnlineEndPoint"], new Uri(Session["exactOnlineReturnBackURL"].ToString()), Session["ExactOnlineReturnCode"].ToString());

                //*** First Reset All "FileStillAlive" Flag into DB
                (from p in objCloudStorageEntities.DropBoxExactOnlines
                 where p.Id >= 0
                 select p).ToList().ForEach(x => x.FileStillAlive = 0);
                objCloudStorageEntities.SaveChanges();

                //*** Loop on All Objects on DropBox Grid View
                foreach (var DropBoxFile in lstDropBoxFile)
                {
                    strFolderpath = "";

                    //*** Refresh Counts
                    intCount += 1;

                    //**** Check If File item exist into DB with same Modified Date or not
                    //*** 1. Exist with Same Modified Date, Do Nothing
                    //*** 2. Not Exist, So Add File to Exact Online and DB
                    //*** 3. Exist with Different Modified Date, So Update File into Exact Online and Modified Date into DB

                    DropBoxExactOnline objRecord = objCloudStorageEntities.DropBoxExactOnlines.Where(i => i.DropBoxPath == DropBoxFile.FileName).FirstOrDefault();
                    if (objRecord == null || (objRecord != null && DropBoxFile.ModificationDate != objRecord.DropBoxFileModifiedDate))   //*** Not Exist Or File Exist with Different Modification Date
                    {
                        //********************************************************************
                        //*** Add File to Exact Online
                        //********************************************************************

                        //**** Get File Stream then upload it to ExactOnline & Flush
                        //*** Construct Parent Folder Path String
                        strParentFolderpath = "";
                        if ((List <string>)Session["FolderPath"] != null)
                        {
                            foreach (var item in (List <string>)Session["FolderPath"])
                            {
                                strParentFolderpath += "/" + item;
                            }
                        }

                        string strPath = strParentFolderpath + "/" + DropBoxFile.FileName;
                        strFolderpath = strPath;

                        //*** Create Folder Function
                        Stream fnStreamResult = await DropBoxConnector.Download(Session["dropBoxClientObj"], strPath);

                        if (DropBoxConnector.MsgError != "")    //*** If error
                        {
                            intFailed += 1;
                        }
                        else
                        {
                            //*************************************************************
                            //*** Convert File to Byte Array and upload it to Exact Online
                            //*************************************************************
                            if (Session["ExactOnlineAccessToken"] != null)
                            {
                                objExactOnlineConnector.AccessToken = Session["ExactOnlineAccessToken"].ToString();
                            }

                            //**** Get Document Folder GUID
                            Session["CurrentExactFolderGUID"] = string.Empty;       //*** Root Folder

                            //*** If File already exisit then Delete it first
                            if (objRecord != null && DropBoxFile.ModificationDate != objRecord.DropBoxFileModifiedDate)
                            {
                                objExactOnlineConnector.DeleteDocument(objRecord.ExactOnlineGUID);  //**** Call Delete Document
                            }

                            strExactFileGUID = objExactOnlineConnector.CreateDocumentWithAttachment(DropBoxFile.FileName, Session["CurrentExactFolderGUID"].ToString(), Common.ConvertStreamtoByteArr(fnStreamResult));
                            if (strExactFileGUID == "")
                            {
                                intFailed += 1;
                            }
                            else
                            {
                                intSuccess += 1;
                            }
                        }
                        //******************************************************************

                        if (objRecord == null)
                        {
                            //*** add to DB
                            DropBoxExactOnline objRecordNew = new DropBoxExactOnline();
                            objRecordNew.DropBoxPath             = DropBoxFile.FileName;
                            objRecordNew.DropBoxFileModifiedDate = DropBoxFile.ModificationDate;
                            objRecordNew.ExactOnlineGUID         = strExactFileGUID;
                            objRecordNew.isFile         = 1;
                            objRecordNew.FileStillAlive = 1;

                            objCloudStorageEntities.DropBoxExactOnlines.Add(objRecordNew);
                            objCloudStorageEntities.SaveChanges();
                        }
                        else
                        {
                            //**** Update DB
                            objRecord.DropBoxFileModifiedDate = DropBoxFile.ModificationDate;
                            objRecord.ExactOnlineGUID         = strExactFileGUID;
                            objRecord.FileStillAlive          = 1;

                            objCloudStorageEntities.SaveChanges();
                        }
                    }

                    //*** If File still exit and not changed
                    if (objRecord != null && DropBoxFile.ModificationDate == objRecord.DropBoxFileModifiedDate)
                    {
                        objRecord.FileStillAlive = 1;

                        objCloudStorageEntities.SaveChanges();
                    }

                    //*** set Session Variable (Shared Variable)
                    Session["SyncAllNumbers"] = lstDropBoxFile.Count.ToString() + "," + intCount.ToString() + "," + intSuccess.ToString() + "," + intFailed.ToString();
                }   //*** For Loop

                //***************************************************************************************
                //*** Then Check For Not Alive Files to Delete from DB and Exact Online
                //***************************************************************************************
                List <DropBoxExactOnline> lstFiles = objCloudStorageEntities.DropBoxExactOnlines.Where(item => item.FileStillAlive == 0).ToList();

                foreach (var file in lstFiles)
                {
                    //****************************************************************
                    //**** Delete File from Exact Online
                    //****************************************************************
                    if (file.ExactOnlineGUID != "")
                    {
                        //*** Delete File on Exact Online also
                        if (Session["ExactOnlineAccessToken"] != null)
                        {
                            objExactOnlineConnector.AccessToken = Session["ExactOnlineAccessToken"].ToString();
                        }

                        //**** Call Delete Document
                        objExactOnlineConnector.DeleteDocument(file.ExactOnlineGUID);
                    }
                    //***************************************************************************

                    //*** Delete From DB
                    objCloudStorageEntities.DropBoxExactOnlines.Remove(file);
                }   //*** For Loop

                //*** Submit Delete from DB
                objCloudStorageEntities.SaveChanges();
                //***************************************************************************************
            }
            catch (Exception e)
            {
                Session["lblDropBoxMsg"] = "SyncAllFilesFolders Error: " + e.ToString();
            }
        }