示例#1
0
        public ActionResult RemoveRule(int ID, int Num, string systemName, string prefix)
        {
            var rules = DiscountService.GetRules();

            if (string.IsNullOrEmpty(systemName) || !rules.ContainsKey(systemName))
            {
                return(Content(RP.T("Admin.Discount.RuleNotFound").ToString()));
            }
            var rule  = rules[systemName];
            var saved = rule.GetConfigItem();

            MapModel(saved);
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

            var discount = _db.Discounts.FirstOrDefault(x => x.ID == ID);

            if (discount != null)
            {
                for (var i = 1; i <= discount.RuleList.Count; i++)
                {
                    if (i == Num)
                    {
                        discount.RuleList.RemoveAt(i - 1);
                        break;
                    }
                }
            }
            //js.Serialize();
            discount.RulesData = js.Serialize(discount.RuleList);
            _db.SaveChanges();
            return(Json(new { result = "ok" }));
        }
示例#2
0
        public ActionResult OrderAjax([DataSourceRequest] DataSourceRequest request)
        {
            if (!LS.isHaveID())
            {
                return(Json(new { }));
            }
            //kendo reset manual sort to default =(
            if (request.Sorts == null)
            {
                request.Sorts = new List <SortDescriptor>();
            }
            if (request.Sorts.Count == 0)
            {
                request.Sorts.Add(new SortDescriptor("OrderStatus",
                                                     System.ComponentModel.ListSortDirection.Ascending));
                request.Sorts.Add(new SortDescriptor("ID",
                                                     System.ComponentModel.ListSortDirection.Descending));
            }
            var items = _db.Orders.Where(x => x.UserID == LS.CurrentUser.ID && !x.RegularOrder);

            DataSourceResult result = items.ToDataSourceResult(request);

            foreach (var item in (IEnumerable <Order>)result.Data)
            {
                item.TotalStr           = ShoppingService.FormatPrice(item.Total);
                item.RegularIntervalStr = RP.T("Enums." + item.RegularInterval.ToString()).ToString();
                item.OrderStatusStr     = RP.T("Enums." + item.OrderStatus.ToString()).ToString();
            }
            return(Json(result));
        }
示例#3
0
        public ActionResult SaveNewRule(int ID, string systemName, string prefix)
        {
            var rules = DiscountService.GetRules();

            if (string.IsNullOrEmpty(systemName) || !rules.ContainsKey(systemName))
            {
                return(Content(RP.T("Admin.Discount.RuleNotFound").ToString()));
            }
            var rule  = rules[systemName];
            var saved = rule.GetConfigItem();

            MapModel(saved, prefix);
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

            var discount = _db.Discounts.FirstOrDefault(x => x.ID == ID);

            if (discount != null)
            {
                discount.RuleList.Add(new JsonKeyValue()
                {
                    Name  = systemName,
                    Value = js.Serialize(saved)
                });
            }
            //js.Serialize();
            discount.RulesData = js.Serialize(discount.RuleList);
            _db.SaveChanges();
            return(Json(new { result = "ok" }));
        }
