/// <summary>
        /// Get FacebookOAuthClient.
        /// </summary>
        void MainPage_Loaded()
        {
            using (DbStorage fbdb = new DbStorage(strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user select db;
                Db ac = fbQuery.FirstOrDefault();
                if(ac == null){
                    string appId = "YOUR FACEBOOK APP ID";
                    string[] extendedPermissions = new[] { "publish_stream"};

                    var oauth = new FacebookOAuthClient { AppId = appId };
                    var parameters = new Dictionary<string, object>
                            {
                               { "response_type", "token" },
                                { "display", "touch" }
                            };
                    if (extendedPermissions != null && extendedPermissions.Length > 0)
                    {
                        var scope = new StringBuilder();
                        scope.Append(string.Join(",", extendedPermissions));
                        parameters["scope"] = scope.ToString();
                    }
                    var loginUrl = oauth.GetLoginUrl(parameters);
                    //Add webBrowser to the contentPanel
                    _webBrowser.Navigate(loginUrl);
                    ContentPanel.Children.Add(_webBrowser);
                    _webBrowser.Navigated += webBrowser_Navigated;
                    //Open the facebook login page into the browser
           
            }
        }
        }
        public void GetMyFiles() 
        {
            using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user select db;
                Db ac = fbQuery.FirstOrDefault();
                if (ac != null)
                {
                    // finding received images from NOSQL of App42.
                    Util.storageObj.FindDocumentByKeyValue(Util.storageDbName, Util.storageCollName, "userId", ac.FbId, this);

                }

            }
         }
        // save my facebook feed to local db.
        private void UpdateProfile(string Name, string FbId, string Picture)
        {
            using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user where db.AccessToken == _accessToken select db;
                Db ac = fbQuery.FirstOrDefault();
                if (ac != null)
                {
                    ac.Name = Name;
                    ac.FbId = FbId;
                    ac.Picture = Picture;
                    fbdb.SubmitChanges();
                }

            }
        }
        /// <summary>
        /// Get FacebookOAuthClient.
        /// </summary>
        void MainPage_Loaded()
        {
            using (DbStorage fbdb = new DbStorage(strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user select db;
                Db ac = fbQuery.FirstOrDefault();
                if(ac == null){

                    var loginUrl = GetFacebookLoginUrl(appId, ExtendedPermissions);
                    //Add webBrowser to the contentPanel
                    _webBrowser.Navigate(loginUrl);
                    ContentPanel.Children.Add(_webBrowser);
                    _webBrowser.Navigated += WebBrowser_Navigated;
                    //Open the facebook login page into the browser
           
            }
        }
        }
        // fetch all shared image from App42 storage.
       void ImageDownloaded()
        {
            ReceivedFiles myfiles = new ReceivedFiles(imageList);
            myfiles.GetMyFiles();
             using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
             {
                 IQueryable<Db> fbQuery = from db in fbdb.user select db;
                 Db ac = fbQuery.FirstOrDefault();
                 if (ac != null)
                 {
                     // finding Shared images from NOSQL of App42.
                     Util.storageService.FindDocumentByKeyValue(Util.storageDbName, Util.storageCollName, "ownerId", ac.FbId, this);

                 }

             }
             
             SystemTray.SetProgressIndicator(this, indicator);
          
        }
        // callback when comments will be receive or add.
        void App42Callback.OnSuccess(object response)
        {
            using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user select db;
                Db ac = fbQuery.FirstOrDefault();
                if (ac != null)
                {
                    me = ac.Name;
                }

            }

            if (response is IList<Review>)
            {
                IList<Review> reviewList = (IList<Review>)response;
                for (int i = 0; i < reviewList.Count; i++)
                {
                    String userId = reviewList[i].GetUserId();
                    String message = reviewList[i].GetComment();
                    DateTime time = reviewList[i].GetCreatedOn();
                    if (userId == me)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {

                            messages.Add(new Message()
                            {

                                Side = MessageSide.Me,
                                Text = message,
                                Timestamp = time
                            });
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {

                            messages.Add(new Message()
                            {

                                Side = MessageSide.You,
                                Text = message,
                                Timestamp = time
                            });
                        });
                    }
                }
            }
            else if (response is Review)
            {
                Review review = (Review)response;
                String message = review.GetComment();
                DateTime time = review.GetCreatedOn();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {

                    messages.Add(new Message()
                    {

                        Side = MessageSide.Me,
                        Text = message,
                        Timestamp = time
                    });
                });
            }

        }
        // Send comment 
        private void SendMessage(String userName,String message)
        {
            using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
            {
                IQueryable<Db> fbQuery = from db in fbdb.user select db;
                Db ac = fbQuery.FirstOrDefault();
                if (ac != null)
                {
                    // Adding comment on image with your buddy.
                    Util.reviewService.AddComment(ac.Name,fileName,message,this);
                }

            }
             
        }
        /// <summary>
        /// Get access token from facebook and save to local database.
        /// </summary>
        void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            //Try because there might be cases when user input wrong password
            if (FacebookOAuthResult.TryParse(e.Uri.AbsoluteUri, out result))
            {
                if (result.IsSuccess)
                {
                    _accessToken = result.AccessToken;
                    //AccessToken is used when you want to use API as a user
                    //This example is not using it at all just showing it in a messagebox

                    //Adding data to the local database
                    using (DbStorage fbdb = new DbStorage(strConnectionString))
                    {
                        IQueryable<Db> fbQuery = from db in fbdb.user select db;
                        Db ac = fbQuery.FirstOrDefault();
                        if (ac == null)
                        {
                            Db newUser = new Db
                            {
                                AccessToken = _accessToken,
                            };

                            fbdb.user.InsertOnSubmit(newUser);
                            fbdb.SubmitChanges();
                         }
                        
                    }
                    //Hide the browser controller
                    _webBrowser.Visibility = System.Windows.Visibility.Collapsed;
                    ContentPanel.Children.Remove(_webBrowser);
                    
                    SystemTray.SetProgressIndicator(this, indicator);
                    Util myProfile = new Util(_accessToken);
                    myProfile.myProfile();

                    // load friend list from App42
                    GetFacebookFriendsFromSocial(_accessToken);
                   
                }
                else
                {
                    var errorDescription = result.ErrorDescription;
                    var errorReason = result.ErrorReason;
                    MessageBox.Show(errorReason + " " + errorDescription);
                }
            }
        }
 // create database.
 private void CreateDbIfNotExists()
 {
     using (DbStorage fbDb = new DbStorage(strConnectionString))
     {
         if (fbDb.DatabaseExists() == false)
         {
             fbDb.CreateDatabase();
             image1.Visibility = Visibility.Collapsed;
             LoginText.Visibility = Visibility.Collapsed;
             textBlock1.Visibility = Visibility.Visible;
             button1.Visibility = Visibility.Visible;
             _webBrowser = new WebBrowser();
             MainPage_Loaded();
            // this.Loaded += new RoutedEventHandler(MainPage_Loaded);
         }
         else
         {
             using (DbStorage fbdb = new DbStorage(strConnectionString))
             {
                 IQueryable<Db> fbQuery = from db in fbdb.user select db;
                 Db ac = fbQuery.FirstOrDefault();
                 image1.Visibility = Visibility.Collapsed;
                 LoginText.Visibility = Visibility.Collapsed;
                 textBlock1.Visibility = Visibility.Visible;
                 button1.Visibility = Visibility.Visible;
                 SystemTray.SetProgressIndicator(this, indicator);
                 // load friend list from App42
                 GetFacebookFriendsFromSocial(ac.AccessToken.ToString());
                 
             }
         }
     }
 }
        // App42 Callback 
        void App42Callback.OnSuccess(object response)
        {
            if (response is Upload)
            {
                Upload upload = (Upload)response;
                IList<Upload.File> fileList = upload.GetFileList();
                for (int i = 0; i < fileList.Count; i++)
                {
                    name = fileList[i].GetName();
                    type = fileList[i].GetType();
                    url = fileList[i].GetUrl();
                    description = fileList[i].GetDescription();
                }
                currentPage.Dispatcher.BeginInvoke(() =>
                {
                    indicator.IsVisible = false;
                });
                using (DbStorage fbdb = new DbStorage(MainPage.strConnectionString))
                {
                    IQueryable<Db> fbQuery = from db in fbdb.user select db;
                    Db ac = fbQuery.FirstOrDefault();
                    if (ac != null)
                    {
                        JObject myJson = new JObject();

                        myJson.Add("ownerId", ac.FbId);
                        myJson.Add("ownerName", ac.Name);
                        myJson.Add("userId", uId);
                        myJson.Add("userName", uName);
                        myJson.Add("imageName", name);
                        myJson.Add("imageUrl", url);
                        myJson.Add("description", description);
                        AddMetaInfoWithApp42(myJson);
                    }

                }
            }
        }
        /// <summary>
        /// Get access token from facebook and save to local database.
        /// </summary>
        void WebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;
            if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                MessageBox.Show("tt");
                return;
            }

            if (oauthResult.IsSuccess)
            {
                var accessToken1 = oauthResult.AccessToken;
                MessageBox.Show(accessToken1);
                _accessToken = oauthResult.AccessToken;
                //AccessToken is used when you want to use API as a user
                //This example is not using it at all just showing it in a messagebox

                //Adding data to the local database
                using (DbStorage fbdb = new DbStorage(strConnectionString))
                {
                    IQueryable<Db> fbQuery = from db in fbdb.user select db;
                    Db ac = fbQuery.FirstOrDefault();
                    if (ac == null)
                    {
                        Db newUser = new Db
                        {
                            AccessToken = _accessToken,
                        };

                        fbdb.user.InsertOnSubmit(newUser);
                        fbdb.SubmitChanges();
                    }

                }
                //Hide the browser controller
                _webBrowser.Visibility = System.Windows.Visibility.Collapsed;
                ContentPanel.Children.Remove(_webBrowser);

                SystemTray.SetProgressIndicator(this, indicator);
                Util myProfile = new Util(_accessToken);
                myProfile.MyProfile();

                // load friend list from App42
                GetFacebookFriendsFromSocial(_accessToken);
            }
            else
            {
                // user cancelled
                MessageBox.Show(oauthResult.ErrorDescription);
            }
            
        }