Example #1
0
        public SitesViewModel GetSites()
        {
            var sitesViewModel = new SitesViewModel()
            {
                CommercialMenuSites = new List <CommercialMenuSite>(),
                MallMenuSites       = new List <MallMenuSite>()
            };
            var fraserRewardItem = SitecoreContext.Database.GetItem(Templates.FrasersRewards.ID);

            if (fraserRewardItem != null)
            {
                this.GetMallSiteAndCommerceSite(fraserRewardItem, sitesViewModel);
                sitesViewModel.PageSizeCommerceSite   = sitesViewModel.CommercialMenuSites.Count <= 1 ? sitesViewModel.CommercialMenuSites.Count : sitesViewModel.CommercialMenuSites.Count / 2;
                sitesViewModel.PageSizeMallMenuSite   = sitesViewModel.MallMenuSites.Count <= 1 ? sitesViewModel.MallMenuSites.Count : sitesViewModel.MallMenuSites.Count / 2;
                sitesViewModel.RepeatLoopCommerceSite = CalculateRepeatLoop(sitesViewModel.PageSizeCommerceSite, sitesViewModel.CommercialMenuSites.Count);
                sitesViewModel.RepeatLoopMallSites    = CalculateRepeatLoop(sitesViewModel.PageSizeMallMenuSite, sitesViewModel.MallMenuSites.Count);
                var siteItem = SitecoreContext.Database.GetItem(Sitecore.Context.Site.StartPath);
                if (siteItem.Parent.IsDerived(Templates.CommercialWebsite.ID) || siteItem.Parent.IsDerived(Templates.MallWebsite.ID))
                {
                    sitesViewModel.GroupMenuName = siteItem.Parent.GetString(Multisite.Templates.Identity.Fields.SiteName);
                }
                else
                {
                    sitesViewModel.GroupMenuName = DictionaryPhraseRepository.Current.Get(Multisite.Constants.SiteSwitcher, Multisite.Constants.SiteSwitcherText);
                }
            }
            return(sitesViewModel);
        }
Example #2
0
        private void GetMallSiteAndCommerceSite(Item fraserRewardItem, SitesViewModel sitesViewModel)
        {
            var siteInfoList = Sitecore.Configuration.Factory.GetSiteInfoList();

            foreach (Item item in fraserRewardItem.Parent.Children)
            {
                var siteInfo = siteInfoList.FirstOrDefault(x => item.Paths.FullPath.Trim().Equals(x.RootPath.Trim(), System.StringComparison.OrdinalIgnoreCase));
                if (siteInfo != null)
                {
                    var schema = System.Web.HttpContext.Current.Request.Url.Scheme;

                    if (item.IsDerived(Templates.MallWebsite.ID))
                    {
                        sitesViewModel.MallMenuSites.Add(new MallMenuSite()
                        {
                            SiteTitle = item.Field(Multisite.Templates.Identity.Fields.SiteName),
                            Link      = $"{schema}://{siteInfo.HostName}"
                        });
                    }
                    else if (item.IsDerived(Templates.CommercialWebsite.ID))
                    {
                        sitesViewModel.CommercialMenuSites.Add(new CommercialMenuSite()
                        {
                            SiteTitle = item.Field(Multisite.Templates.Identity.Fields.SiteName),
                            Link      = $"{schema}://{siteInfo.HostName}"
                        });
                    }
                }
            }
        }
Example #3
0
        public IActionResult ListSites()
        {
            var sitesViewModel = new SitesViewModel
            {
                Sites = _context.Site
                        .Include(s => s.SiteType)
                        .Include(s => s.Company)
                        .ToList()
            };

            return(View(sitesViewModel));
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            model = new SitesViewModel()
            {
                SiteId         = SiteId,
                PageName       = PageName,
                Settings       = SettingsInfo,
                ControllerName = ControllerName,
                ActionName     = ActionName,
                Sites          = _cmsRepository.GetSites(),
                MenuCMS        = MenuCmsCore,
                MenuModules    = MenuModulCore,
            };
        }