示例#4
0
        public ActionResult DiscountRuleList(int ID)
        {
            var discount = _db.Discounts.FirstOrDefault(x => x.ID == ID);

            if (discount != null)
            {
                var list  = new List <JsonKeyObject>();
                var rules = DiscountService.GetRules();
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

                foreach (var r in discount.RuleList)
                {
                    if (rules.ContainsKey(r.Name))
                    {
                        var ruleprovider = rules[r.Name];
                        var confitem     = ruleprovider.GetConfigItem();
                        var o            = js.Deserialize(r.Value, confitem.GetType());
                        list.Add(new JsonKeyObject()
                        {
                            Name   = r.Name,
                            Object = o
                        });
                    }
                }

                return(PartialView(list));
            }
            return(Content(RP.T("Admin.Discount.NotFound").ToString()));
        }
 public ActionResult Contact(int?ID)
 {
     if (ID.HasValue)
     {
         if (TempData["ViewData"] != null)
         {
             ViewData = (ViewDataDictionary)TempData["ViewData"];
         }
         Contact contact = new Contact();
         var     shop    = LS.GetFirst <Shop>(x => x.ID == ID);
         if (shop != null)
         {
             contact.DropDownItems = new List <string> {
                 RP.T("Views.Shared.Contact.DropDownOneText").ToString(),
                 RP.T("Views.Shared.Contact.DropDownTwoText").ToString(),
                 RP.T("Views.Shared.Contact.DropDownThreeText").ToString(),
             };
             if (!string.IsNullOrEmpty(shop.Theme))
             {
                 this.HttpContext.Items["ShopTheme"] = shop.Theme;
             }
             contact.Shop = shop;
             return(View(contact));
         }
     }
     return(Redirect("~/Landing/Main/Index.html"));
 }
 public ActionResult LogOnAjx(LogOnModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (Membership.ValidateUser(model.UserName, model.Password))
         {
             var u = _db.Users.FirstOrDefault(x => x.UserName == model.UserName);
             LS.Authorize(u);
             bool haveOld = false;
             if (LS.CurrentHttpContext.Request.Cookies["SALcart"] != null)
             {
                 haveOld = true;
             }
             if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                 !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
             {
                 return(Json(new { result = "ok", url = returnUrl, haveOld = haveOld }));
             }
             else
             {
                 return(Json(new { result = "ok", haveOld = haveOld, url = Url.Action("DomainPage", "Page", new { name = "root" }) }));
                 //  eturn RedirectToAction("DomainPage", "Page", new { name = "root" });
             }
         }
         else
         {
             ModelState.AddModelError("", RP.T("Account.Logon.PasswordOrUserIncorrect").ToString());
         }
     }
     return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
     //  return View(model);
 }
        public ActionResult CSVExport([DataSourceRequest] DataSourceRequest request)
        {
            Expression <Func <Order, bool> > predicate = x => true
                                                         //  && x.OrderStatus != OrderStatus.New
                                                         // && x.OrderStatus != OrderStatus.Canceled
                                                         //  && x.OrderStatus != OrderStatus.Rejected
            ;

            if (request.Filters != null)
            {
                predicate = GetPredicate(predicate, request.Filters);
            }
            var items = _db.Orders.Where(predicate).Select(x => new PaymentReportItemModel()
            {
                ID            = x.ID,
                ShopID        = x.ShopID,
                IsPaidUp      = x.IsPaidUp,
                OrderID       = x.ID,
                Date          = x.CreateOn,
                PaymentMethod = x.PaymentMethod,
                Total         = x.Total
            }).ToList();

            foreach (var item in items)
            {
                item.Total            = item.Cash + item.Card;
                item.TotalStr         = ShoppingService.FormatPrice(item.Total);
                item.PayedTo          = item.Card > 0 ? PayedToType.ToAdmin : PayedToType.ToShop;
                item.PayedToStr       = RP.T("Enums." + item.PayedTo.ToString()).ToString();
                item.PaymentMethodStr = RP.T("Enums." + item.PaymentMethod.ToString()).ToString();
                item.DateStr          = item.Date.HasValue ? item.Date.Value.ToString("dd/MM HH:mm") : "";
            }
            // var items = _db.AbstractPages.Where(r => r.Visible == true).OrderBy(r => r.Title).ToList();
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            writer.Write(RP.M("PaymentReportItemModel", "OrderID") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "Date") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "Total") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "PaymentMethod") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "PayedTo"));
            writer.WriteLine();
            var csvQuote = "\"";

            foreach (var item in items)
            {
                writer.Write(item.OrderID); writer.Write(",\"");
                writer.Write(item.DateStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.TotalStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.PaymentMethodStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.PayedToStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\"");
                writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;
            Encoding heb = Encoding.GetEncoding("windows-1255");

            return(File(heb.GetBytes(new StreamReader(output).ReadToEnd()), "text/csv", "PaymentReport_" + (DateTime.Now.ToString("dd/MM HH:mm")) + ".csv"));
        }
 public ActionResult _AjaxPaymentMarkAsPaid(List <int> IDs)
 {
     if (IDs != null)
     {
         var orders = _db.Orders.Where(x => IDs.Contains(x.ID)).ToList();
         foreach (var o in orders)
         {
             o.IsPaidUp = true;
         }
         _db.SaveChanges();
     }
     return(Json(new { result = "ok", message = RP.T("Admin.Main._AjaxPaymentMarkAsPaid.MarkedSuccess").ToString() }));
 }
