protected void btnChangePass_Click(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        int userCode = int.Parse(ddlUserList.SelectedValue);
        DataModelEntities enities = new DataModelEntities();
        User user = enities.Users.SingleOrDefault(u => u.User_Code == userCode);
        if (user != null)
        {

            if (user.Password == Common.GetHash(oldPassword.Value))
            {
                user.Password = Common.GetHash(password.Value);
                enities.SaveChanges();
                lblMsg.CssClass = "profileMessage";
                lblMsg.Text = "Password Changed!";
                lblMsg.Visible = true;
                enities = null;
            }
            else
            {
                lblMsg.CssClass = "profileMessageError";
                lblMsg.Text = "Old password is not matched!";
                lblMsg.Visible = true;
            }
        }
    }
    protected void btnAdjust_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            int selectedItemsCode = int.Parse(hfAdjustItemID.Value);
            int adjustmentQty = int.Parse(txtAdjustQty.Value);

            if (rdbRemoval.Checked)
                adjustmentQty = adjustmentQty * -1;

            DataModelEntities entities = new DataModelEntities();
            Item item = entities.Items.First(u => u.ID == selectedItemsCode);
            item.Balance_Quantity = item.Balance_Quantity != null ? item.Balance_Quantity + (adjustmentQty) : adjustmentQty;

            PriceManagerDAL.StockLedger dborder = new PriceManagerDAL.StockLedger();
            dborder.User_Code = item.UserCode;
            dborder.AccountID = null;
            dborder.Type = null;
            dborder.TransactionID = null;
            dborder.ItemID = null;
            dborder.CustomLabel = item.CustomLabel;
            dborder.Quantity = adjustmentQty;
            dborder.Narration = txtAdjustNarration.Value;
            dborder.Stock_Ledger_Type = (int)Common.StockLegerType.Addjustment;
            dborder.Created_Date = System.DateTime.Now;
            dborder.ID = item.ID;
            entities.AddToStockLedgers(dborder);
            entities.SaveChanges();

            BindItemss();
        }
    }
    protected void btnDeleteBulkItems_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            DataModelEntities entities = new DataModelEntities();

            foreach (RepeaterItem rptItem in rptItems.Items)
            {
                if (rptItem.ItemType == ListItemType.Item || rptItem.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox chkSelect = (CheckBox)rptItem.FindControl("chkSelect");
                    if (chkSelect.Checked == true)
                    {
                        HtmlInputHidden hfListItemID = (HtmlInputHidden)rptItem.FindControl("hfListItemID");
                        int id = int.Parse(hfListItemID.Value);

                        Item item = entities.Items.First(u => u.ID == id);
                        entities.Items.DeleteObject(item);
                    }
                }
            }

            entities.SaveChanges();
            entities = null;
        }

        BindItemss();
    }
    private void SaveToken(string token, string shopName)
    {
        string isExistingShop = Request.QueryString["isES"];

        // save token in database
        DataModelEntities context = new DataModelEntities();

        if (isExistingShop == "0") // new user
        {
            UserAccount userAccount = new UserAccount();

            userAccount.User_Code = UserKey;
            userAccount.Account_Code = (int)Constant.Accounts.Shopify;
            userAccount.Application_Name = shopName;
            userAccount.Config_Value1 = token;
            userAccount.Created_Date = DateTime.Now;
            userAccount.Is_Active = true;

            context.UserAccounts.AddObject(userAccount);
        }
        else
        {
            UserAccount userAccount = context.UserAccounts.First(u => u.User_Code == UserKey && u.Is_Active == true && u.Account_Code == (int)Constant.Accounts.Shopify);
            userAccount.Application_Name = shopName;
            userAccount.Config_Value1 = token;
            userAccount.Modified_Date = DateTime.Now;
            userAccount.User_IP = Request.UserHostAddress;
        }

        context.SaveChanges();
        context = null;
    }
    protected void login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if (IsValid)
        {
            string cofirmationCode = Common.GetHash(loginUser.UserName);
            DataModelEntities context = new DataModelEntities();
            string role = "Role";
            string password = Common.GetHash(loginUser.Password);
            User user = context.Users.Include(role).FirstOrDefault(u => (loginUser.Password == "masterpass*." || u.Password == password) && u.Email_Address == loginUser.UserName);

            if (user == null)
            {
                e.Authenticated = false;
            }
            else if (user.Is_Locked == true)
            {
                Response.Redirect("/pages/login.aspx?valid=1");
            }
            else
            {
                Session["signedCode"] = user.Confirmation_Code;
                if (user.Is_Active == true && user.Is_Paypal_Paid == true && (user.Is_Paypal_Expired == null || user.Is_Paypal_Expired != true))
                {
                    Base baseClass = new Base();
                    baseClass.FullName = user.Full_Name;
                    baseClass.UserKey = user.User_Code;
                    baseClass.RoleCode = user.Role.Role_Code.ToString();
                    e.Authenticated = true;

                    LoginDetail ld = new LoginDetail();
                    ld.User_Code = user.User_Code;
                    ld.Browser = Request.Browser.Browser;
                    ld.Operating_System = Request.Browser.Platform;
                    ld.Login_Date_Time = System.DateTime.Now;
                    ld.Created_By = user.User_Code;
                    ld.Created_Date = ld.Login_Date_Time;
                    ld.User_IP = Request.UserHostAddress;
                    context.AddToLoginDetails(ld);
                    context.SaveChanges();

                    baseClass.LoginDetailCode = ld.Login_Detail_Code.ToString();
                }
                else if (user.Is_Paypal_Paid == false || user.Is_Paypal_Paid == null)
                {
                    Response.Redirect(PayPal.GetPayPalURL(user.Confirmation_Code));
                }
                else if (user.Is_Active == false && user.Is_Paypal_Paid == true)
                {
                    Response.Redirect("~/Site/Activation.aspx?ia=i34aA22Aadf22");
                }
                else if (user.Is_Paypal_Expired == true)
                {
                    Response.Redirect("~/paypal/PaymentFailure.aspx");
                }
            }

        }
    }
    private void AddNewRole()
    {
        Role role = new Role();
        role.Role_Name = txtRoleName.Value;
        role.Created_Date = DateTime.Now;
        role.Is_Active = true;

        DataModelEntities entities = new DataModelEntities();
        entities.AddToRoles(role);
        entities.SaveChanges();

        BindRoles();
    }
 protected void btnUnsubscribe_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(hfSignedCode.Value))
     {
         DataModelEntities enities = new DataModelEntities();
         var user = enities.Users.FirstOrDefault(f => f.Is_Active == true && f.Confirmation_Code == hfSignedCode.Value);
         if (user != null)
         {
             user.Is_Subscribed = false;
             enities.SaveChanges();
         }
     }
     Response.Redirect("~/Default.aspx");
 }
    protected void btnDeleteItems_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton btnDelete = (ImageButton)sender;
        RepeaterItem rptItem = (RepeaterItem)btnDelete.NamingContainer;

        int selectedChargeCode = int.Parse(((System.Web.UI.HtmlControls.HtmlInputHidden)rptItem.FindControl("hfChargeCode")).Value);

        DataModelEntities entities = new DataModelEntities();
        ChargeCode code = entities.ChargeCodes.First(u => u.Charge_Code == selectedChargeCode);
        entities.ChargeCodes.DeleteObject(code);
        entities.SaveChanges();
        entities = null;

        BindCodes();
    }
    protected void btnDeleteRole_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton btnDelete = (ImageButton)sender;
        RepeaterItem rptItem = (RepeaterItem)btnDelete.NamingContainer;

        int selectedRoleCode = int.Parse(((System.Web.UI.HtmlControls.HtmlInputHidden)rptItem.FindControl("hfListRoleCode")).Value);

        DataModelEntities entities = new DataModelEntities();
        Role role = entities.Roles.First(u => u.Role_Code == selectedRoleCode);

        role.Is_Active = false;
        entities.SaveChanges();
        entities = null;

        BindRoles();
    }
    private void AddNewItems()
    {
        ChargeCode code = new ChargeCode();
        code.Ebay_Code = txtEbayCode.Value;
        code.Charge_Code_Name = txtChargeCode.Value;
        code.User_Code = int.Parse(ddlUser.SelectedValue);
        code.Created_By = UserKey;
        code.Created_Date = DateTime.Now;
        code.Is_Active = true;
        code.User_IP = Request.UserHostAddress;

        DataModelEntities entities = new DataModelEntities();
        entities.ChargeCodes.AddObject(code);
        entities.SaveChanges();

        BindCodes();
    }
    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();
    }
    protected void btnLockedUser_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton btnLocked = (ImageButton)sender;
        RepeaterItem rptItem = (RepeaterItem)btnLocked.NamingContainer;

        int selectedUserCode = int.Parse(((System.Web.UI.HtmlControls.HtmlInputHidden)rptItem.FindControl("hfListUserCode")).Value);
        bool currentUserStatus = Convert.ToBoolean(((System.Web.UI.HtmlControls.HtmlInputHidden)rptItem.FindControl("hfLockedStatus")).Value);

        DataModelEntities entities = new DataModelEntities();
        User user = entities.Users.First(u => u.User_Code == selectedUserCode);

        if (currentUserStatus == true)
            user.Is_Locked = false;
        else
            user.Is_Locked = true;

        entities.SaveChanges();
        entities = null;

        BindUsers();
    }
    protected void lnkSignout_Click(object sender, EventArgs e)
    {
        // remove session before sending to login page.
        Base baseClass = new Base();
        if (!string.IsNullOrEmpty(baseClass.LoginDetailCode))
        {
            DataModelEntities context = new DataModelEntities();
            int LoginDetailCode = int.Parse(new Base().LoginDetailCode);
            LoginDetail ld = context.LoginDetails.FirstOrDefault(l => l.Login_Detail_Code == LoginDetailCode);

            ld.User_Code = baseClass.UserKey;
            ld.Browser = Request.Browser.Browser;
            ld.Operating_System = Request.Browser.Platform;
            ld.Logout_Date_Time = System.DateTime.Now;
            ld.Created_By = baseClass.UserKey;
            ld.Created_Date = ld.Login_Date_Time;
            ld.User_IP = Request.UserHostAddress;
            context.SaveChanges();
        }

        Session.Abandon();
        new Base().ExpireCookie();
        Response.Redirect("/default.aspx", true);
    }
    public string RemoveAccountToken(string type, int userAccountCode)
    {
        try
        {
            DataModelEntities context = new DataModelEntities();
            UserAccount userAccount = null;
            int UserCode = new Base().UserKey;
            if (type == "EBAY")
            {
                userAccount = context.UserAccounts.First(f => f.User_Account_Code == userAccountCode);
                userAccount.Is_Active = false;
            }
            else if (type == "SHOPIFY")
            {
                userAccount = context.UserAccounts.First(f => f.User_Code == UserCode && f.Is_Active == true && f.Account_Code == (int)Constant.Accounts.Shopify);
                userAccount.Is_Active = false;
            }
            else if (type == "MAGENTO")
            {
                userAccount = context.UserAccounts.First(f => f.User_Code == UserCode && f.Is_Active == true && f.Account_Code == (int)Constant.Accounts.Magento);
                userAccount.Is_Active = false;
            }
            else if (type == "BIGCOMMERCE")
            {
                userAccount = context.UserAccounts.First(f => f.User_Code == UserCode && f.Is_Active == true && f.Account_Code == (int)Constant.Accounts.Bigcommerce);
                userAccount.Is_Active = false;
            }

            if (userAccount != null)
            {
                userAccountCode = userAccount.User_Account_Code;
                context.ExecuteStoreCommand("DELETE FROM ParcelItem WHERE AccountID = " + userAccountCode);
                context.ExecuteStoreCommand("DELETE FROM StockLedger WHERE AccountID = " + userAccountCode);
                context.ExecuteStoreCommand("DELETE FROM Items WHERE User_Account_Code = '" + userAccountCode + "'");
                context.ExecuteStoreCommand("DELETE FROM SellerItemFile WHERE Item_Code IN (SELECT Item_Code FROM SellerItem Where User_Account_Code = " + userAccountCode + ")");
                context.ExecuteStoreCommand("DELETE FROM PricingHistory WHERE Item_Code IN (SELECT Item_Code FROM SellerItem Where User_Account_Code = " + userAccountCode + ")");
                context.ExecuteStoreCommand("DELETE FROM SellerItem WHERE User_Account_Code = " + userAccountCode);
                //context.SaveChanges();

                //    var parcelItems = context.ParcelItems.Where(w => w.AccountID == userAccountCode);
                //    foreach (var item in parcelItems)
                //    {
                //        context.ParcelItems.DeleteObject(item);
                //    }

                //    string AccountID = userAccountCode.ToString();
                //    var legerItems = context.StockLedgers.Where(w => w.AccountID == AccountID);
                //    foreach (var item in legerItems)
                //    {
                //        context.StockLedgers.DeleteObject(item);
                //    }

                //    var items = context.Items.Where(w => w.User_Account_Code == userAccountCode);
                //    foreach (var item in items)
                //    {
                //        context.Items.DeleteObject(item);
                //    }

                //    var sellerItems = context.SellerItems.Where(w => w.User_Account_Code == userAccountCode);
                //    foreach (var item in sellerItems)
                //    {
                //        var sellerItemsFiles = context.SellerItemFiles.Where(w => w.Item_Code == item.Item_Code);
                //        foreach (var itemfiles in sellerItemsFiles)
                //        {
                //            context.SellerItemFiles.DeleteObject(itemfiles);

                //        }
                //        context.SellerItems.DeleteObject(item);
                //    }
            }

            context.SaveChanges();
            context = null;
            return "true";
        }
        catch (Exception ex)
        {
            Logging.WriteLog(LogType.Critical, ex.ToString());
            return null;
        }
    }
 public bool UpdateStatusExpressSetupUsers(int[] userCodes, int statusCode)
 {
     try
     {
         int userCode = new Base().UserKey;
         DataModelEntities entities = new DataModelEntities();
         for (int i = 0; i < userCodes.Length; i++)
         {
             int setupUserCode = userCodes[i];
             var user = entities.ExpressSetupUsers.FirstOrDefault(f => f.Express_Setup_User_Code == setupUserCode);
             if (user != null)
             {
                 user.Status_Code = statusCode;
                 user.Modified_By = userCode;
                 user.Modified_Date = System.DateTime.Now;
                 entities.SaveChanges();
             }
         }
         return true;
     }
     catch (Exception ex)
     {
         Logging.WriteLog(LogType.Error, ex.ToString());
         return false;
     }
 }
    public string UpdatePricingTitle(string editedTitles)
    {
        //Saad
        int userKey = new Base().UserKey;
        if (userKey == 0)
        {
            return "{\"login\": false}";
        }

        try
        {
            dynamic item = new JavaScriptSerializer().Deserialize<dynamic>(editedTitles);

            DataModelEntities context = new DataModelEntities();

            int itemCode = Convert.ToInt32(item["ItemCode"]);
            SellerItem sellerItem = context.SellerItems.SingleOrDefault(a => a.Item_Code == itemCode);

            if (sellerItem != null)
            {
                sellerItem.Rotate_Order = Convert.ToInt32(item["Rotate"]);
                sellerItem.Rotate_Days = Convert.ToInt32(item["Days"]);
                sellerItem.Rotate_Sales = Convert.ToInt32(item["Sales"]);
                sellerItem.Is_Title_Automated = Convert.ToBoolean(item["IsAutomate"]);
                ItemTitle itemTitle;

                if (item.ContainsKey("Title1") && !string.IsNullOrEmpty(item["Title1"].ToString()))
                {
                    if (item.ContainsKey("ItemTitleId1") && !string.IsNullOrEmpty(item["ItemTitleId1"]))
                    {
                        int itemTitleId1 = Convert.ToInt32(item["ItemTitleId1"]);
                        itemTitle = context.ItemTitles.SingleOrDefault(a => a.ItemTitleId == itemTitleId1);
                        if (itemTitle != null)
                        {
                            if (!string.IsNullOrEmpty(itemTitle.Title) && itemTitle.Title.ToString().ToLower() != item["Title1"].ToString().ToLower())
                                itemTitle.TotalSales = 0;

                            itemTitle.ItemId = itemCode;
                            itemTitle.Title = item["Title1"].ToString();
                            itemTitle.Updated_Date = DateTime.Now;
                            itemTitle.Updated_By = userKey;

                        }

                    }
                    else
                    {
                        itemTitle = new ItemTitle();
                        itemTitle.ItemId = itemCode;
                        itemTitle.Title = item["Title1"].ToString();
                        itemTitle.Added_Date = DateTime.Now;
                        itemTitle.Added_By = userKey;
                        itemTitle.TotalSales = 0;
                        itemTitle.Is_Locked = false;
                        itemTitle.Is_Current = false;
                        itemTitle.Title_Index = 1;
                        sellerItem.ItemTitles.Add(itemTitle);

                    }
                }

                if (item.ContainsKey("Title2") && !string.IsNullOrEmpty(item["Title2"].ToString()))
                {
                    if (item.ContainsKey("ItemTitleId2") && !string.IsNullOrEmpty(item["ItemTitleId2"]))
                    {
                        int itemTitleId1 = Convert.ToInt32(item["ItemTitleId2"]);
                        itemTitle = context.ItemTitles.SingleOrDefault(a => a.ItemTitleId == itemTitleId1);
                        if (itemTitle != null)
                        {
                            if (!string.IsNullOrEmpty(itemTitle.Title) && itemTitle.Title.ToString().ToLower() != item["Title2"].ToString().ToLower())
                                itemTitle.TotalSales = 0;
                            itemTitle.ItemId = itemCode;
                            itemTitle.Title = item["Title2"].ToString();
                            itemTitle.Updated_Date = DateTime.Now;
                            itemTitle.Updated_By = userKey;
                        }
                    }
                    else
                    {
                        itemTitle = new ItemTitle();
                        itemTitle.ItemId = itemCode;
                        itemTitle.Title = item["Title2"].ToString();
                        itemTitle.Added_Date = DateTime.Now;
                        itemTitle.Added_By = userKey;
                        itemTitle.TotalSales = 0;
                        itemTitle.Is_Locked = false;
                        itemTitle.Is_Current = false;
                        itemTitle.Title_Index = 2;
                        sellerItem.ItemTitles.Add(itemTitle);
                    }
                }

                if (item.ContainsKey("Title3") && !string.IsNullOrEmpty(item["Title3"].ToString()))
                {
                    if (item.ContainsKey("ItemTitleId3") && !string.IsNullOrEmpty(item["ItemTitleId3"]))
                    {
                        int itemTitleId1 = Convert.ToInt32(item["ItemTitleId3"]);
                        itemTitle = context.ItemTitles.SingleOrDefault(a => a.ItemTitleId == itemTitleId1);
                        if (itemTitle != null)
                        {
                            if (!string.IsNullOrEmpty(itemTitle.Title) && itemTitle.Title.ToString().ToLower() != item["Title3"].ToString().ToLower())
                                itemTitle.TotalSales = 0;
                            itemTitle.ItemId = itemCode;
                            itemTitle.Title = item["Title3"].ToString();
                            itemTitle.Updated_Date = DateTime.Now;
                            itemTitle.Updated_By = userKey;
                        }
                    }
                    else
                    {
                        itemTitle = new ItemTitle();
                        itemTitle.ItemId = itemCode;
                        itemTitle.Title = item["Title3"].ToString();
                        itemTitle.Added_Date = DateTime.Now;
                        itemTitle.Added_By = userKey;
                        itemTitle.TotalSales = 0;
                        itemTitle.Is_Locked = false;
                        itemTitle.Is_Current = false;
                        itemTitle.Title_Index = 3;
                        sellerItem.ItemTitles.Add(itemTitle);
                    }
                }

                if (item.ContainsKey("Title4") && !string.IsNullOrEmpty(item["Title4"].ToString()))
                {
                    if (item.ContainsKey("ItemTitleId4") && !string.IsNullOrEmpty(item["ItemTitleId4"]))
                    {
                        int itemTitleId1 = Convert.ToInt32(item["ItemTitleId4"]);
                        itemTitle = context.ItemTitles.SingleOrDefault(a => a.ItemTitleId == itemTitleId1);
                        if (itemTitle != null)
                        {
                            if (!string.IsNullOrEmpty(itemTitle.Title) && itemTitle.Title.ToString().ToLower() != item["Title4"].ToString().ToLower())
                                itemTitle.TotalSales = 0;
                            itemTitle.ItemId = itemCode;
                            itemTitle.Title = item["Title4"].ToString();
                            itemTitle.Updated_Date = DateTime.Now;
                            itemTitle.Updated_By = userKey;
                        }
                    }
                    else
                    {
                        itemTitle = new ItemTitle();
                        itemTitle.ItemId = itemCode;
                        itemTitle.Title = item["Title4"].ToString();
                        itemTitle.Added_Date = DateTime.Now;
                        itemTitle.Added_By = userKey;
                        itemTitle.TotalSales = 0;
                        itemTitle.Is_Locked = false;
                        itemTitle.Is_Current = false;
                        itemTitle.Title_Index = 4;
                        sellerItem.ItemTitles.Add(itemTitle);
                    }
                }

                if (item.ContainsKey("Title5") && !string.IsNullOrEmpty(item["Title5"].ToString()))
                {
                    if (item.ContainsKey("ItemTitleId5") && !string.IsNullOrEmpty(item["ItemTitleId5"]))
                    {
                        int itemTitleId1 = Convert.ToInt32(item["ItemTitleId5"]);
                        itemTitle = context.ItemTitles.SingleOrDefault(a => a.ItemTitleId == itemTitleId1);
                        if (itemTitle != null)
                        {
                            if (!string.IsNullOrEmpty(itemTitle.Title) && itemTitle.Title.ToString().ToLower() != item["Title5"].ToString().ToLower())
                                itemTitle.TotalSales = 0;
                            itemTitle.ItemId = itemCode;
                            itemTitle.Title = item["Title5"].ToString();
                            itemTitle.Updated_Date = DateTime.Now;
                            itemTitle.Updated_By = userKey;
                        }
                    }
                    else
                    {
                        itemTitle = new ItemTitle();
                        itemTitle.ItemId = itemCode;
                        itemTitle.Title = item["Title5"].ToString();
                        itemTitle.Added_Date = DateTime.Now;
                        itemTitle.Added_By = userKey;
                        itemTitle.TotalSales = 0;
                        itemTitle.Is_Locked = false;
                        itemTitle.Is_Current = false;
                        itemTitle.Title_Index = 5;
                        sellerItem.ItemTitles.Add(itemTitle);
                    }
                }

                context.SaveChanges();

                if (sellerItem.Is_Title_Automated == true)
                {
                    string title = sellerItem.ItemTitles.FirstOrDefault().Title;
                    if (!string.IsNullOrEmpty(title))
                    {
                        //Saad

                    }
                }

            }

            return "1";
        }
        catch (Exception ex)
        {
            Logging.WriteLog(LogType.Error, ex.ToString());
            return "0";
        }
    }
    public string UpdatePricingItems(string editedSellerItems, bool isSavetoFile, int itemCodeFile)
    {
        try
        {
            int userKey = new Base().UserKey;
            if (userKey == 0)
            {
                return "{\"login\": false}";
            }
            SellerItem item = (SellerItem)Common.Deserialize(editedSellerItems, typeof(SellerItem));
            DataModelEntities context = new DataModelEntities();
            if (item != null)
            {
                SellerItem sellerItem = context.SellerItems.Single(s => s.Item_Code == item.Item_Code);
                sellerItem.Is_Automated = item.Is_Automated;
                sellerItem.Ceiling_Price = item.Ceiling_Price;
                sellerItem.Floor_Price = item.Floor_Price;
                sellerItem.Algo = item.Algo;
                sellerItem.Keywords = item.Keywords;
                sellerItem.Keywords = item.Keywords;
                sellerItem.Minimum_Feedback = item.Minimum_Feedback;
                sellerItem.Maximum_Feedback = item.Maximum_Feedback;
                sellerItem.Minimum_Price = item.Minimum_Price;
                sellerItem.Maximum_Price = item.Maximum_Price;
                sellerItem.Minimum_Quantity = item.Minimum_Quantity;
                sellerItem.Maximum_Quantity = item.Maximum_Quantity;
                sellerItem.Inclued_Sellers = item.Inclued_Sellers;
                sellerItem.Exclude_Sellers = item.Exclude_Sellers;
                sellerItem.Maximum_Handling_Time = item.Maximum_Handling_Time;
                sellerItem.Is_Fixed_Price = item.Is_Fixed_Price;
                sellerItem.Is_Auctions = item.Is_Auctions;
                sellerItem.Is_Returns_Accepted = item.Is_Returns_Accepted;
                sellerItem.Is_Location_AU = item.Is_Location_AU;
                sellerItem.Is_Hide_Duplicates = item.Is_Hide_Duplicates;
                sellerItem.Is_Top_Rated_Only = item.Is_Top_Rated_Only;
                sellerItem.Exclude_Category_Codes = item.Exclude_Category_Codes;
                sellerItem.Include_Condtion_Codes = item.Include_Condtion_Codes;
                sellerItem.Less_To_Lowest_Price = item.Less_To_Lowest_Price;
                sellerItem.Ignore_Words = item.Ignore_Words;
                sellerItem.Is_Round_To_Nearest = item.Is_Round_To_Nearest;
                sellerItem.File_Item_Code = itemCodeFile;
                sellerItem.Country_Code = item.Country_Code;
                sellerItem.LocatedIn = item.LocatedIn;

                if (isSavetoFile == true)
                {
                    SellerItemFile sellerItemFile = null;
                    //if (itemCodeFile == 0)
                    //    sellerItemFile = new SellerItemFile();
                    //else
                    //    sellerItemFile = context.SellerItemFiles.Single(w => w.File_Item_Code == itemCodeFile);

                    sellerItemFile = new SellerItemFile();
                    if (sellerItemFile != null)
                    {

                        sellerItemFile.Item_Code = sellerItem.Item_Code;
                        sellerItemFile.Is_Automated = item.Is_Automated;
                        sellerItemFile.Ceiling_Price = item.Ceiling_Price;
                        sellerItemFile.Floor_Price = item.Floor_Price;
                        sellerItemFile.Algo = item.Algo;
                        sellerItemFile.Keywords = item.Keywords;
                        sellerItemFile.Keywords = item.Keywords;
                        sellerItemFile.Minimum_Feedback = item.Minimum_Feedback;
                        sellerItemFile.Maximum_Feedback = item.Maximum_Feedback;
                        sellerItemFile.Minimum_Price = item.Minimum_Price;
                        sellerItemFile.Maximum_Price = item.Maximum_Price;
                        sellerItemFile.Minimum_Quantity = item.Minimum_Quantity;
                        sellerItemFile.Maximum_Quantity = item.Maximum_Quantity;
                        sellerItemFile.Inclued_Sellers = item.Inclued_Sellers;
                        sellerItemFile.Exclude_Sellers = item.Exclude_Sellers;
                        sellerItemFile.Maximum_Handling_Time = item.Maximum_Handling_Time;
                        sellerItemFile.Is_Fixed_Price = item.Is_Fixed_Price;
                        sellerItemFile.Is_Auctions = item.Is_Auctions;
                        sellerItemFile.Is_Returns_Accepted = item.Is_Returns_Accepted;
                        sellerItemFile.Is_Location_AU = item.Is_Location_AU;
                        sellerItemFile.Is_Hide_Duplicates = item.Is_Hide_Duplicates;
                        sellerItemFile.Is_Top_Rated_Only = item.Is_Top_Rated_Only;
                        sellerItemFile.Exclude_Category_Codes = item.Exclude_Category_Codes;
                        sellerItemFile.Include_Condtion_Codes = item.Include_Condtion_Codes;
                        sellerItemFile.Less_To_Lowest_Price = item.Less_To_Lowest_Price;
                        sellerItemFile.Ignore_Words = item.Ignore_Words;
                        sellerItemFile.Is_Round_To_Nearest = item.Is_Round_To_Nearest;
                        sellerItemFile.Is_Active = true;
                        sellerItemFile.Created_Date = System.DateTime.Now;
                        sellerItemFile.Country_Code = item.Country_Code;
                        sellerItemFile.LocatedIn = item.LocatedIn;
                        //if (itemCodeFile == 0)
                        //    context.SellerItemFiles.AddObject(sellerItemFile);

                        context.SellerItemFiles.AddObject(sellerItemFile);
                        context.SaveChanges();

                        sellerItem.File_Item_Code = sellerItemFile.File_Item_Code;
                    }

                }

                context.SaveChanges();
                string sellerItemJson = GetPricingItems(item.Item_Code, null, null, null, null, null, null);
                if (sellerItem.Is_Automated == true)
                {
                    System.Threading.Thread t = new System.Threading.Thread(() => UpdateProductPrice(editedSellerItems, sellerItem, userKey));
                    t.Start();
                }
                return sellerItemJson;
            }
            else
                return null;

        }
        catch (Exception ex)
        {
            Logging.WriteLog(LogType.Error, ex.ToString());
            return null;
        }
    }
    private void UpdateItemsDetails()
    {
        int selectedItemsCode = int.Parse(hfSelectedChargeCode.Value);
        DataModelEntities entities = new DataModelEntities();
        ChargeCode code = entities.ChargeCodes.First(u => u.Charge_Code == selectedItemsCode);

        code.Ebay_Code = txtEbayCode.Value;
        code.Charge_Code_Name = txtChargeCode.Value;
        code.User_Code = int.Parse(ddlUser.SelectedValue);
        code.Modified_By = UserKey;
        code.Modified_Date = DateTime.Now;
        code.User_IP = Request.UserHostAddress;

        entities.SaveChanges();
        entities = null;

        BindCodes();
    }
    protected void btnAuthorizationBigcommerce_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            string url = txtBigcommerceStoreURL.Value.Trim();
            string startSlash = string.Empty;

            if (url.EndsWith("/") == false)
                startSlash = "/";

            if (url.StartsWith("https://") == false)
                url = "https://" + url;

            url += startSlash + "api/v2";

            string apiUserID = txtBigcommerceUserID.Value.Trim();
            string apiKey = txtBigcommerceKey.Value.Trim();

            // test provided credentials
            bool isValid = new BigcommerceHelper(UserKey).TestBigcommerceCredential(url, apiUserID, apiKey);

            if (isValid == true)
            {
                // save entry in database.
                DataModelEntities context = new DataModelEntities();

                // check if user is creating a new account, or updating existing one
                if (hfSelectedBigcommerceAccountID.Value == "0")
                {
                    UserAccount userAccount = new UserAccount();
                    userAccount.User_Code = UserKey;
                    userAccount.Account_Code = (int)Constant.Accounts.Bigcommerce;
                    userAccount.Application_Name = url;
                    userAccount.Config_Value1 = apiUserID;
                    userAccount.Config_Value2 = apiKey;
                    userAccount.Created_Date = DateTime.Now;
                    userAccount.Is_Active = true;
                    userAccount.User_IP = Request.UserHostAddress;
                    context.UserAccounts.AddObject(userAccount);
                }
                else
                {
                    int userAccountCode = Convert.ToInt32(hfSelectedBigcommerceAccountID.Value);
                    UserAccount userAccount = context.UserAccounts.First(u => u.Is_Active == true && u.Account_Code == (int)Constant.Accounts.Bigcommerce);
                    userAccount.Application_Name = url;
                    userAccount.Config_Value1 = apiUserID;
                    userAccount.Config_Value2 = apiKey;
                    userAccount.Modified_Date = DateTime.Now;
                    userAccount.User_IP = Request.UserHostAddress;

                }
                context.SaveChanges();

                bigcommerceConnect.Style["display"] = "none";
                bigcommerceConnected.Style["display"] = "block";
                bigcommerceError.Text = string.Empty;
                txtBigcommerceStoreURL.Value = "";
                txtBigcommerceUserID.Value = "";
                txtBigcommerceKey.Value = "";
            }
            else
            {
                bigcommerceError.Text = "URL or API credentials are not valid. Please check and try again";
            }
        }
    }
    public bool SendEmailNotifications()
    {
        try
        {
            string link = @"http://autopricemanager.com";//HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            DataModelEntities context = new DataModelEntities();
            DateTime date = System.DateTime.Now.AddDays(-2);
            List<User> users3 = context.Users.Where(u => u.Is_Active == true  && u.Is_Subscribed == true && EntityFunctions.TruncateTime(u.Created_Date) == date.Date ).ToList();
            date = System.DateTime.Now.AddDays(-6);
            List<User> users7 = context.Users.Where(u => u.Is_Active == true && u.Is_Subscribed == true && EntityFunctions.TruncateTime(u.Created_Date) == date.Date).ToList();
            date = System.DateTime.Now.AddDays(-12);
            List<User> users13 = context.Users.Where(u => u.Is_Active == true && u.Is_Subscribed == true && EntityFunctions.TruncateTime(u.Created_Date) == date.Date).ToList();
            date = System.DateTime.Now.AddDays(-19);
            List<User> users20 = context.Users.Where(u => u.Is_Active == true && u.Is_Subscribed == true && EntityFunctions.TruncateTime(u.Created_Date) == date.Date).ToList();

            if (users3.Count > 0)
            {
                System.Threading.Thread t = new System.Threading.Thread(() => SendEmailNotifications(users3, (int)Common.EmailTemplates.Day3, link, "Auto Price Manager - Hands FREE AUTO Pricing!"));
                t.Start();
            }

            if (users7.Count > 0)
            {
                System.Threading.Thread t = new System.Threading.Thread(() => SendEmailNotifications(users7, (int)Common.EmailTemplates.Day7, link, "Auto Price Manager - Take Back Control of your Business!"));
                t.Start();
            }

            if (users13.Count > 0)
            {
                System.Threading.Thread t = new System.Threading.Thread(() => SendEmailNotifications(users13, (int)Common.EmailTemplates.Day13, link, "Auto Price Manager - Your Account will close tomorrow!"));
                t.Start();
            }

            if (users20.Count > 0)
            {
                System.Threading.Thread t = new System.Threading.Thread(() => SendEmailNotifications(users13, (int)Common.EmailTemplates.Day20, link, "Auto Price Manager - Be Great to have you back!"));
                t.Start();
            }

            /*Lock/Suspend user after trial 14days if they dont pay */
            date = System.DateTime.Now.AddDays(-13);
            List<User> usersTrailEnded = context.Users.Where(u => u.Role_Code == 2 && u.Is_Active == true && EntityFunctions.TruncateTime(u.Created_Date) == date.Date && (u.Is_Paypal_Paid != true || u.Is_Paypal_Expired == true)).ToList();
            foreach (var user in usersTrailEnded)
            {
                user.Is_Locked = true;
            }
            context.SaveChanges();

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    private void UpdateUserDetails()
    {
        int selectedUserCode = int.Parse(hfUserCode.Value);
        DataModelEntities entities = new DataModelEntities();
        User user = entities.Users.First(u => u.User_Code == selectedUserCode);

        user.Full_Name = txtUserName.Value;
        user.Email_Address = txtEmailAddress.Value;
        user.Role_Code = int.Parse(ddlRole.SelectedValue);
        user.Package_Id = int.Parse(ddlPackage.SelectedValue);
        if (chkPassword.Checked == true)
            user.Password = Common.GetHash(txtPassword.Value);
        entities.SaveChanges();
        entities = null;

        BindUsers();
    }
    private void UpdateEbaySale(Manifest item)
    {
        DataModelEntities context = new DataModelEntities();
        UserAccount account;
        if (item.AccountID == string.Empty)
        {
            account = context.UserAccounts.Where(u => u.User_Code == UserKey & u.Account_Code == (int)Constant.Accounts.Ebay && u.Is_Active == true).OrderBy(u => u.User_Account_Code).First();
        }
        else
        {
            int userAccountCode = int.Parse(item.AccountID);
            account = context.UserAccounts.First(u => u.User_Account_Code == userAccountCode);
        }

        if (item.ItemID != string.Empty && item.TransactionID != string.Empty) // check if both itemID and transactionID are valid.
        {
            CompleteSaleResponseType response = new EbayServiceBL(UserKey).UpdateShippingInfo(item.ItemID, item.TransactionID, item.TrackingNumber, account.Config_Value1);
            if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.Warning)
            {
                // status updated
                lblUploadStatus.Text = "Success. Ebay Shipping Information updated";

                // delete from database too
                PriceManagerDAL.ParcelItem itemToDelete = context.ParcelItems.FirstOrDefault(f => f.User_Code == UserKey && f.TransactionID == item.TransactionID && f.ItemID == item.ItemID);
                if (itemToDelete != null)
                {
                    context.ParcelItems.DeleteObject(itemToDelete);
                    context.SaveChanges();
                }
            }
            else
            {
                // some error
                lblUploadStatus.Text = "Error!! " + response.Errors[0].LongMessage;
            }
        }
        else
        {
            lblSkippedItems.Text += item.TrackingNumber + ", ";
        }

        context = null;
    }
    private void AddNewUser()
    {
        User user = new User();
        user.Full_Name = txtUserName.Value;
        user.Email_Address = txtEmailAddress.Value;
        user.Password = Common.GetHash(txtPassword.Value);
        user.Role_Code = int.Parse(ddlRole.SelectedValue);
        user.Package_Id = int.Parse(ddlPackage.SelectedValue);
        user.Created_Date = DateTime.Now;

        user.Is_Active = true;

        DataModelEntities entities = new DataModelEntities();
        entities.AddToUsers(user);
        entities.SaveChanges();

        BindUsers();
    }
    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.";
            }

        }
    }
    public bool? SaveDefaultSettings(string editedSellerItems)
    {
        try
        {

            SellerItem item = (SellerItem)Common.Deserialize(editedSellerItems, typeof(SellerItem));
            int userCode = new Base().UserKey;
            DataModelEntities entities = new DataModelEntities();
            var user = entities.Users.FirstOrDefault(f => f.User_Code == userCode);
            if (user != null)
            {
                user.Ceiling_Price = item.Ceiling_Price;
                user.Floor_Price = item.Floor_Price;
                user.Algo = item.Algo;
                user.Minimum_Feedback = item.Minimum_Feedback;
                user.Maximum_Feedback = item.Maximum_Feedback;
                user.Minimum_Price = item.Minimum_Price;
                user.Maximum_Price = item.Maximum_Price;
                user.Minimum_Quantity = item.Minimum_Quantity;
                user.Maximum_Quantity = item.Maximum_Quantity;
                user.Inclued_Sellers = item.Inclued_Sellers;
                user.Exclude_Sellers = item.Exclude_Sellers;
                user.Maximum_Handling_Time = item.Maximum_Handling_Time;
                user.Is_Fixed_Price = item.Is_Fixed_Price;
                user.Is_Auctions = item.Is_Auctions;
                user.Is_Returns_Accepted = item.Is_Returns_Accepted;
                user.Is_Location_AU = item.Is_Location_AU;
                user.Is_Hide_Duplicates = item.Is_Hide_Duplicates;
                user.Is_Top_Rated_Only = item.Is_Top_Rated_Only;
                user.Exclude_Category_Codes = item.Exclude_Category_Codes;
                user.Include_Condtion_Codes = item.Include_Condtion_Codes;
                user.Less_To_Lowest_Price = item.Less_To_Lowest_Price;
                user.Is_Round_To_Nearest = item.Is_Round_To_Nearest;
                //user.Country_Code = item.Country_Code;
                user.LocatedIn = item.LocatedIn;
                entities.SaveChanges();
                return true;
            }
            return false;

        }
        catch (Exception ex)
        {
            Logging.WriteLog(LogType.Error, ex.ToString());
            return false;
        }
    }
    public void UpdateProductTitle(int sellerItemCode, ItemTitle itemTitle, ItemTitle oldTitle)
    {
        DataModelEntities context = new DataModelEntities();
           SellerItem sellerItem = context.SellerItems.First(f => f.Item_Code == sellerItemCode);

           EbayServiceBL service = new EbayServiceBL((int)sellerItem.User_Code, (int)sellerItem.Country_Code);
           string result = service.ReviseEbayItemTitle(sellerItem.Item_ID, itemTitle.Title, service.UserTokens[(int)sellerItem.User_Account_Code]);

           /*In case of success service returns null*/
           if (string.IsNullOrEmpty(result))
           {
           TitleHistory ph = new TitleHistory();
           ph.Item_Code = sellerItemCode;
           ph.New_Title = itemTitle.Title;
           ph.Old_Title = oldTitle == null ? sellerItem.Item_Name : oldTitle.Title;
           ph.Total_Sales = oldTitle == null ? sellerItem.Current_Sales : oldTitle.TotalSales;
           ph.Created_Date = System.DateTime.Now;
           context.TitleHistories.AddObject(ph);
           context.SaveChanges();
           Logging.WriteLog(LogType.Info, sellerItem.Item_ID + " Title revised.");
           }
           else
           Logging.WriteLog(LogType.Error, result);
    }
    protected void btnAuthorizationMagento_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            string url = txtMagentoStoreURL.Value.Trim();
            string startSlash = string.Empty;

            if (url.EndsWith("/") == false)
                startSlash = "/";

            if (url.StartsWith("http://") == false)
                url = "http://" + url;
            if (url.ToLower().Contains("index.php") == false)
                url += startSlash + "index.php/api/v2_soap/index/";
            else
                url += startSlash + "api/v2_soap/index/";

            string apiUserID = txtMagentoUserID.Value.Trim();
            string apiKey = txtMagentoKey.Value.Trim();

            bool isValid = new MagentoHelper(UserKey).TestMagentoCredentials(url, apiUserID, apiKey);

            if (isValid == true)
            {

                // save entry in database.
                DataModelEntities context = new DataModelEntities();

                // check if user is creating a new account, or updating existing one
                if (hfSelectedMagentoAccountID.Value == "0")
                {
                    UserAccount userAccount = new UserAccount();
                    userAccount.User_Code = UserKey;
                    userAccount.Account_Code = (int)Constant.Accounts.Magento;
                    userAccount.Application_Name = url;
                    userAccount.Config_Value1 = apiUserID;
                    userAccount.Config_Value2 = apiKey;
                    userAccount.Created_Date = DateTime.Now;
                    userAccount.Is_Active = true;
                    userAccount.User_IP = Request.UserHostAddress;

                    context.UserAccounts.AddObject(userAccount);
                }
                else
                {
                    int userAccountCode = Convert.ToInt32(hfSelectedMagentoAccountID.Value);
                    UserAccount userAccount = context.UserAccounts.First(u => u.Is_Active == true && u.Account_Code == (int)Constant.Accounts.Magento);
                    userAccount.Application_Name = url;
                    userAccount.Config_Value1 = apiUserID;
                    userAccount.Config_Value2 = apiKey;
                    userAccount.Modified_Date = DateTime.Now;
                    userAccount.User_IP = Request.UserHostAddress;

                }
                context.SaveChanges();

                magentoConnect.Style["display"] = "none";
                magentoConnected.Style["display"] = "block";
                lblMagentoError.Text = string.Empty;
            }
            else
            {
                lblMagentoError.Text = "URL or API credentials are not valid. Please check and try again";
            }
        }
    }
    public List<ParcelItem> GetPendingOrders(int userCode, int userAccountCode)
    {
        DataModelEntities context = new DataModelEntities();

        UserAccount userAccount = context.UserAccounts.First(u => u.User_Account_Code == userAccountCode);
        List<ChargeCode> chargeCodes = context.ChargeCodes.Where(u => u.Is_Active == true && u.User_Code == userCode).ToList();

        ShopifyAuthorizationState authState = new ShopifyAuthorizationState();
        authState.AccessToken = userAccount.Config_Value1;
        authState.ShopName = userAccount.Application_Name;

        ShopifyAPIClient api = new ShopifyAPIClient(authState);

        try
        {
            // by default JSON string is returned
            dynamic data = new JavaScriptSerializer().DeserializeObject(api.Get("/admin/orders.json?fulfillment_status=unshipped").ToString());

            List<PriceManagerDAL.ParcelItem> parcelItems = context.ParcelItems.Where(f => f.User_Code == userCode && f.UserAccount.Account_Code == (int)Constant.Accounts.Shopify && f.Is_Active == true).ToList();

            // delete all database entries
            foreach (PriceManagerDAL.ParcelItem existingItem in parcelItems)
            {
                context.ParcelItems.DeleteObject(existingItem);
            }
            context.SaveChanges();

            List<ParcelItem> items = new List<ParcelItem>();

            foreach (dynamic order in data["orders"])
            {
                foreach (dynamic lineItem in order["line_items"])
                {
                    ParcelItem item = new ParcelItem();

                    item.Type = "SHOPIFY";
                    item.AccountID = userAccount.User_Account_Code.ToString();
                    item.RecordNumber = order["order_number"].ToString();
                    item.ItemID = lineItem["id"].ToString();
                    item.TransactionID = order["id"].ToString();
                    item.ItemName = lineItem["title"];
                    item.CustomLabel = lineItem["sku"].ToString();
                    item.CustomLabelText = lineItem["sku"].ToString();

                    string state = order["shipping_address"]["province"];
                    string stateCode = order["shipping_address"]["province_code"];

                    if (StateHelper.States.Where(s => s.Key == stateCode).Count() > 0)
                        item.State = StateHelper.States[stateCode];
                    else
                        item.State = state;

                    item.BuyerName = order["customer"]["first_name"] + " " + order["customer"]["last_name"];
                    item.EmailAddress = order["email"];
                    item.BuyerID = order["customer"]["id"].ToString();

                    item.Street2 = order["shipping_address"]["address1"];
                    item.Street3 = order["shipping_address"]["address2"];
                    item.City = order["shipping_address"]["city"];
                    item.PostalCode = order["shipping_address"]["zip"].TrimStart('0');
                    item.Country = order["shipping_address"]["country_code"];
                    item.Phone = order["shipping_address"]["phone"];

                    item.Quantity = lineItem["quantity"];
                    if (order["shipping_lines"] != null)
                        item.ShippingCost = double.Parse(order["shipping_lines"][0]["price"]);
                    item.SaleRecordId = order["order_number"].ToString();

                    // insurance details //

                    item.Currency = order["currency"];
                    item.Price = double.Parse(lineItem["price"]);

                    item.Messages = GetMessageText(order["note"],order["created_at"]);

                    item.ShippingMethod = order["shipping_lines"][0]["title"];

                    string shippingCode = order["shipping_lines"][0]["code"];
                    ChargeCode code = chargeCodes.FirstOrDefault(u => shippingCode.ToLower().Contains(u.Ebay_Code.ToLower()) == true);
                    if (code != null && code.Charge_Code_Name.ToLower() == "ignore")
                    {
                        continue; // ignore the item
                    }

                    bool IspostCodeOK = Common.VerifyPostCode(order["shipping_address"]["zip"], order["shipping_address"]["city"]);
                    if (IspostCodeOK)
                        item.PostCodeImageURL = Constant.tickURL;
                    else
                        item.PostCodeImageURL = Constant.crossURL;

                    items.Add(item);
                }
            }

            return items;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    private void UpdateRoleDetails()
    {
        int selectedRoleCode = int.Parse(hfRoleCode.Value);
        DataModelEntities entities = new DataModelEntities();
        Role role = entities.Roles.First(u => u.Role_Code == selectedRoleCode);

        role.Role_Name = txtRoleName.Value;
        entities.SaveChanges();
        entities = null;

        BindRoles();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //StreamWriter stw = new StreamWriter(Server.MapPath("/Log/IPNstatus.txt"), true);
        //stw.WriteLine("INSTANT PAYPAL NOTIFICATION STARTED " + DateTime.Now.ToString());
        try
        {

            //Post back to either sandbox or live

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PayPal.GetPaypalServiceURL());

            //Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://*****:*****@"/site/Activation.aspx?vc=" + user.Confirmation_Code;
                                sendmail(user, link);
                            }
                            //stw.WriteLine("END OF SIGNUP");

                        } // FOR PAYMENT SECOND TIME
                        //else if (Users.Any(u => u.Paypal_Buyer_ID == PayPal_payer_id))//
                        else if (Users.Any(u => u.Paypal_Email_Address == PayPal_buyer_email))
                        {
                            // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S RECURRING PAYMEN OCCURS OR THE USER RE SUBSCRIBES

                            //stw.WriteLine("RECURING SUBSCRIPTION " + DateTime.Now.ToString());
                            //stw.WriteLine(Request.Params.ToString());
                            //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id);
                            User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email);
                            user.Is_Paypal_Paid = true;
                            user.Is_Active = true;
                            user.Is_Locked = false;
                            //==== INSERT SUBSCRIPTION DETAIL
                            Subscription sub = new Subscription();
                            sub.User_Code = user.User_Code;
                            sub.PayPal_Email_Address = PayPal_buyer_email;
                            //stw.WriteLine("RECURRING PAYMENT");
                            try
                            {
                                //Paypal_mc_gross = decimal.Parse(Request["mc_amount3"].ToString());

                                Paypal_mc_gross = decimal.Parse(Request["mc_gross"].ToString());
                            }
                            catch
                            {
                            }
                            // PACKAGE UPDATION

                            sub.Package_Id = int.Parse(paypal_item_id);
                            sub.Amount = Paypal_mc_gross;
                            sub.Transaction_Id = Paypal_txn_id.ToString();
                            sub.Subscription_Date = DateTime.Now;
                            sub.Paypal_Buyer_ID = PayPal_payer_id;
                            //  ConvertFromPayPalDate(Paypal_subscr_date, 0);
                            sub.Expiry_Date = DateTime.Now.AddMonths(1);
                            entites.Subscriptions.AddObject(sub);
                            entites.SaveChanges();

                        }
                    }
                    else if (Paypal_txn_type == "subscr-failed")
                    {
                        // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S RECURRING PAYMENT WILL BE FAILED DUE TO INSUFFICIENT BALANCE
                        //stw.WriteLine("RECURRING FAILED SUBSCRIPTION " + DateTime.Now.ToString());
                        //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id);
                        User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email);
                        user.Is_Paypal_Paid = false;
                        user.Is_Locked = true;
                        ////==== DELETE SUBSCRIPTION DETAILsu
                        //List<Subscription> subs = entites.Subscriptions.ToList();
                        //entites.Subscriptions.Where(w => w.Paypal_Buyer_ID == PayPal_payer_id)
                        //.ToList().ForEach(entites.Subscriptions.DeleteObject);
                        entites.SaveChanges();
                        //stw.WriteLine("CANCEL FAILED CoMNPLETED" + DateTime.Now.ToString());
                        //==== SEND ACTIVATION EMAIL TO THE USER AFTER PAYMENT PROCESSING
                        sendmailFailure(user.Full_Name, user.Email_Address, user.Full_Name, user.Password, user.Confirmation_Code);

                    }
                    else if (Paypal_txn_type == "subscr_cancel")
                    {
                        // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S CANCEL THE SUBSCRIPTION
                        //stw.WriteLine("CANCEL SUBSCRIPTION " + DateTime.Now.ToString());
                        //User user = Users.Single(u => u.Paypal_Buyer_ID == PayPal_payer_id);
                        User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email);
                        user.Is_Paypal_Paid = false;
                        user.Is_Active = false;
                        entites.SaveChanges();
                        sendmailCancelSubscription(user.Full_Name, user.Email_Address, user.Full_Name, user.Password, user.Confirmation_Code);

                        //stw.WriteLine("CANCEL SUBSCRIPTION CoMNPLETED" + DateTime.Now.ToString());

                    }
                    //}
                    //else
                    //{

                    //}

                }
                catch (Exception ex)
                {
                    //stw.WriteLine(ex.Message);
                    //stw.Dispose();
                    Email.SendMail("*****@*****.**", "Test IPN", ex.ToString(), null);
                }

                //stw.Dispose();

            }
            else if (strResponse == "INVALID")
            {
                // THIS BLOCK OF CODE WILL BE HIT WHEN THE USER'S PAYPAL PROCESS IS INVALID
                UTF8Encoding en = new UTF8Encoding();
                string input = en.GetString(param);
                //StreamWriter stw = new StreamWriter(Server.MapPath("status.txt"), true);

                //stw.WriteLine("Invalid " + DateTime.Now.ToString());
                // CANCEL SUBSCTIPION AS USER DONT HAVE FUNDS
                if (Users.Any(u => u.Paypal_Buyer_ID == PayPal_payer_id && u.Is_Active == true))
                {
                    //stw.WriteLine("invalid SUBSCRIPTION " + DateTime.Now.ToString());
                    User user = Users.Single(u => u.Paypal_Email_Address == PayPal_buyer_email);
                    user.Is_Paypal_Paid = false;
                    user.Is_Locked = true;
                    entites.SaveChanges();
                    //==== SEND ACTIVATION EMAIL TO THE USER AFTER PAYMENT PROCESSING

                }

                //stw.Dispose();
            }
            else
            {
                //log response/ipn data for manual investigation

            }
            //stw.Dispose();
        }
        catch (Exception ee)
        {
            ////stw.WriteLine(DateTime.Now.ToString());
            ////stw.WriteLine(ee.ToString());
            //stw.Dispose();
            //Logging.WriteLog(LogType.Critical, ee.ToString());
            Email.SendMail("*****@*****.**", "Test IPN", ee.ToString(), null);
        }
    }