public bool RefreshTransactions()
 {
     try
     {
         DataModelEntities context = new DataModelEntities();
         List<User> users = context.Users
             .Where(u =>
                 u.Is_Active == true &&
                 u.Is_Locked != true &&
                 u.Is_Verified == true &&
                 u.Is_Paypal_Paid == true //&&
                // (u.Is_Paypal_Expired == null || u.Is_Paypal_Expired != true)
                 ).ToList();
         ParcelBL parcelBL = new ParcelBL();
         foreach (PriceManagerDAL.User user in users)
         {
             int UserCode = user.User_Code;
             ParcelBL objParcelBL = new ParcelBL();
             /*Save Ebay's All Account's items to seller item table in order to automate pricing*/
             objParcelBL.SaveEbayUserItems(UserCode);
         }
         return true;
     }
     catch (Exception ex)
     {
         return false;
     }
 }
    protected void DownloadCategories(object sender, EventArgs e)
    {
        DataModelEntities context = new DataModelEntities();

        ParcelBL parcelBL = new ParcelBL();
        List<CategoryType> catogories = parcelBL.GetEbayCategories(26);

        foreach (CategoryType item in catogories)
        {
            ProductCategory objProductCategory = new ProductCategory();
            objProductCategory.CategoryId = Convert.ToInt32(item.CategoryID);
            objProductCategory.CategoryName = item.CategoryName;
            objProductCategory.ParentId = item.CategoryParentID.Length > 0 ? Convert.ToInt32(item.CategoryParentID[0]) : 0;
            objProductCategory.CategoryLevel = item.CategoryLevel;
            context.AddToProductCategories(objProductCategory);
        }
        context.SaveChanges();
    }
    public string GetPricingItems(int? itemCode, int? userAccountCode, string categoryID, string searchColumn, string searchValue, bool? reload, int? country)
    {
        int userKey = new Base().UserKey;
        if (userKey == 0)
        {
            return "{\"login\": false}";
        }

        if (reload == true)
        {
            ParcelBL objParcelBL = new ParcelBL();
            objParcelBL.SaveEbayUserItems(userKey);
        }

        //string[] searchitems = null;

        //if (searchValue.Contains(""))
        //{
        //    searchitems = searchValue.Split(' ');

        //}

        DataModelEntities context = new DataModelEntities();
        var user = context.Users.FirstOrDefault(f => f.User_Code == userKey);

        DateTime currentDate = DateTime.Today.Date;

        var items = context.SellerItems.Where(c => c.Is_Active == true
                                                && c.User_Code == userKey
                                                && (
                                                (
                                                    itemCode == null
                                        //            && (country == null || c.Country_Code == country)
                                                    && (userAccountCode == null || userAccountCode == 0 || c.User_Account_Code == userAccountCode)
                                                    && (string.IsNullOrEmpty(categoryID) || categoryID == "0" || c.Item_Category_ID == categoryID)

                                                    && (searchColumn != "Item_Name" || string.IsNullOrEmpty(searchValue) || c.Item_Name.Contains(searchValue))
                                                    && (searchColumn != "Item_ID" || string.IsNullOrEmpty(searchValue) || c.Item_ID.Contains(searchValue))

                                                   //// && (searchColumn == "Item_Name" && (string.IsNullOrEmpty(searchValue) == false || c.Item_Name.Any(p => searchitems.Any())) )
                                                    //&& (searchColumn == "Item_ID" && (string.IsNullOrEmpty(searchValue) == false  || c.Item_Name.Any(p => searchitems.Any()))   )
                                                    && (EntityFunctions.TruncateTime(c.End_Date) > currentDate)
                                                )
                                                    || (c.Item_Code == itemCode)
                                                    )

                                             ).AsEnumerable()
            .Select(a => new SellerItemModel()
            {
                Item_View_URL = a.Item_View_URL,
                Picture_URL = a.Picture_URL,
                Is_Promo_Item = a.Is_Promo_Item,
                Algo = a.Algo,
                BIN_Price = a.BIN_Price,
                Ceiling_Price = a.Ceiling_Price,
                Current_Price = a.Current_Price,
                End_Date = a.End_Date,
                Floor_Price = a.Floor_Price,
                Item_Code = a.Item_Code,
                Item_ID = a.Item_ID,
                Item_Name = a.Item_Name,
                Item_SKU = a.Item_SKU,
                Start_Date = a.Start_Date,
                Keywords = a.Keywords,
                Is_Automated = a.Is_Automated,
                User_Code = a.User_Code,
                Algo_Name = Common.GetAlgoName(a.Algo),
                Minimum_Feedback = a.Minimum_Feedback,
                Maximum_Feedback = a.Maximum_Feedback,
                Minimum_Price = a.Minimum_Price,
                Maximum_Price = a.Maximum_Price,
                Minimum_Quantity = a.Minimum_Quantity,
                Maximum_Quantity = a.Maximum_Quantity,
                Inclued_Sellers = a.Inclued_Sellers,
                Exclued_Sellers = a.Exclude_Sellers,
                Maximum_Handling_Time = a.Maximum_Handling_Time,
                Is_Fixed_Price = a.Is_Fixed_Price,
                Is_Auctions = a.Is_Auctions,
                Is_Returns_Accepted = a.Is_Returns_Accepted,
                Is_Location_AU = a.Is_Location_AU,
                Is_Hide_Duplicates = a.Is_Hide_Duplicates,
                Is_Top_Rated_Only = a.Is_Top_Rated_Only,
                Exclude_Category_Codes = a.Exclude_Category_Codes,
                Include_Condtion_Codes = a.Include_Condtion_Codes,
                Item_Category_ID = a.Item_Category_ID,
                Item_Category_Name = a.Item_Category_Name,
                Less_To_Lowest_Price = a.Less_To_Lowest_Price,
                Item_Rank = a.Item_Rank,
                Currency = a.Currency,
                Ignore_Words = a.Ignore_Words,
                Country_Code = a.Country_Code,
                LocatedIn = a.LocatedIn,
                Rotate_Order = a.Rotate_Order,
                Rotate_Days = a.Rotate_Days,
                Rotate_Sales = a.Rotate_Sales,
                User_Account_Code = a.User_Account_Code,
                QuantityAvailable = a.QuantityAvailable
            })
            .ToList();

        if (itemCode.HasValue)
        {
            items[0].ItemTitles = context.ItemTitles.Where(a => a.ItemId == itemCode).Select(
                b => new ItemTitleModels
                    {
                        Title = b.Title,
                        ItemTitleId = b.ItemTitleId,
                        TotalSales = b.TotalSales == null ? 0 : (int)b.TotalSales
                    }
                ).ToList();
        }

        if (user.Package_Id == (int)Common.Package.Trial)
            return Common.Serialize(items.Take(100));
        else if (user.Package_Id == (int)Common.Package.Business)
            return Common.Serialize(items.ToList().Take(200));
        else
            return Common.Serialize(items);
    }
    protected void btnConfirmAuthorization_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            string sessionID = hfSessionID.Value;

            try
            {
                // fetch a new token using SessionID
                string token = new EbayServiceBL(UserKey).FetchToken(sessionID);
                if (string.IsNullOrEmpty(token) == false)
                {
                    // save entry in database.
                    DataModelEntities context = new DataModelEntities();
                    // check if user is creating a new account, or updating existing one
                    UserAccount userAccount = null;

                    if (hfSelectedEbayAccountID.Value == "0")
                    {
                        userAccount = new UserAccount();
                        userAccount.User_Code = UserKey;
                        userAccount.Account_Code = (int)Constant.Accounts.Ebay;
                        userAccount.Application_Name = string.Empty;
                        userAccount.Config_Value1 = token;
                        userAccount.Created_Date = DateTime.Now;
                        userAccount.Is_Active = true;
                        userAccount.User_IP = Request.UserHostAddress;

                        context.UserAccounts.AddObject(userAccount);
                    }
                    else
                    {
                        int userAccountCode = Convert.ToInt32(hfSelectedEbayAccountID.Value);
                        userAccount = context.UserAccounts.First(u => u.User_Account_Code == userAccountCode);
                        userAccount.Config_Value1 = token;
                        userAccount.Modified_Date = DateTime.Now;
                        userAccount.User_IP = Request.UserHostAddress;
                    }
                    context.SaveChanges();

                    try
                    {

                        EbayServiceBL service = new EbayServiceBL((int)userAccount.User_Code);
                        if (service.UserTokens != null)
                        {
                            Dictionary<string, int> localTokens = new Dictionary<string, int>();
                            foreach (KeyValuePair<int, string> pair in service.UserTokens)
                            {
                                string ebayUserName = service.GetUser(pair.Value);

                                if (pair.Key == userAccount.User_Account_Code)
                                {
                                    userAccount.Ebay_User_Name = ebayUserName;
                                    context.SaveChanges();
                                }

                            }

                        }

                        ParcelBL objParcelBL = new ParcelBL();
                        System.Threading.Thread t = new System.Threading.Thread(() => objParcelBL.SaveEbayUserItems(UserKey));
                        t.Start();

                    }
                    catch (Exception ex)
                    {
                        Logging.WriteLog(LogType.Critical, ex.ToString());
                    }

                    ScriptManager.RegisterClientScriptBlock(this, GetType(), "1", "window.location.reload()", true);
                    lblAuthError.Text = string.Empty;
                }
                else
                {
                    lblAuthError.Text = "Either you have not authorized properly, or the Ebay servers are down for the moment. Please try agian in a while.";
                }
            }
            catch (Exception ex)
            {
                lblAuthError.Text = "Either you have not authorized properly, or the Ebay servers are down for the moment. Please try agian in a while.";
            }

        }
    }
 protected void btnDownloadItems_Click(object sender, EventArgs e)
 {
     try
     {
         ParcelBL objParcelBL = new ParcelBL();
         objParcelBL.SaveEbayUserItems(UserKey);
         BindItemss();
     }
     catch (Exception ex)
     {
     }
 }
    protected void btnRefreshTransactions_Click(object sender, EventArgs e)
    {
        ParcelBL parcelBL = new ParcelBL();
        if (IsValid)
        {
            aConnectAgain.Visible = false;
            lblAPIIssues.Visible = false;
            List<ParcelItem> ebayItems = new List<ParcelItem>();

            try
            {
                ebayItems = parcelBL.GetEbayTransactions(UserKey);
            }
            catch (InvalidEbayCredentialsException ex)
            {
                lblAPIIssues.Visible = true;
                lblAPIIssues.Text = "The Ebay API settings are invalid. Please check back with your developer account or contact Ebay Support";
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Token has been revoked"))
                {
                    lblAPIIssues.Text = "The connectivity with your Ebay account is removed from your Ebay account.";
                    aConnectAgain.Visible = true;
                }
                else
                {
                    lblAPIIssues.Text = "There is some issue connecting to the Ebay server. Please check back in a while.";
                }
                lblAPIIssues.Visible = true;
            }

            List<ParcelItem> shopifyItems = parcelBL.GetShopifyTransactions(UserKey);

            List<ParcelItem> magentoItems = parcelBL.GetMagentoTransactions(UserKey);

            List<ParcelItem> bigcommerceItems = parcelBL.GetBigcommerceTransactions(UserKey);

            if (ebayItems == null)
            {
                ebayItems = new List<ParcelItem>();
                lblPendingShipmentCount.Visible = imgEbay.Visible = false;
            }
            if (shopifyItems == null)
                shopifyItems = new List<ParcelItem>();
            if (magentoItems == null)
                magentoItems = new List<ParcelItem>();
            if (bigcommerceItems == null)
                bigcommerceItems = new List<ParcelItem>();

            List<ParcelItem> allItems = ebayItems.Union(shopifyItems.OrderBy(i => i.BuyerID)).Union(magentoItems.OrderBy(i => i.BuyerID)).Union(bigcommerceItems.OrderBy(i => i.BuyerID)).ToList();

            new ParcelBL().SaveTransactions(allItems, UserKey);
            ShowPendingTransactions();
        }
    }
    protected void btnUpdateSettings_Click(object sender, EventArgs e)
    {
        try
        {
            DataModelEntities context = new DataModelEntities();
            var user = context.Users.FirstOrDefault(w => w.User_Code == UserKey);
            if (user != null)
            {
                user.Floor_Limit_Alert = chkFloorLimitNotification.Checked;
                user.Automation_Time_Delay = int.Parse(ddlTimeDelay.SelectedValue);
                user.Automation_Include_Shipping = chkIncludeShipping.Checked;
                user.Search_Only_Top_Items = int.Parse(ddlSeachOnlyTop.SelectedValue);
                int countryCode = int.Parse(ddlCountrySettings.SelectedValue);
                if (countryCode != user.Country_Code)
                {
                    user.Country_Code = int.Parse(ddlCountrySettings.SelectedValue);
                    hfCountryCode.Value = ddlCountrySettings.SelectedValue;//int.Parse(ddlCountrySettings.SelectedValue);
                    ParcelBL objParcelBL = new ParcelBL();
                    objParcelBL.SaveEbayUserItems(UserKey);
                    //ddlCountrySearch.SelectedValue = hfCountryCode.Value;

                }

                context.SaveChanges();
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void btnSaveProfile_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            int userCode = int.Parse(ddlUserList.SelectedValue);

            DataModelEntities enities = new DataModelEntities();
            User user = enities.Users.SingleOrDefault(u => u.User_Code == userCode);
            if (user != null)
            {
                string fileName = UploadLogo(user.User_Code.ToString());
                user.Full_Name = f_name.Value + " " + l_name.Value;
                user.First_Name = f_name.Value;
                user.Last_Name = l_name.Value;
                user.Company = company.Value;
                user.Address1 = txtAddress1.Value;
                user.Address2 = txtAddress2.Value;
                user.City = txtSuburb.Value;
                user.State = txtState.Value;
                user.Zip = txtPostcode.Value;
                user.Phone_Number = txtPhone.Value;
                //user.Email_Address = txtEmail.Value;
                //user.Role_Code = 2; // user;
                user.User_IP = Request.UserHostAddress;
                user.ABN_Number = txtABNNumber.Value;
                user.Charge_Code_Standard = ddlStandardCode.SelectedValue;
                user.Charge_Code_Express = ddlExpressCode.SelectedValue;
                user.Charge_Code_ExpressInt = ddlExpressIntCode.SelectedValue;
                user.Charge_Code_StandardInt = ddlStandardIntCode.SelectedValue;
                user.Charge_Code_AirMailInt = ddlAirMailIntCode.SelectedValue;
                user.Charge_Code_AusPostRegInt = ddlAusPostRegIntCode.SelectedValue;
                user.Flat_Rate_Client = chkFlatRate.Checked;
                int countryCode = int.Parse(ddlCountry.SelectedValue);

                user.Currency_Code = int.Parse(ddlCurrency.SelectedValue);
                user.LocatedIn = enities.Countries.FirstOrDefault(f => f.Country_Code == countryCode).Country_Abbr;

                if (countryCode != user.Country_Code)
                {
                    user.Country = countryCode.ToString();
                    user.Country_Code = countryCode;
                    ParcelBL objParcelBL = new ParcelBL();
                    objParcelBL.SaveEbayUserItems(UserKey);

                }

                if (!string.IsNullOrEmpty(fileName))
                {
                    user.Company_Logo = fileName;
                    imgLogo.ImageUrl = fileName;
                }
                /*Added by javed*/
                user.Minimum_Threshold_Alert = chkMinimumThresholdNotification.Checked;
                user.Floor_Limit_Alert = chkFloorLimitNotification.Checked;
                user.Automation_Time_Delay = int.Parse(ddlTimeDelay.SelectedValue);
                user.Automation_Include_Shipping = chkIncludeShipping.Checked;
                user.Search_Only_Top_Items = int.Parse(ddlSeachOnlyTop.SelectedValue);
                /*Added by javed*/

                // Added by saad
                user.Automate_Title_Display = int.Parse(ddlTitleDisplayed.SelectedValue);
                user.Notify_Title_Locked = chkNotifyTitleLocked.Checked;

                enities.SaveChanges();

                lblMsg.CssClass = "profileMessage";
                lblMsg.Visible = true;

                lblMsg.Text = "Profile Updated!";
                enities = null;
            }
        }
    }