示例#9
0
        public ActionResult NewRule(string RuleName)
        {
            var rules = DiscountService.GetRules();

            if (string.IsNullOrEmpty(RuleName) || !rules.ContainsKey(RuleName))
            {
                return(Content(RP.T("Admin.Discount.RuleNotFound").ToString()));
            }
            var rule  = rules[RuleName];
            var model = rule.GetConfigItem();

            return(PartialView(model));
        }
        public ActionResult ShopProfile(Shop shop)
        {
            if (CurrentShop == null)
            {
                return(Content("Shop not found. Please register"));
            }
            if (shop.ID == CurrentShop.ID)
            {
                CurrentShop.Address         = shop.Address;
                CurrentShop.AddressMap      = shop.AddressMap;
                CurrentShop.RadiusLatitude  = shop.RadiusLatitude;
                CurrentShop.RadiusLongitude = shop.RadiusLongitude;
                CurrentShop.DisplayOrder    = shop.DisplayOrder;
                CurrentShop.Email           = shop.Email;
                CurrentShop.FullDescription = shop.FullDescription;
                CurrentShop.Image           = shop.Image;
                CurrentShop.Kosher          = shop.Kosher;
                CurrentShop.Latitude        = shop.Latitude;
                CurrentShop.Longitude       = shop.Longitude;
                CurrentShop.Name            = shop.Name;
                CurrentShop.Phone           = shop.Phone;
                CurrentShop.ShipCost        = shop.ShipCost;
                CurrentShop.FreeShipFrom    = shop.FreeShipFrom;
                //CurrentShop.ShipHourFrom = shop.ShipHourFrom;
                //CurrentShop.ShipHourTo = shop.ShipHourTo;
                CurrentShop.ShipRadius = shop.ShipRadius;
                //CurrentShop.ShopTypeID = shop.ShopTypeID;
                CurrentShop.ShopTypeIDs      = shop.ShopTypeIDs;
                CurrentShop.ShortDescription = shop.ShortDescription;
                //CurrentShop.TraidingDayFrom = shop.TraidingDayFrom;
                //CurrentShop.TraidingDayTo = shop.TraidingDayTo;
                //CurrentShop.TraidingHourFrom = shop.TraidingHourFrom;
                //CurrentShop.TraidingHourTo = shop.TraidingHourTo;
                CurrentShop.Youtube = shop.Youtube;
                CurrentShop.Active  = shop.Active;
                CurrentShop.DeliveryManualDescription = shop.DeliveryManualDescription;
                CurrentShop.DeliveryTime         = shop.DeliveryTime;
                CurrentShop.InStorePickUpEnabled = shop.InStorePickUpEnabled;
                CurrentShop.IsShipEnabled        = shop.IsShipEnabled;
                CurrentShop.Theme   = shop.Theme;
                CurrentShop.FavIcon = shop.FavIcon;
                _db.SaveChanges();

                ViewBag.MessageGreen = RP.T("Member.Controlers.MainController.Saved").ToString();
            }
            return(View(CurrentShop));
        }
        public ActionResult _AddContactData(int shopID, Contact model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserActivityService.InsertShopContact(LS.CurrentUser.ID, shopID
                                                          , model.ContactData,
                                                          model.ContactEmail,
                                                          model.ContactName
                                                          , model.ContactPhone
                                                          , model.DropDownItems

                                                          , Request.RawUrl,
                                                          Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                          , LS.GetUser_IP(Request)
                                                          );


                    model.ContactData = RP.T("Views.Shared.Contact.DropDownChooseText").ToString().ToLower() + ": " + model.ContactData;
                    if (model.DropDownItems.Count > 0)
                    {
                        model.ContactData = model.ContactData + "<br />" +
                                            RP.T("Views.Shared.Contact.TextAreaPlaceholder").ToString().ToLower() + ": " + model.DropDownItems.FirstOrDefault();
                    }
                    model.ContactDate    = DateTime.Now;
                    model.ContactReferal = SF.GetCookie("Referal");
                    model.ContactUrl     = "<a target='_blank' href='" + Request.UrlReferrer.ToString() + "'>" + Request.UrlReferrer.ToString() + "</a>";
                    model.RoleDefault    = "Member";
                    ShoppingService.AddContact(model);

                    return(Redirect("/c/contact-sent"));
                }
                catch (Exception exc)
                {
                    SF.LogError(exc);
                }
            }
            TempData["ViewData"] = ViewData;
            return(RedirectToAction("Contact", new { ID = shopID }));
        }