Example #5
0
        public ActionResult Save(Guid id, SitesViewModel backModel)
        {
            ErrorMessage message = new ErrorMessage
            {
                Title = "Информация"
            };

            if (ModelState.IsValid)
            {
                backModel.Item.Id = id;
                if (_cmsRepository.CheckSiteExist(id))
                {
                    _cmsRepository.UpdateSite(backModel.Item);
                    message.Info = "Запись обновлена";
                }
                else
                {
                    _cmsRepository.InsertSite(backModel.Item);
                    message.Info = "Запись добавлена";
                }
                message.Buttons = new ErrorMessageBtnModel[]
                {
                    new ErrorMessageBtnModel {
                        Url = StartUrl + Request.Url.Query, Text = "вернуться в список"
                    },
                    new ErrorMessageBtnModel {
                        Url = StartUrl + "item/" + id, Text = "ок", Action = "false"
                    }
                };
            }
            else
            {
                message.Info    = "Ошибка в заполнении формы. Поля в которых допушены ошибки - помечены цветом";
                message.Buttons = new ErrorMessageBtnModel[]
                {
                    new ErrorMessageBtnModel {
                        Url = "#", Text = "ок", Action = "false"
                    }
                };
            }

            model.ErrorInfo = message;
            return(View("item", model));
        }
        public async Task <int> SaveOrUpdateSite([FromBody] SitesViewModel mvm)
        {
            // string sql = "dbo.ENAppSaveSites";

            try
            {
                string sql = @"Insert into dbo.TempClientSites(clientId,clientSiteId,nodeType,siteName,description,countryId,industryId,logo)
                           values(@clientId,@clientSiteId,@nodeType,@siteName,@description,@countryId,@industryId,@logo)";

                using (var conn = util.MasterCon())
                {
                    return(await conn.ExecuteAsync(sql, new { mvm.clientId, mvm.clientSiteId, mvm.nodeType, mvm.siteName, mvm.description, mvm.countryId, mvm.industryId, mvm.logo }));
                }
            }
            catch (Exception ex)
            {
                throw new CustomException("Unable to Save Or Update, Please Contact Support!!!", "Error", true, ex);
            }
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            model = new SitesViewModel
            {
                Account        = AccountInfo,
                Settings       = SettingsInfo,
                UserResolution = UserResolutionInfo,
                ControllerName = ControllerName,
                ActionName     = ActionName
            };

            #region Метатеги
            ViewBag.Title       = UserResolutionInfo.Title;
            ViewBag.Description = "";
            ViewBag.KeyWords    = "";
            #endregion
        }
Example #8
0
        public ActionResult Sites(SitesViewModel model)
        {
            try
            {
                var accessToken = HttpHelper.GetAccessTokenForCurrentUser();
                if (!String.IsNullOrEmpty(accessToken))
                {
                    var jsonSite = HttpHelper.MakeGetRequestForString(
                        model.SiteUrlOrId.Contains(",") ?
                        $"{GraphSettings.MicrosoftGraphV1BaseUri}sites/{model.SiteUrlOrId}" :
                        $"{GraphSettings.MicrosoftGraphV1BaseUri}sites/{GraphSettings.SpoTenant}:{model.SiteUrlOrId}",
                        accessToken);

                    if (!String.IsNullOrEmpty(jsonSite))
                    {
                        var site = JsonConvert.DeserializeObject <SiteInfoViewModel>(jsonSite);

                        if (site != null)
                        {
                            return(View("SiteInfo", site));
                        }
                    }
                }
            }
            catch (AdalException adalEx)
            {
                // Skip any ADAL Exception and repeat the AuthN challenge
                Debug.WriteLine(adalEx.Message);
            }
            catch (Exception)
            {
                throw;
            }

            return(View(model));
        }