示例#12
0
 public IHtmlString T(string text)
 {
     return(RP.T(text));
 }
        public ActionResult _AjaxPaymentReport([DataSourceRequest] DataSourceRequest request)
        {
            if (CurrentShop == null)
            {
                return(Json(new {}));
            }
            //kendo reset manual sort to default =(
            if (request.Sorts.Count == 0)
            {
                request.Sorts.Add(new SortDescriptor("ID",
                                                     System.ComponentModel.ListSortDirection.Descending));
            }
            Expression <Func <Order, bool> > predicate = x => x.ShopID == CurrentShop.ID
                                                         //  && x.OrderStatus != OrderStatus.New
                                                         // && x.OrderStatus != OrderStatus.Canceled
                                                         //  && x.OrderStatus != OrderStatus.Rejected
            ;
            var items = _db.Orders.Where(predicate)
                        .Select(x => new PaymentReportItemModel()
            {
                ID            = x.ID,
                ShopID        = x.ShopID,
                IsPaidUp      = x.IsPaidUp,
                OrderID       = x.ID,
                Date          = x.CreateOn,
                PaymentMethod = x.PaymentMethod,
                Total         = x.Total,
            });

            DataSourceResult result = items.ToDataSourceResult(request);

            foreach (var item in (IEnumerable <PaymentReportItemModel>)result.Data)
            {
                item.Total            = item.Cash + item.Card;
                item.TotalStr         = ShoppingService.FormatPrice(item.Total);
                item.PayedTo          = item.PaymentMethod == PaymentMethod.Credit ? PayedToType.ToAdmin : PayedToType.ToShop;
                item.PayedToStr       = RP.T("Enums." + item.PayedTo.ToString()).ToString();
                item.PaymentMethodStr = RP.T("Enums." + item.PaymentMethod.ToString()).ToString();
                item.DateStr          = item.Date.HasValue ? item.Date.Value.ToString("dd/MM HH:mm") : "";
            }

            //prepare report model
            var model = new PaymentReportModel();

            //prepare filters, get from kendo grid filter
            if (request.Filters != null)
            {
                predicate = GetPredicate(predicate, request.Filters);
            }
            model.TotalShop = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.CreditShopOwner && !x.LessFee)
                              .Select(x => x.Total).DefaultIfEmpty(0).Sum();
            model.TotalShop += _db.Orders.Where(predicate).Where(x => !x.LessFee).Select(x => x.Total).DefaultIfEmpty(0).Sum();
            var totalSpecial = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.CreditShopOwner && x.LessFee)
                               .Select(x => x.Total).DefaultIfEmpty(0).Sum();

            totalSpecial += _db.Orders.Where(predicate).Where(x => x.LessFee).Select(x => x.Total).DefaultIfEmpty(0).Sum();


            model.TotalAdmin = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.Credit)
                               .Select(x => x.Total).DefaultIfEmpty(0).Sum();

            var     date1     = items.Where(x => x.Date.HasValue).Select(x => x.Date.Value).DefaultIfEmpty(DateTime.Now).Max();
            var     date2     = items.Where(x => x.Date.HasValue).Select(x => x.Date.Value).DefaultIfEmpty(DateTime.Now).Min();
            int     mouthes   = ((date1.Year - date2.Year) * 12) + date1.Month - date2.Month;
            decimal mounthFee = CurrentShop.MounthlyFee * mouthes;

            model.TotalFee   = (model.TotalShop * CurrentShop.PercentFee / 100) - model.TotalAdmin + mounthFee;
            model.TotalFee  += (totalSpecial * CurrentShop.SpecialPercentFee / 100);
            model.TotalShop += totalSpecial;
            // if (model.TotalFee < 0) { model.TotalFee = 0; }

            model.TotalAdminStr = ShoppingService.FormatPrice(model.TotalAdmin);
            model.TotalShopStr  = ShoppingService.FormatPrice(model.TotalShop);
            model.TotalFeeStr   = ShoppingService.FormatPrice(model.TotalFee);


            return(Json(new { result.Data, result.AggregateResults, result.Errors, result.Total, model }));
        }
        public ActionResult _GetProductByCategoryAndFilters(int shopID, int?categoryID, int[] filters, string viewIn = "gallery", int skip = 0, int take = 20,
                                                            string keywords        = null,
                                                            bool showFirstCategory = false,
                                                            bool isBestSelling     = false, string productName = "", bool refreshFilters = true, bool isForSpider = false)
        {
            List <SpecificationOptionModel>    specifications = null;
            IEnumerable <ProductOverviewModel> data;
            var profiler = MiniProfiler.Current;

            using (profiler.Step("Step Controller _ByCategoryAndFilters"))
            {
                if (string.IsNullOrEmpty(productName))
                {
                    if (showFirstCategory)
                    {
                        //var sc = LS.Get<ShopCategory>().OrderBy(x => x.DisplayOrder).Where(x => x.Published).FirstOrDefault();
                        //var category1 = LS.Get<Category>().ToList();

                        var sc = LS.Get <ShopCategoryMenu>().FirstOrDefault(x => x.ShopID == shopID && x.Published == true && x.Level == 0);


                        if (sc != null)
                        {
                            categoryID = sc.CategoryID;
                        }
                        else
                        {
                            var shopCatMap = LS.Get <ShopCategory>().Where(x => x.Published);

                            var shc = shopCatMap.OrderBy(x => x.DisplayOrder).FirstOrDefault();
                            if (shc != null)
                            {
                                categoryID = shc.CategoryID;
                            }
                        }
                    }
                    bool FeautureTop = false;
                    if (!categoryID.HasValue &&
                        (filters == null || filters.Length == 0) &&
                        string.IsNullOrEmpty(keywords) &&
                        !isBestSelling
                        )
                    {
                        FeautureTop = true;
                    }
                    data = LS.SearchProducts(
                        shopID: shopID,
                        options: out specifications,
                        page: isForSpider ? 1 : (skip / take) + 1,
                        limit: isForSpider ? -1 : take,
                        categoryID: categoryID,
                        filters: filters,
                        loadSpecifications: skip == 0,
                        keywords: keywords,
                        isBestSelling: isBestSelling,
                        featuredTop: FeautureTop,
                        showDiscounts: true);

                    foreach (var d in data)
                    {
                        //d.ProductNoteText = ShoppingService.GetUserNoteForProduct(d.ProductID, LS.CurrentUser.ID);
                    }
                }
                else
                {
                    data = LS.SearchProducts(shopID, out specifications, (skip / take) + 1, take
                                             // , categoryID: categoryID
                                             // , filters: filters
                                             //, loadSpecifications: skip == 0,
                                             , productName: productName
                                             //, isBestSelling: isBestSelling
                                             // , featuredTop: FeautureTop
                                             , showDiscounts: true
                                             );
                }


                ViewBag.LastProductNum = skip + take; //data.Count();
                ViewBag.Specifications = specifications;
                ViewBag.RefreshFilters = refreshFilters;
                ViewBag.CategoryID     = categoryID;
                if (categoryID.HasValue)
                {
                    var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == categoryID.Value);
                    if (cat != null)
                    {
                        ViewBag.Category = cat;
                    }
                }
                if (!string.IsNullOrEmpty(productName) && data.Count() == 0 || !string.IsNullOrEmpty(keywords) && data.Count() == 0)
                {
                    return(Json(new
                    {
                        status = "productNotFound",
                        localizationMessage = RP.T("ShopController.SearchMessage.ProductNotFound").ToString(),
                        localizationTextComponent = RP.Text("ShopController.SearchMessage.ProductNotFoundComponent").ToString()
                    }, JsonRequestBehavior.AllowGet));
                }
            }

            if (data.Count() == 0)
            {
                return(Content(string.Empty));
            }
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == shopID);

            if (shop != null)
            {
                if (!string.IsNullOrEmpty(shop.Theme))
                {
                    this.HttpContext.Items["ShopTheme"] = shop.Theme;
                }
                ViewBag.Shop = shop;
            }
            switch (viewIn)
            {
            case "gallery":
                return(PartialView("_ProductsGallery", data));

            case "table":
                return(PartialView("_ProductsTable", data));

            case "tableItemPartial":
                return(PartialView("_ProductTableItem", data));
            }
            return(Content(string.Empty));
        }
 public string GetLocalizeRuleName(string systemName)
 {
     return(RP.T("Discount.Name." + systemName).ToString());
 }
        public ActionResult FacebookAjx(string token)
        {
            try
            {
                if (!string.IsNullOrEmpty(token))
                {
                    WebClient client     = new WebClient();
                    string    JsonResult = client.DownloadString(string.Concat(
                                                                     "https://graph.facebook.com/me?access_token=", token));

                    JObject jsonUserInfo = JObject.Parse(JsonResult);

                    FacebookProfile fp = new FacebookProfile();
                    fp.FacebookUsername = jsonUserInfo.Value <string>("username");
                    fp.FacebookEmail    = jsonUserInfo.Value <string>("email");
                    fp.FacebookLocale   = jsonUserInfo.Value <string>("locale");
                    fp.FacebookID       = jsonUserInfo.Value <long>("id");
                    fp.FacebookToken    = token;

                    fp.FacebookName        = jsonUserInfo.Value <string>("name");
                    fp.FacebookFirstName   = jsonUserInfo.Value <string>("first_name");
                    fp.FacebookLastName    = jsonUserInfo.Value <string>("last_name");
                    fp.FacebookLink        = jsonUserInfo.Value <string>("link");
                    fp.FacebookGender      = jsonUserInfo.Value <string>("gender");
                    fp.FacebookTimezone    = jsonUserInfo.Value <int>("timezone");
                    fp.FacebookVerified    = jsonUserInfo.Value <bool>("verified");
                    fp.FacebookUpdatedTime = jsonUserInfo.Value <DateTime>("updated_time");

                    User uLogin = _db.Users.FirstOrDefault(r => r.FacebookID == fp.FacebookID);
                    if (uLogin != null)
                    {
                        //login
                        LS.Authorize(uLogin);
                        // var messService = new MessageService(_db);
                        // messService.SendUserRegisterEmailToUser(u);
                        return(Json(new { result = "ok", url = "" }));
                    }
                    else
                    {
                        //register
                        string email = fp.FacebookEmail;
                        //generate code
                        var chars    = "0123456789abcdefghjklmnopqrstuwvxyzQAZWSXEDCRFVTGBYHNUJMIKLOP@$&%";
                        var random   = new Random();
                        var password = new string(
                            Enumerable.Repeat(chars, 8)
                            .Select(s => s[random.Next(s.Length)])
                            .ToArray());
                        if (string.IsNullOrEmpty(email))
                        {
                            if (!string.IsNullOrEmpty(fp.FacebookUsername))
                            {
                                email = fp.FacebookUsername + "@facebook.com";
                            }
                            else
                            {
                                email = fp.FacebookID.ToString() + "@facebook.com";
                            }
                        }
                        User uExist = _db.Users.FirstOrDefault(r => r.UserName == email);
                        if (uExist != null)
                        {
                            uExist.FacebookID = fp.FacebookID;
                            _db.SaveChanges();//update facebook ID
                            //login
                            LS.Authorize(uExist);

                            return(Json(new { result = "ok", url = "" }));
                        }
                        MembershipCreateStatus createStatus;
                        MembershipUser         newUser = Membership.CreateUser(email, password, email, "-", "-", true, out createStatus);

                        if (createStatus != MembershipCreateStatus.Success)
                        {
                            ModelState.AddModelError(string.Empty, RP.T("Account.Register.Error." + createStatus.ToString()).ToString());
                        }
                        else
                        {
                            User u = _db.Users.FirstOrDefault(r => r.UserName == email);
                            u.Roles            = SF.RolesStringAdd(u.Roles, "Register");
                            u.FirstName        = fp.FacebookFirstName;
                            u.LastName         = fp.FacebookLastName;
                            u.RoleDefault      = "Register";
                            u.FacebookID       = fp.FacebookID;
                            u.IsApproved       = true;
                            _db.Entry(u).State = EntityState.Modified;
                            _db.SaveChanges();

                            Newsletter n = new Newsletter()
                            {
                                NewsletterAccept = true,
                                NewsletterDate   = DateTime.UtcNow,
                                NewsletterEmail  = u.Email,
                                NewsletterName   = u.FirstName + " " + u.LastName,
                                RoleDefault      = "Register"
                            };
                            _db.Newsletters.Add(n);
                            _db.SaveChanges();
                            SF.AddToNewsletter(n);

                            if (Membership.ValidateUser(u.UserName, u.Password))
                            {
                                LS.Authorize(u);
                                var messService = new MessageService(_db);

                                messService.SendUserRegisterEmailToUser(u);
                                return(Json(new { result = "ok", url = "" }));
                            }
                            else
                            {
                                ModelState.AddModelError("", RP.T("Account.Logon.PasswordOrUserIncorrect").ToString());
                            }
                        }
                    }
                    return(Json(new { result = "error", json = JsonResult, facebook = fp, message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
                }
                return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
            }
            catch (Exception error)
            {
                SF.LogError(error);
                return(Json(new { result = "error", message = error.Message }));
            }
        }
示例#17
0
        //private static UiResources ui = new UiResources(); // database class
        protected override ModelMetadata CreateMetadata(
            IEnumerable <Attribute> attributes,
            Type containerType,
            Func <object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            ModelMetadata baseres = null;

            try
            {
                baseres = base.CreateMetadata
                              (attributes, containerType, modelAccessor, modelType, propertyName);
            }
            catch (Exception e)
            {
                baseres = base.CreateMetadata
                              (new List <Attribute>(), containerType, modelAccessor, modelType, propertyName);
            }
            string sKey           = string.Empty; //  ощощ мчбмъ дтшк щм displayname
            string tab            = string.Empty;
            string sLocalizedText = string.Empty; // ощъощ мчбм тшк оъешвн

            HttpContext.Current.Application.Lock();
            string keyType = "";

            if (containerType != null)
            {
                keyType = containerType.Name;
                if (containerType.BaseType != null && containerType.BaseType == typeof(AbstractPage))
                {
                    keyType = containerType.BaseType.Name;
                }
            }
            bool?  hideTab = null;
            string currole = null;

            if (HttpContext.Current != null)
            {
                var controller = HttpContext.Current.Items["controllerInstance"] as BaseController;
                if (controller != null)
                {
                    currole = controller.ViewBag.CurrentRole;
                }
            }
            if (containerType != null && propertyName != null)
            {
                var modelAttr = containerType.GetProperty(propertyName).GetCustomAttributes <ModelAttribute>()
                                .Where(x => x.Role == currole || x.Role == null).OrderByDescending(x => x.Role).ToList().FirstOrDefault();

                if (modelAttr != null)
                {
                    if (!hideTab.HasValue && !modelAttr.ShowInEdit && !modelAttr.Edit)
                    {
                        hideTab = true;
                    }
                }
            }
            foreach (var attr in attributes)
            {
                if (attr != null)
                {
                    string typeName   = attr.GetType().Name; // ощйв аъ сев дтшк мгевоа DisplayAttribute
                    string attrAppKey = string.Empty;

                    if (typeName.Equals("DisplayAttribute"))
                    {
                        sKey = ((DisplayAttribute)attr).Name;
                        var tabKey = ((DisplayAttribute)attr).Prompt;
                        //if (tabKey != null && tabKey.StartsWith("Tab"))
                        //{
                        //    tabKey = tabKey.Substring("Tab".Length);
                        //}


                        if (!string.IsNullOrEmpty(tabKey))
                        {
                            // attrAppKey = string.Format("{0}-{1}-{2}", containerType.Name, propertyName, typeName);

                            if (RP.Mbool(out tabKey, keyType, ((DisplayAttribute)attr).Prompt, "Prompt"))
                            {
                                // rewriteTab = true;
                                baseres.Watermark = tabKey;
                                //((DisplayAttribute)attr).ResourceType = null;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(tabKey) && tabKey != baseres.Watermark)
                                {
                                    RP.Madd(keyType, tabKey, "Prompt", baseres.Watermark);
                                }
                            }
                        }
                    }
                    //else if (attr is ValidationAttribute)
                    //{
                    //    sKey = ((ValidationAttribute)attr).ErrorMessage;

                    //    if (!string.IsNullOrEmpty(sKey))
                    //    {
                    //        attrAppKey = string.Format("{0}-{1}-{2}", containerType.Name, propertyName, typeName);


                    //        ((ValidationAttribute)attr).ErrorMessage = sKey;
                    //    }
                    //}
                    else if (attr is ValidationAttribute)
                    {
                        sKey = ((ValidationAttribute)attr).ErrorMessage;

                        if (!string.IsNullOrEmpty(sKey))
                        {
                            attrAppKey = string.Format("{0}-{1}-{2}",
                                                       keyType, propertyName, typeName);
                            if (HttpContext.Current.Application[attrAppKey] == null)
                            {
                                HttpContext.Current.Application[attrAppKey] = sKey;
                            }
                            else
                            {
                                sKey = HttpContext.Current.Application[attrAppKey].ToString();
                            }

                            sLocalizedText = RP.T(sKey).ToString();
                            if (string.IsNullOrEmpty(sLocalizedText))
                            {
                                sLocalizedText = sKey;
                            }

                            ((ValidationAttribute)attr).ErrorMessage = sLocalizedText;
                        }
                    }
                }
            }


            if (!string.IsNullOrEmpty(sKey))
            {
                // attrAppKey = string.Format("{0}-{1}-{2}", containerType.Name, propertyName, typeName);

                if (RP.Mbool(out sKey, keyType, propertyName))
                {
                    // rewriteName = true;
                    baseres.DisplayName = sKey;
                    //((DisplayAttribute)attr).ResourceType = null;
                }
                // else
                // {

                if (!string.IsNullOrEmpty(sKey) &&
                    sKey != baseres.DisplayName
                    //&& ((DisplayAttribute)attr).Name != baseres.DisplayName //update if different
                    && sKey.Contains(".")) // update if it auto generated
                {
                    RP.Madd(keyType, propertyName, "", baseres.DisplayName);
                }

                // }
            }
            else if (containerType != null && keyType != null && propertyName != null)
            {
                baseres.DisplayName = RP.M(keyType, propertyName);
            }
            if (hideTab.HasValue && hideTab.Value && baseres.Watermark != null)
            {
                baseres.Watermark = null;
            }
            return(baseres);
        }
        public ActionResult RegAjx(RegisterAjxModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus;
                MembershipUser         newUser = Membership.CreateUser(model.Email, model.Password, model.Email, "-", "-", true, out createStatus);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, RP.T("Account.Register.Error." + createStatus.ToString()).ToString());
                }
                else
                {
                    User u = _db.Users.FirstOrDefault(r => r.UserName == model.Email);
                    u.Roles       = SF.RolesStringAdd(u.Roles, "Register");
                    u.FirstName   = model.FirstName.Trim();
                    u.LastName    = model.LastName.Trim();
                    u.RoleDefault = "Register";
                    if (Session["address"] != null)
                    {
                        u.AddressMap = (string)Session["address"];
                    }
                    if (Session["longitude"] != null)
                    {
                        u.Longitude = (decimal)Session["longitude"];
                    }
                    if (Session["latitude"] != null)
                    {
                        u.Latitude = (decimal)Session["latitude"];
                    }

                    u.IsApproved       = true;
                    _db.Entry(u).State = EntityState.Modified;
                    _db.SaveChanges();
                    if (model.NewsLetter)
                    {
                        Newsletter n = new Newsletter()
                        {
                            NewsletterAccept = true,
                            NewsletterDate   = DateTime.UtcNow,
                            NewsletterEmail  = u.Email,
                            NewsletterName   = u.FirstName + " " + u.LastName,
                            RoleDefault      = "Register"
                        };
                        _db.Newsletters.Add(n);
                        _db.SaveChanges();
                        SF.AddToNewsletter(n);
                    }
                    if (Membership.ValidateUser(u.UserName, u.Password))
                    {
                        LS.Authorize(u);
                        var messService = new MessageService(_db);

                        messService.SendUserRegisterEmailToUser(u);
                        return(Json(new { result = "ok", url = "" }));
                    }
                    else
                    {
                        ModelState.AddModelError("", RP.T("Account.Logon.PasswordOrUserIncorrect").ToString());
                    }
                }
            }
            return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));

            //for future needed
            //   return Json(new { result = "error", message = new Dictionary<string,List<string>>().Select(x=> new { Value = x.Key,errors=x.Value  }) });
        }
示例#19
0
        //private static UiResources ui = new UiResources();
        protected override ModelMetadata CreateMetadata(
            IEnumerable <Attribute> attributes,
            Type containerType,
            Func <object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            string sKey           = string.Empty;
            string sLocalizedText = string.Empty;

            HttpContext.Current.Application.Lock();
            foreach (var attr in attributes)
            {
                if (attr != null)
                {
                    string typeName   = attr.GetType().Name;
                    string attrAppKey = string.Empty;

                    if (typeName.Equals("DisplayAttribute"))
                    {
                        sKey = ((DisplayAttribute)attr).Name;

                        if (!string.IsNullOrEmpty(sKey))
                        {
                            attrAppKey = string.Format("{0}-{1}-{2}",
                                                       containerType.Name, propertyName, typeName);
                            if (HttpContext.Current.Application[attrAppKey] == null)
                            {
                                HttpContext.Current.Application[attrAppKey] = sKey;
                            }
                            else
                            {
                                sKey = HttpContext.Current.Application[attrAppKey].ToString();
                            }

                            sLocalizedText = RP.T(sKey).ToString();
                            if (string.IsNullOrEmpty(sLocalizedText))
                            {
                                sLocalizedText = sKey;
                            }

                            ((DisplayAttribute)attr).Name = sLocalizedText;
                        }
                    }
                    else if (attr is ValidationAttribute)
                    {
                        sKey = ((ValidationAttribute)attr).ErrorMessage;

                        if (!string.IsNullOrEmpty(sKey))
                        {
                            attrAppKey = string.Format("{0}-{1}-{2}",
                                                       containerType.Name, propertyName, typeName);
                            if (HttpContext.Current.Application[attrAppKey] == null)
                            {
                                HttpContext.Current.Application[attrAppKey] = sKey;
                            }
                            else
                            {
                                sKey = HttpContext.Current.Application[attrAppKey].ToString();
                            }

                            sLocalizedText = RP.T(sKey).ToString();
                            if (string.IsNullOrEmpty(sLocalizedText))
                            {
                                sLocalizedText = sKey;
                            }

                            ((ValidationAttribute)attr).ErrorMessage = sLocalizedText;
                        }
                    }
                }
            }
            HttpContext.Current.Application.UnLock();

            return(base.CreateMetadata
                       (attributes, containerType, modelAccessor, modelType, propertyName));
        }
        public ActionResult GoogleAjx(string ID, string Name, string Image, string Email)
        {
            // google 111929910329405075066
            // long   9223372036854775807
            if (!string.IsNullOrEmpty(ID) && ID != "0")
            {
                string email = Email;
                if (string.IsNullOrEmpty(email))
                {
                    email = ID + "@gmail.com.com";
                }


                User uLogin = _db.Users.FirstOrDefault(r => r.GoogleID == ID);
                if (uLogin != null)
                {
                    //login
                    LS.Authorize(uLogin);
                    // var messService = new MessageService(_db);
                    // messService.SendUserRegisterEmailToUser(u);
                    return(Json(new { result = "ok", url = "" }));
                }
                else
                {
                    //register

                    //generate code
                    var chars    = "0123456789abcdefghjklmnopqrstuwvxyzQAZWSXEDCRFVTGBYHNUJMIKLOP@$&%";
                    var random   = new Random();
                    var password = new string(
                        Enumerable.Repeat(chars, 8)
                        .Select(s => s[random.Next(s.Length)])
                        .ToArray());

                    User uExist = _db.Users.FirstOrDefault(r => r.UserName == email || r.Email == email);
                    if (uExist != null)
                    {
                        uExist.GoogleID = ID;

                        _db.SaveChanges();//update facebook ID
                        //login
                        LS.Authorize(uExist);

                        return(Json(new { result = "ok", url = "" }));
                    }
                    MembershipCreateStatus createStatus;
                    MembershipUser         newUser = Membership.CreateUser(email, password, email, "-", "-", true, out createStatus);

                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError(string.Empty, RP.T("Account.Register.Error." + createStatus.ToString()).ToString());
                    }
                    else
                    {
                        User u = _db.Users.FirstOrDefault(r => r.UserName == email);
                        u.Roles     = SF.RolesStringAdd(u.Roles, "Register");
                        u.FirstName = "";
                        u.LastName  = "";
                        if (!string.IsNullOrEmpty(Name))
                        {
                            string[] firstLast = Name.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                            if (firstLast.Length > 0)
                            {
                                u.FirstName = firstLast[0];
                            }
                            if (firstLast.Length > 1)
                            {
                                u.LastName = firstLast[1];
                            }
                        }
                        u.RoleDefault      = "Register";
                        u.GoogleID         = ID;
                        u.IsApproved       = true;
                        _db.Entry(u).State = EntityState.Modified;
                        _db.SaveChanges();

                        Newsletter n = new Newsletter()
                        {
                            NewsletterAccept = true,
                            NewsletterDate   = DateTime.UtcNow,
                            NewsletterEmail  = u.Email,
                            NewsletterName   = u.FirstName + " " + u.LastName,
                            RoleDefault      = "Register"
                        };
                        _db.Newsletters.Add(n);
                        _db.SaveChanges();
                        SF.AddToNewsletter(n);


                        if (Membership.ValidateUser(u.UserName, u.Password))
                        {
                            LS.Authorize(u);

                            var messService = new MessageService(_db);
                            messService.SendUserRegisterEmailToUser(u);
                            return(Json(new { result = "ok", url = "" }));
                        }
                        else
                        {
                            ModelState.AddModelError("", RP.T("Account.Logon.PasswordOrUserIncorrect").ToString());
                        }
                    }
                }
                return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
            }
            return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
        }