Example #9
0
        public ActionResult SitesManagement(int page = 1, int pageSize = 50, string title = "", int?areaId = null)
        {
            ViewBag.Title         = "";
            ViewBag.MessageStatus = TempData["MessageStatus"];
            ViewBag.Message       = TempData["Message"];
            if (pageSize == 1)
            {
                pageSize = CMSHelper.pageSizes[0];
            }
            @ViewBag.PageSizes = CMSHelper.pageSizes;
            int              CurrentUserId = WebMatrix.WebData.WebSecurity.CurrentUserId;
            string           userName      = User.Identity.Name;
            int              skip          = (page - 1) * pageSize;
            int              totalRows     = 0;
            List <SiteModel> list          = new List <SiteModel>();

            #region Lấy dữ liệu
            if (userName == "administrator")
            {
                list = sitesService.GetAll(skip, pageSize, out int totalRow, title, areaId, null).AsEnumerable().Select(item => new SiteModel
                {
                    Id         = item.Id,
                    Name       = item.Name,
                    DeviceId   = item.DeviceId,
                    Latitude   = item.Latitude,
                    Longtitude = item.Longtitude,
                    CreateDay  = item.CreateDay,
                    NguoiTao   = userProfileService.userProfileResponsitory.Single(item.CreateBy).FullName,
                    IsActive   = item.IsActive,
                    GroupsName = groupService.groupResponsitory.Single(item.Group_Id).Name,
                    AreasName  = areasService.areaResponsitory.Single(item.Area_Id).Name
                }).ToList();
                totalRows = totalRow;
            }
            else
            {
                int groupId = userProfileService.userProfileResponsitory.Single(CurrentUserId).Group_Id.Value;
                list = sitesService.GetAll(skip, pageSize, out int totalRow, title, areaId, groupId).AsEnumerable().Select(item => new SiteModel
                {
                    Id         = item.Id,
                    Name       = item.Name,
                    Latitude   = item.Latitude,
                    DeviceId   = item.DeviceId,
                    Longtitude = item.Longtitude,
                    CreateDay  = item.CreateDay,
                    NguoiTao   = userProfileService.userProfileResponsitory.Single(item.CreateBy).FullName,
                    IsActive   = item.IsActive,
                    GroupsName = groupService.groupResponsitory.Single(item.Group_Id).Name,
                    AreasName  = areasService.areaResponsitory.Single(item.Area_Id).Name
                }).ToList();
                totalRows = totalRow;
            }
            #endregion

            #region Hiển thị dữ liệu và phân trang
            SitesViewModel viewModel = new SitesViewModel
            {
                Sites      = new StaticPagedList <SiteModel>(list, page, pageSize, totalRows),
                PagingInfo = new PagingInfo
                {
                    CurrentPage  = page,
                    ItemsPerPage = pageSize,
                    TotalItems   = totalRows
                }
            };
            #endregion

            return(View(viewModel));
        }
        public ActionResult Index(SitesViewModel backModel, HttpPostedFileBase upload, HttpPostedFileBase uploadBack)
        {
            ErrorMessage userMassege = new ErrorMessage
            {
                title = "Информация"
            };

            if (ModelState.IsValid)
            {
                double MapX = 0;
                double MapY = 0;

                if (backModel.Item.CoordX != null)
                {
                    MapX = (double)backModel.Item.CoordX;
                }
                if (backModel.Item.CoordY != null)
                {
                    MapY = (double)backModel.Item.CoordY;
                }
                ViewBag.Xcoord = MapX;
                ViewBag.Ycoord = MapY;

                if (backModel.Item.Adress != String.Empty && (MapX == 0 || MapY == 0))
                {
                    string url  = "http://geocode-maps.yandex.ru/1.x/?format=json&results=1&geocode=" + backModel.Item.Adress;
                    string html = string.Empty;
                    // Отправляем GET запрос и получаем в ответ JSON с данным об адресе
                    HttpWebRequest  myHttpWebRequest  = (HttpWebRequest)HttpWebRequest.Create(url);
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    StreamReader    myStreamReader    = new StreamReader(myHttpWebResponse.GetResponseStream());
                    html = myStreamReader.ReadToEnd();

                    string coord   = String.Empty;
                    Regex  ReCoord = new Regex("(?<=\"Point\":{\"pos\":\")(.*)(?=\"})", RegexOptions.IgnoreCase);

                    coord = Convert.ToString(ReCoord.Match(html).Groups[1].Value);

                    coord = coord.Replace(" ", ";");
                    string[] ArrCoord = coord.Split(';');
                    foreach (string qwerty in ArrCoord)
                    {
                        MapX = double.Parse(ArrCoord[1].Replace(".", ","));
                        MapY = double.Parse(ArrCoord[0].Replace(".", ","));
                    }
                    backModel.Item.CoordX = MapX;
                    backModel.Item.CoordY = MapY;
                }

                #region Сохранение изображений

                if (upload != null && upload.ContentLength > 0)
                {
                    var photo = imageWorker(upload, 1);
                    if (photo == null)
                    {
                        return(View("Item", model));
                    }

                    backModel.Item.Logo = photo;
                }

                #region Изображени под слайдером
                if (uploadBack != null && uploadBack.ContentLength > 0)
                {
                    string SavePath   = Settings.UserFiles + Domain + "/logo/";
                    int    idx        = uploadBack.FileName.LastIndexOf('.');
                    string Title      = uploadBack.FileName.Substring(0, idx);
                    string TransTitle = Transliteration.Translit(Title);
                    string FileName   = TransTitle + Path.GetExtension(uploadBack.FileName);


                    string FullName = SavePath + FileName;
                    if (!Directory.Exists(Server.MapPath(SavePath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(SavePath));
                    }
                    uploadBack.SaveAs(Server.MapPath(Path.Combine(SavePath, FileName)));
                    backModel.Item.BackGroundImg = new Photo {
                        Url = FullName
                    };
                }

                #endregion


                #endregion

                _cmsRepository.updateSiteInfo(backModel.Item);
                userMassege.info    = "Запись обновлена";
                userMassege.buttons = new ErrorMassegeBtn[]
                {
                    new ErrorMassegeBtn {
                        url = "/Admin/sitesettings", text = "ок"
                    }
                };
            }
            else
            {
                userMassege.info = "Ошибка в заполнении формы. Поля в которых допушены ошибки - помечены цветом.";

                userMassege.buttons = new ErrorMassegeBtn[]
                {
                    new ErrorMassegeBtn {
                        url = "#", text = "ок", action = "false"
                    }
                };
            }
            model.ErrorInfo = userMassege;
            model.Item      = _cmsRepository.getSite();
            return(View(model));
        }
Example #11
0
        public ActionResult Save(Guid Id, SitesViewModel back_model)
        {
            ErrorMessage userMassege = new ErrorMessage();

            userMassege.title = "Информация";
            if (!_cmsRepository.check_Site(Id) && back_model.Item.ContentId == null)
            {
                ModelState.AddModelError("Name", "Необходимо выбрать тип и контент сайта");
            }

            if (ModelState.IsValid)
            {
                // дополнительные домены
                List <string> domains = new List <string>();
                domains.Add(back_model.Item.Alias + ".localhost");

                if (!string.IsNullOrEmpty(back_model.Item.DomainListString))
                {
                    string[] dopDomains = back_model.Item.DomainListString.Replace(" ", "").Split(';');
                    foreach (var d in dopDomains)
                    {
                        if (!string.IsNullOrEmpty(d))
                        {
                            domains.Add(d);
                        }
                    }
                    back_model.Item.DomainListArray = domains;
                }

                if (_cmsRepository.check_Site(Id))
                {
                    _cmsRepository.updateSite(Id, back_model.Item); //, AccountInfo.id, RequestUserInfo.IP
                    userMassege.info = "Запись обновлена";
                }
                else if (!_cmsRepository.check_Site(Id))
                {
                    back_model.Item.Id = Id;
                    _cmsRepository.insertSite(back_model.Item); //, AccountInfo.id, RequestUserInfo.IP
                    userMassege.info = "Запись добавлена";
                }
                else
                {
                    userMassege.info = "Запись с таким псевдонимом уже существует. <br />Замените псевдоним.";
                }
                userMassege.buttons = new ErrorMassegeBtn[] {
                    new ErrorMassegeBtn {
                        url = StartUrl + Request.Url.Query, text = "вернуться в список"
                    },
                    new ErrorMassegeBtn {
                        url = StartUrl + "item/" + Id + "/" + Request.Url.Query, text = "редактировать"
                    }
                };
            }
            else
            {
                userMassege.info    = "Ошибка в заполнении формы";
                userMassege.buttons = new ErrorMassegeBtn[] {
                    new ErrorMassegeBtn {
                        url = "#", text = "ок", action = "false"
                    }
                };
                model.Item      = _cmsRepository.getSite(Id);
                model.ErrorInfo = userMassege;

                return(View("Master", model));
            }
            model.Item      = _cmsRepository.getSite(Id);
            model.ErrorInfo = userMassege;

            #region Данные из адресной строки(для случаев когда сайт создается со страницы того кому создается сайт)
            FilterParams filter = new FilterParams()
            {
                Page = 1,
                Size = 999999
            };
            string OrgType   = Request.QueryString["type"];
            string ContentId = Request.QueryString["contentid"];

            if (!String.IsNullOrEmpty(OrgType))
            {
                ViewBag.OrgType = OrgType;
            }
            else
            {
            }
            if (!String.IsNullOrEmpty(ContentId))
            {
                ViewBag.ContentId = Guid.Parse(ContentId);
            }
            #endregion
            #region данные для выпадающих списков
            model.TypeList = new SelectList(
                new List <SelectListItem>
            {
                new SelectListItem {
                    Text = "Не выбрано", Value = ""
                },
                new SelectListItem {
                    Text = "Организация", Value = "org"
                },
                new SelectListItem {
                    Text = "Главный специалист", Value = "spec"
                },
                new SelectListItem {
                    Text = "Событие", Value = "event"
                }
            }, "Value", "Text", OrgType
                );
            var orgfilter = FilterParams.Extend <OrgFilter>(filter);
            var evfilter  = FilterParams.Extend <EventFilter>(filter);
            #endregion

            return(View("Item", model));
        }