예제 #1
0
        private async Task <LogoModel> PrepareLogo()
        {
            var model = new LogoModel {
                StoreName = _storeContext.CurrentStore.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id)
            };

            var cacheKey = string.Format(ModelCacheEventConst.STORE_LOGO_PATH, _storeContext.CurrentStore.Id, _themeContext.WorkingThemeName);

            model.LogoPath = await _cacheBase.GetAsync(cacheKey, async() =>
            {
                var logo    = "";
                var picture = await _pictureService.GetPictureById(_storeInformationSettings.LogoPictureId);
                if (picture != null)
                {
                    logo = await _pictureService.GetPictureUrl(picture, showDefaultPicture: false);
                }
                if (string.IsNullOrEmpty(logo))
                {
                    //use default logo
                    logo = string.Format("{0}://{1}/Themes/VueTheme/Content/images/images/img/dlogo.svg", HttpContext.Request.Scheme, HttpContext.Request.Host, _themeContext.WorkingThemeName);
                }
                return(logo);
            });

            return(model);
        }
예제 #2
0
        /// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public virtual LogoModel PrepareLogoModel()
        {
            var model = new LogoModel
            {
                StoreName = _storeContext.CurrentStore.GetLocalized(x => x.Name)
            };

            var cacheKey = string.Format(ModelCacheEventConsumer.STORE_LOGO_PATH, _storeContext.CurrentStore.Id, _themeContext.WorkingThemeName, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _cacheManager.Get(cacheKey, () =>
            {
                var logo          = "";
                var logoPictureId = _storeInformationSettings.LogoPictureId;
                if (logoPictureId > 0)
                {
                    logo = _pictureService.GetPictureUrl(logoPictureId, showDefaultPicture: false);
                }
                if (string.IsNullOrEmpty(logo))
                {
                    //use default logo
                    logo = $"{_webHelper.GetStoreLocation()}Themes/{_themeContext.WorkingThemeName}/Content/images/logo.png";
                }
                return(logo);
            });

            return(model);
        }
예제 #3
0
        public ActionResult EditLogo(string userId, string linked, string twitter, string facebook, string google)
        {
            try
            {
                int id = Convert.ToInt32(userId);
                //var crm_users = _userService.Find(id);
                crm_Users crm_Users = _userService.ODataQueryable().Where(x => x.ID.Equals(id)).FirstOrDefault();

                if (!string.IsNullOrEmpty(_logoModel.FileName))
                {
                    crm_Users.Image = _logoModel.FileName;
                    _logoModel      = null;
                }
                crm_Users.LinkedURL     = linked;
                crm_Users.FacebookURL   = facebook;
                crm_Users.TwitterURL    = twitter;
                crm_Users.GoogleplusURL = google;
                crm_Users.UpdatedDate   = DateTime.Now;

                crm_Users.ObjectState = ObjectState.Modified;
                _userService.Update(crm_Users);
                _unitOfWork.SaveChanges();

                _helper.InsertLogActive(_logService, _unitOfWork, "User", "update avatar of user success", 2, true);
                return(Content("Update success!"));
            }
            catch (Exception ex)
            {
                _helper.InsertLogActive(_logService, _unitOfWork, "User", "update avatar of user :"******"Update fail!"));
            }
        }
예제 #4
0
        public ActionResult Index()
        {
            var model = new LogoModel();

            model.ImageUrl = "/Content/BSFA/images/logo.png";
            return(View(model));
        }
예제 #5
0
        /// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public Task <LogoModel> PrepareLogoModel()
        {
            var model = new LogoModel {
                TenantName = _tenantContext.CurrentTenant.Name
            };

            var cacheKey = string.Format(ModelCacheDefaults.LogoPath, _tenantContext.CurrentTenant.Id, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _cacheManager.Get(cacheKey, () =>
            {
                var logo          = "";
                var logoPictureId = _commonSettings.LogoPictureId;
                if (logoPictureId > 0)
                {
                    logo = _pictureService.GetPictureUrl(logoPictureId, showDefaultPicture: false);
                }

                if (string.IsNullOrEmpty(logo))
                {
                    //use default logo
                    logo = $"{_webHelper.GetLocation()}images/MainMenu_Logo.png";
                }

                return(logo);
            });

            return(Task.FromResult(model));
        }
예제 #6
0
        /// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public virtual LogoModel PrepareLogoModel()
        {
            var model = new LogoModel
            {
                StoreName = _localizationService.GetLocalized(_storeContext.CurrentStore, x => x.Name)
            };

            var cacheKey = _cacheKeyService.PrepareKeyForDefaultCache(NopModelCacheDefaults.StoreLogoPath
                                                                      , _storeContext.CurrentStore, _themeContext.WorkingThemeName, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _staticCacheManager.Get(cacheKey, () =>
            {
                var logo          = string.Empty;
                var logoPictureId = _storeInformationSettings.LogoPictureId;

                if (logoPictureId > 0)
                {
                    logo = _pictureService.GetPictureUrl(logoPictureId, showDefaultPicture: false);
                }

                if (string.IsNullOrEmpty(logo))
                {
                    //use default logo
                    var pathBase      = _httpContextAccessor.HttpContext.Request.PathBase.Value ?? string.Empty;
                    var storeLocation = _mediaSettings.UseAbsoluteImagePath ? _webHelper.GetStoreLocation() : $"{pathBase}/";
                    logo = $"{storeLocation}Themes/{_themeContext.WorkingThemeName}/Content/images/logo.png";
                }

                return(logo);
            });

            return(model);
        }
        public IActionResult UpdateLogo(LogoModel model)
        {
            var filePath = model.Value;
            var logo     = new SiteConfig
            {
                Id      = model.Id,
                Name    = model.Name,
                Type    = Constants.SiteConfigTypes.Logo,
                Value   = filePath,
                OwnerId = model.OwnerId
            };

            if (model.Image != null && model.Image.Length > 0)
            {
                var fileName = _fileHandler.SaveFile(model.Image, new List <string> {
                    "images", "logos", _userManager.SupervisorId
                });
                logo.Value = fileName;
            }

            if (model.Id == null || model.Id == Guid.Empty)
            {
                logo.OwnerId = _userManager.SupervisorId;
                _siteConfigService.Create(logo);
            }
            else
            {
                _siteConfigService.Update(logo);
            }

            return(RedirectToAction("Logo"));
        }
예제 #8
0
        public ActionResult Create(UsersModel usersModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(_logoModel.FileName) && usersModel.Image != _logoModel.FileName)
                    {
                        usersModel.Image = _logoModel.FileName;
                        _logoModel       = null;
                    }

                    var roleID = usersModel.SelectedRoleIds;

                    string encryptPassword = "";
                    string passwordSalt    = "";
                    passwordSalt    = EncryptProvider.GenerateSalt();
                    encryptPassword = EncryptProvider.EncryptPassword(usersModel.Password, passwordSalt);

                    usersModel.CreatedDate  = DateTime.Now;
                    usersModel.PasswordSalt = passwordSalt;
                    usersModel.Password     = encryptPassword;

                    if (usersModel.TenantId == 0)
                    {
                        usersModel.TenantId = usersModel.ID;
                    }

                    var _userEntity = usersModel.ToEntity();
                    _userService.Insert(_userEntity);

                    _unitOfWork.SaveChanges();

                    //insert role for table userRoles
                    var crm_UserRoles = new crm_UserRoles();
                    crm_UserRoles.RoleID = roleID;
                    crm_UserRoles.UserID = _userEntity.ID;
                    _userRoleService.Insert(crm_UserRoles);

                    _unitOfWork.SaveChanges();

                    //note log
                    _helper.InsertLogActive(_logService, _unitOfWork, "User", "Insert new user", 1, true);

                    if (usersModel.TenantId != 0)
                    {
                        return(RedirectToAction("Index", "User", new { area = "Admin", id = usersModel.TenantId }));
                    }

                    return(RedirectToAction("Index"));
                }
                return(View(usersModel));
            }
            catch (Exception ex)
            {
                _helper.InsertLogActive(_logService, _unitOfWork, "User", "Insert new user:"******"Index"));
            }
        }
예제 #9
0
        public ActionResult EditLogo(string tenantId, string linked, string twitter, string facebook, string google)
        {
            int id          = Convert.ToInt32(tenantId);
            int countUpdate = 0;
            var crm_tenant  = _tenantService.Find(id);

            if (!string.IsNullOrEmpty(_logoModel.FileName))
            {
                crm_tenant.CompanyLogo = _pathFiles + "/" + _logoModel.FileName;

                //move a file from temps file to tenant folder
                var _sourceFile      = Path.Combine(Server.MapPath(_tempFiles), _logoModel.FileName);
                var _destinationFile = Path.Combine(Server.MapPath(_pathFiles), _logoModel.FileName);
                if (System.IO.File.Exists(_destinationFile))
                {
                    System.IO.File.Delete(_destinationFile);
                }
                System.IO.File.Move(_sourceFile, _destinationFile);

                _logoModel = null;
                countUpdate++;
            }

            if (crm_tenant.LinkedURL != linked)
            {
                crm_tenant.LinkedURL = linked;
                countUpdate++;
            }

            if (crm_tenant.FacebookURL != facebook)
            {
                crm_tenant.FacebookURL = facebook;
                countUpdate++;
            }

            if (crm_tenant.TwitterURL != twitter)
            {
                crm_tenant.TwitterURL = twitter;
                countUpdate++;
            }

            if (crm_tenant.GoogleplusURL != google)
            {
                crm_tenant.GoogleplusURL = google;
                countUpdate++;
            }
            if (countUpdate > 0)
            {
                crm_tenant.ModifiedDate = DateTime.Now;
                crm_tenant.ObjectState  = ObjectState.Modified;
                _tenantService.Update(crm_tenant);
                _unitOfWork.SaveChanges();
                return(Content("Update success!"));
            }
            else
            {
                return(Content("No change"));
            }
        }
        /// <summary>
        /// Appends the logo to specified worksheet.
        /// </summary>
        /// <param name="worksheet">The worksheet.</param>
        /// <param name="model">Logo model.</param>
        public static void AppendLogo(this ExcelWorksheet worksheet, LogoModel model)
        {
            SentinelHelper.ArgumentNull(model);
            SentinelHelper.ArgumentNull(worksheet);

            if (model.IsDefault)
            {
                return;
            }

            if (model.Show == YesNo.No)
            {
                return;
            }

            var logoPosition = model.Location;
            var positionType = logoPosition.LocationType;

            if (positionType == KnownElementLocation.ByAlignment)
            {
                return;
            }

            var found = model.Image.TryGetImage(out var image);

            if (!found)
            {
                return;
            }

            var logoWidth =
                model.LogoSize.Width == -1
                    ? image.Width
                    : model.LogoSize.Width;

            var logoHeight =
                model.LogoSize.Height == -1
                    ? image.Height
                    : model.LogoSize.Height;

            var logoNameBuilder = new StringBuilder();
            var coordenates     = (CoordenatesModel)logoPosition.Mode;

            logoNameBuilder.Append("logo");
            logoNameBuilder.Append(coordenates.TableCoordenates.X);
            logoNameBuilder.Append(coordenates.TableCoordenates.Y);

            worksheet.Row(coordenates.TableCoordenates.Y).Height = (image.Height - 1) * 0.75d;

            var logo = worksheet.Drawings.AddPicture(logoNameBuilder.ToString(), image);

            logo.Locked = true;
            logo.SetSize(logoWidth, logoHeight);
            logo.SetPosition(
                coordenates.TableCoordenates.Y - 1,
                0,
                coordenates.TableCoordenates.X - 1,
                0);
        }
        public ActionResult SetupLogo()
        {
            int configID = GetConfigID();
            var context  = GetContext();
            var model    = new LogoModel(configID, context);

            return(PartialView(model));
            //return PartialView(new LogoModel {Url = "../../../Areas/hvac_app/content/bigimage.png"});
        }
        public IActionResult GetLogos()
        {
            var logoPictureId = _storeInformationSettings.LogoPictureId;
            var model         = new LogoModel
            {
                StoreName = LocalizationService.GetLocalized(_storeContext.CurrentStore, x => x.Name),
                LogoPath  = _pictureService.GetPictureUrl(logoPictureId, showDefaultPicture: false)
            };

            return(Ok(model));
        }
예제 #13
0
        /// <summary>
        /// Adds the logo inside the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="logo">Logo model.</param>
        /// <returns>
        /// Returns the <see cref="T:Novacode.DocX" /> which contains the logo inside.
        /// </returns>
        public static DocX AppendLogoFromModel(this DocX document, LogoModel logo)
        {
            SentinelHelper.ArgumentNull(logo);
            SentinelHelper.ArgumentNull(document);

            if (logo.IsDefault)
            {
                return(document);
            }

            if (logo.Show == YesNo.No)
            {
                return(document);
            }

            var found = logo.Image.TryGetImage(out var imageLogo);

            if (!found)
            {
                return(document);
            }

            var root          = logo.Parent.Parent;
            var imagePath     = root.Resources.GetImageResourceByKey(logo.Image.Key).Path;
            var imageFileName = Path.GetFileNameWithoutExtension(root.ParseRelativeFilePath(imagePath));

            var modifiedImageFileNamePathBuilder = new StringBuilder();

            modifiedImageFileNamePathBuilder.Append(FileHelper.TinExportTempDirectory);
            modifiedImageFileNamePathBuilder.Append(imageFileName);
            modifiedImageFileNamePathBuilder.Append(".png");

            imageLogo.Save(modifiedImageFileNamePathBuilder.ToString(), ImageFormat.Png);

            var logoWidth = logo.LogoSize.Width == -1
                                ? imageLogo.Width
                                : logo.LogoSize.Width;

            var logoHeight = logo.LogoSize.Height == -1
                                    ? imageLogo.Height
                                    : logo.LogoSize.Height;

            var img     = document.AddImage(modifiedImageFileNamePathBuilder.ToString());
            var picture = img.CreatePicture(logoHeight, logoWidth);

            picture.SetPictureShape(RectangleShapes.rect);

            document.SetVerticalLocationFrom(logo.Location);
            var paragraph = document.InsertParagraph(string.Empty, false);

            paragraph.InsertPicture(picture).SetHorizontalAlignmentFrom(logo.Location);

            return(document);
        }
예제 #14
0
        public ActionResult RemoveLogoUpload()
        {
            var physicalPath = string.Format("{0}/{1}", Server.MapPath(_tempFiles), _logoModel.FileName);

            if (System.IO.File.Exists(physicalPath))
            {
                System.IO.File.Delete(physicalPath);
            }
            _logoModel = null;
            return(Json(""));
        }
예제 #15
0
        public ActionResult Logo()
        {
            var model = new LogoModel
            {
                StoreName = "AuctionCommerce"
            };

            model.LogoPath = "/content/images/logo.png";

            return(PartialView(model));
        }
예제 #16
0
        public IViewComponentResult Invoke()
        {
            StoreInformationSettings storeInformationSettings = _settingService.LoadSetting <StoreInformationSettings>();
            int    pictureId = storeInformationSettings.LogoPictureId;
            string logoUrl   = _pictureService.GetPictureUrl(pictureId);
            var    model     = new LogoModel
            {
                StoreName = _storeService.GetAllStores(false).FirstOrDefault()?.Name,
                LogoPath  = logoUrl
            };

            ViewBag.PageHelpContainer = logoUrl;
            return(View(model));
        }
예제 #17
0
        public ActionResult Index(LogoModel model)
        {
            if (ModelState.IsValid)
            {
                string filePath = Server.MapPath("~/Content/BSFA/images/logo.png");
                using (FileStream stream = new FileStream(filePath, FileMode.Truncate))
                {
                    model.File.InputStream.CopyTo(stream);
                    stream.Close();
                }
            }

            return(Index());
        }
        public async Task GetLogoModelShouldBeSuccessful()
        {
            ClarifaiResponse <IModel <Logo> > response =
                await Client.GetModel <Logo>(Client.PublicModels.LogoModel.ModelID)
                .ExecuteAsync();

            Assert.True(response.IsSuccessful);
            Assert.AreEqual(10000, response.Status.StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, response.HttpCode);
            Assert.NotNull(response.RawBody);

            LogoModel logoModel = (LogoModel)response.Get();

            Assert.NotNull(logoModel.ModelID);
            Assert.NotNull(logoModel.OutputInfo.Concepts);
        }
        public ActionResult SaveLogo()
        {
            int configID = GetConfigID();
            var context  = GetContext();

            LogoModel.UpdateOrAddedUrl(Request.Form.Get("Url"), context, configID);
            try
            {
                context.SaveChanges();
                return(Json(new { result = true }));
            }
            catch (Exception)
            {
                return(Json(new { result = false }));
            }
        }
예제 #20
0
        //auto save image into folder images/temps
        public ActionResult SaveLogoUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                // Upload file in to UploadFolder
                var _fileName      = Path.GetFileName(file.FileName);
                var _physhicalPath = Path.Combine(Server.MapPath(_tempFiles), _fileName);

                _logoModel = new LogoModel()
                {
                    FileName = _fileName, PictureUrl = _tempFiles + "/" + _fileName
                };
                file.SaveAs(_physhicalPath);
            }
            return(Json(_logoModel, JsonRequestBehavior.AllowGet));
        }
        private VerificationResult VerificationLogoImage()
        {
            var logo   = new LogoModel(_configId, _context);
            var result = new VerificationResult
            {
                NameOfVerification = "Company Logo linked",
                Result             = false,
                Message            = "No URL is linked to this company"
            };

            if (!String.IsNullOrEmpty(logo.Url))
            {
                result.Result  = true;
                result.Message = String.Format("The logo URL is {0}", logo.Url);
            }
            return(result);
        }
예제 #22
0
        /// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public virtual LogoModel PrepareLogoModel()
        {
            var model = new LogoModel
            {
            };

            var cacheKey = string.Format(ModelCacheEventConsumer.STORE_LOGO_PATH, _themeContext.WorkingThemeName, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _cacheManager.Get(cacheKey, () =>
            {
                //use default logo
                var logo = $"{_webHelper.GetSiteLocation()}Themes/{_themeContext.WorkingThemeName}/Content/images/logo.png";
                return(logo);
            });

            return(model);
        }
예제 #23
0
파일: MaterialModel.cs 프로젝트: Jo3-16/FMA
        public MaterialModel(int id, string title, string description, IEnumerable<MaterialFieldModel> materialFields,
            byte[] flyerFrontSide, byte[] flyerBackside, FontFamilyWithName defaultFont)
        {
            MaterialFields = new ObservableCollection<MaterialFieldModel>();

            Id = id;
            Title = title;
            Description = description;

            materialFields.ToList().ForEach(AddMaterialField);

            MaterialFields.CollectionChanged += (s, e) => OnPropertyChanged("MaterialFields");

            FlyerFrontSide = flyerFrontSide;
            FlyerBackside = flyerBackside;
            DefaultFont = defaultFont;

            LogoModel = new LogoModel();
            LogoModel.PropertyChanged += (s, e) => OnPropertyChanged("Logo");
        }
예제 #24
0
 //upload file : auto save avatar
 public ActionResult SaveLogoUpload(HttpPostedFileBase file)
 {
     if (file != null)
     {
         // Upload file in to UploadFolder
         var _fileName      = Path.GetFileName(file.FileName);
         var _pathFile      = "/images/avatar";
         var _physhicalPath = Path.Combine(Server.MapPath(_pathFile), _fileName);
         if (System.IO.File.Exists(_physhicalPath))
         {
             _physhicalPath = Path.Combine(Server.MapPath(_pathFile), _fileName);
         }
         _logoModel = new LogoModel()
         {
             FileName = _fileName, PictureUrl = _pathFile + "/" + _fileName
         };
         file.SaveAs(_physhicalPath);
     }
     return(Json(_logoModel, JsonRequestBehavior.AllowGet));
 }
예제 #25
0
        public ActionResult Index()
        {
            var firstRoot = StrongContentService.GetRootNodes().First();

            var siteSettingsNode = firstRoot as Samson.Model.DocumentTypes.Website;

            if (siteSettingsNode == null || siteSettingsNode.LogoId == 0)
            {
                // No Logo settings set up.
                return(null);
            }

            var logoImage = StrongMediaService.GetMediaItem <IImage>(siteSettingsNode.LogoId);

            var logoModel = new LogoModel
            {
                Url   = "/",
                Image = logoImage
            };

            return(View("~/Views/Partials/LogoView.cshtml", logoModel));
        }
예제 #26
0
        public ActionResult UploadLogo(LogoModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.File.ContentLength > 0)
                {
                    string FileName = Path.GetFileName(model.File.FileName);
                    string SavePath = Path.Combine(Server.MapPath("~/Logo"), FileName);
                    if (!Directory.Exists(Server.MapPath("~/Logo")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Logo"));
                    }
                    model.File.SaveAs(SavePath);
                    var logoContext = new LogoContext
                    {
                        AltText  = model.AltText,
                        LogoPath = FileName
                    };

                    using (var context = new ApplicationDbContext())
                    {
                        var logoInfo = context.LogoContexts.FirstOrDefault();
                        if (logoInfo == null)
                        {
                            context.LogoContexts.Add(logoContext);
                        }
                        else
                        {
                            logoInfo.AltText  = model.AltText;
                            logoInfo.LogoPath = FileName;
                        }

                        context.SaveChanges();
                    }
                }
            }
            return(View());
        }
예제 #27
0
 private static CustomLogo ToCustomLogo(LogoModel logoModel)
 {
     var customLogo = new CustomLogo(logoModel.Logo, logoModel.LeftMargin, logoModel.TopMargin, logoModel.Width,
         logoModel.Height);
     return customLogo;
 }
예제 #28
0
        public ActionResult Edit(TenantModel tenantModel)
        {
            var _tenant = _tenantService.Find(tenantModel.TenantId);

            if (_tenant != null)
            {
                if (_logoModel != null && !string.IsNullOrEmpty(_logoModel.FileName))
                {
                    tenantModel.CompanyLogo = _pathFiles + "/" + _logoModel.FileName;

                    //move a file from temps file to tenant folder
                    var _sourceFile      = Path.Combine(Server.MapPath(_tempFiles), _logoModel.FileName);
                    var _destinationFile = Path.Combine(Server.MapPath(_pathFiles), _logoModel.FileName);
                    if (System.IO.File.Exists(_destinationFile))
                    {
                        System.IO.File.Delete(_destinationFile);
                    }
                    System.IO.File.Move(_sourceFile, _destinationFile);

                    _logoModel = null;
                }

                if (tenantModel.Website != _tenant.Website)
                {
                    _tenant.Website = tenantModel.Website;
                }

                if (tenantModel.TwitterURL != _tenant.TwitterURL)
                {
                    _tenant.TwitterURL = tenantModel.TwitterURL;
                }

                if (tenantModel.FacebookURL != _tenant.FacebookURL)
                {
                    _tenant.FacebookURL = tenantModel.FacebookURL;
                }

                if (tenantModel.LinkedURL != _tenant.LinkedURL)
                {
                    _tenant.LinkedURL = tenantModel.LinkedURL;
                }

                if (tenantModel.GoogleplusURL != _tenant.GoogleplusURL)
                {
                    _tenant.GoogleplusURL = tenantModel.GoogleplusURL;
                }

                if (tenantModel.TenantName != _tenant.TenantName)
                {
                    _tenant.TenantName = tenantModel.TenantName;
                }

                if (tenantModel.Email != _tenant.Email)
                {
                    _tenant.Email = tenantModel.Email;
                }

                if (tenantModel.VisitingAddress != _tenant.VisitingAddress)
                {
                    _tenant.VisitingAddress = tenantModel.VisitingAddress;
                    _tenant.PostedAddress   = tenantModel.VisitingAddress;
                }

                if (tenantModel.AssignedUserId != _tenant.AssignedUserId)
                {
                    _tenant.AssignedUserId = tenantModel.AssignedUserId;
                }

                if (tenantModel.CountryId != _tenant.CountryId)
                {
                    _tenant.CountryId = tenantModel.CountryId;
                }

                if (tenantModel.Fax != _tenant.Fax)
                {
                    _tenant.Fax = tenantModel.Fax;
                }

                if (tenantModel.OrgNumber != _tenant.OrgNumber)
                {
                    _tenant.OrgNumber = tenantModel.OrgNumber;
                }

                if (tenantModel.Information != _tenant.Information)
                {
                    _tenant.Information = tenantModel.Information;
                }

                if (tenantModel.Information != _tenant.Information)
                {
                    _tenant.Information = tenantModel.Information;
                }
                if (tenantModel.Active != _tenant.Active)
                {
                    _tenant.Active = tenantModel.Active;
                }

                _tenant.ModifiedDate = DateTime.Now;
                _tenant.ModifiedBy   = _userInfo.ID;

                _tenant.ObjectState = ObjectState.Modified;
                _tenantService.Update(_tenant);
                _unitOfWork.SaveChanges();
                _helper.InsertLogActive(_logService, _unitOfWork, "Tenants", "Update tenant", 2, true);
                return(RedirectToAction("Index"));
            }
            else
            {
                _helper.InsertLogActive(_logService, _unitOfWork, "Tenants", "Update tenant", 2, false);
                return(View(tenantModel));
            }
        }
예제 #29
0
        public ActionResult Create(TenantModel tenantModel)
        {
            if (ModelState.IsValid)
            {
                var _tenantEntity = tenantModel.ToEntity();

                _tenantEntity.Active       = true;
                _tenantEntity.CreatedDate  = DateTime.Now;
                _tenantEntity.CreatedBy    = _userInfo.ID;
                _tenantEntity.ModifiedBy   = _userInfo.ID;
                _tenantEntity.ModifiedDate = DateTime.Now;
                _tenantEntity.DbName       = "MultiOrg_" + _tenantEntity.TenantNameAlias;
                try
                {
                    if (_tenantService.CheckAlias(_tenantEntity.TenantNameAlias))
                    {
                        // create directory folder tenant
                        _pathFiles = "/tenants/" + tenantModel.TenantNameAlias;
                        var _newPath = Server.MapPath(_pathFiles);
                        if (!Directory.Exists(_newPath))
                        {
                            Directory.CreateDirectory(_newPath);
                        }

                        // create file default
                        var _fileDefault     = "default.png";
                        var _sourceFile      = Path.Combine(Server.MapPath(_tempFiles), _fileDefault);
                        var _destinationFile = Path.Combine(Server.MapPath(_pathFiles), _fileDefault);
                        System.IO.File.Copy(_sourceFile, _destinationFile);

                        if (!string.IsNullOrEmpty(_logoModel.FileName))
                        {
                            _tenantEntity.CompanyLogo = _pathFiles + "/" + _logoModel.FileName;

                            //move a file from temps file to tenant folder
                            _sourceFile      = Path.Combine(Server.MapPath(_tempFiles), _logoModel.FileName);
                            _destinationFile = Path.Combine(Server.MapPath(_pathFiles), _logoModel.FileName);
                            if (System.IO.File.Exists(_destinationFile))
                            {
                                System.IO.File.Delete(_destinationFile);
                            }
                            System.IO.File.Move(_sourceFile, _destinationFile);

                            _logoModel = null;
                        }
                        else
                        {
                            _tenantEntity.CompanyLogo = _pathFiles + "/" + _fileDefault;
                        }

                        // insert new tenant
                        _tenantService.Insert(_tenantEntity);
                        _unitOfWork.SaveChanges();

                        // write log
                        _helper.InsertLogActive(_logService, _unitOfWork, "Tenants", "Insert new tenant", 1, true);
                        var result = new SqlQueryExcute().CreateDBByTenant(_tenantEntity.DbName, _tenantEntity.DbUsername, _tenantEntity.DbPassword);

                        // add new user
                        var _tenantId = _tenantService.GetTanentByAlias(_tenantEntity.TenantNameAlias).TenantId;
                        if (_tenantId > 0)
                        {
                            try
                            {
                                var _newUser = new crm_Users();
                                _newUser.Username = tenantModel.Username ?? _tenantEntity.DbUsername;

                                string encryptPassword = "";
                                string passwordSalt    = "";
                                passwordSalt    = EncryptProvider.GenerateSalt();
                                encryptPassword = EncryptProvider.EncryptPassword(tenantModel.Password, passwordSalt);

                                _newUser.PasswordSalt = passwordSalt;
                                _newUser.Password     = encryptPassword;

                                _newUser.TenantId      = _tenantId;
                                _newUser.CreatedDate   = DateTime.Now;
                                _newUser.Active        = true;
                                _newUser.Email         = tenantModel.ContactEmail ?? _tenantEntity.Email;
                                _newUser.DisplayName   = tenantModel.ContactName ?? _tenantEntity.TenantName;
                                _newUser.FullName      = tenantModel.ContactName ?? _tenantEntity.TenantName;
                                _newUser.FacebookURL   = _tenantEntity.FacebookURL;
                                _newUser.TwitterURL    = _tenantEntity.TwitterURL;
                                _newUser.GoogleplusURL = _tenantEntity.GoogleplusURL;
                                _newUser.LinkedURL     = _tenantEntity.LinkedURL;
                                _newUser.Image         = _tenantEntity.CompanyLogo;
                                _newUser.Phone         = tenantModel.ContactPhone;
                                _newUser.Mobile        = tenantModel.MobilePhone;
                                _userService.Insert(_newUser);
                                _unitOfWork.SaveChanges();

                                _helper.InsertLogActive(_logService, _unitOfWork, "Users", "Insert user tenant admin", 1, true);

                                // add tenant admin role
                                var _userId = _userService.GetUserByUsername(_newUser.Username).ID;
                                if (_userId > 0)
                                {
                                    try
                                    {
                                        // AssignedUserId
                                        var _ownTenantEntity = _tenantService.Find(_tenantId);
                                        _ownTenantEntity.AssignedUserId = _userId;
                                        _ownTenantEntity.ObjectState    = ObjectState.Modified;
                                        _tenantService.Update(_ownTenantEntity);
                                        _unitOfWork.SaveChanges();
                                        _helper.InsertLogActive(_logService, _unitOfWork, "Tenant", "Assigned user for tenant", 2, true);

                                        // create group role
                                        var _roleEntity = new crm_Roles();

                                        //Console.WriteLine(((WeekDays)1).ToString());

                                        // TenantAdmin = 512
                                        _roleEntity.RoleName       = UserGroupEnum.TenantAdmin.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.TenantAdmin + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.TenantAdmin;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        // add  Manager = 256
                                        _roleEntity                = new crm_Roles();
                                        _roleEntity.RoleName       = UserGroupEnum.Manager.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.Manager + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.Manager;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        // add  Support = 128
                                        _roleEntity                = new crm_Roles();
                                        _roleEntity.RoleName       = UserGroupEnum.Support.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.Support + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.Support;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        // Marketing=64
                                        _roleEntity                = new crm_Roles();
                                        _roleEntity.RoleName       = UserGroupEnum.Marketing.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.Marketing + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.Marketing;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        // Sales = 32
                                        _roleEntity                = new crm_Roles();
                                        _roleEntity.RoleName       = UserGroupEnum.Sales.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.Sales + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.Sales;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        //  NormalUser = 16
                                        _roleEntity                = new crm_Roles();
                                        _roleEntity.RoleName       = UserGroupEnum.NormalUser.ToString();
                                        _roleEntity.Active         = true;
                                        _roleEntity.MaskPermission = (int)UserGroupEnum.NormalUser + 15;
                                        _roleEntity.TenantId       = _tenantId;
                                        _roleEntity.PermissionType = (int)UserGroupEnum.NormalUser;
                                        _roleService.Insert(_roleEntity);
                                        _unitOfWork.SaveChanges();

                                        // map role tenant admin
                                        var _newRole = new crm_UserRoles();
                                        _newRole.RoleID = _roleService.GetRoleIdByPermisstionType(_tenantId, (int)UserGroupEnum.TenantAdmin);
                                        _newRole.UserID = _userId;
                                        _userRoleService.Insert(_newRole);
                                        _unitOfWork.SaveChanges();
                                        _helper.InsertLogActive(_logService, _unitOfWork, "User Role", "Insert role tenant admin for user", 1, true);
                                    }
                                    catch
                                    {
                                        _helper.InsertLogActive(_logService, _unitOfWork, "User Role", "Insert role tenant admin for user", 1, false);
                                    }
                                }
                            }
                            catch
                            {
                                _helper.InsertLogActive(_logService, _unitOfWork, "Users", "Insert user tenant admin", 1, false);
                            }
                        }
                    }
                    MessageBoxModel.ShowMessage = "Add tenant " + _tenantEntity.TenantName + " success!";
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    _helper.InsertLogActive(_logService, _unitOfWork, "Tenants", "Insert new tenant", 1, false);
                    return(View(tenantModel));
                }
            }

            return(View(tenantModel));
        }
예제 #30
0
        public string AddEditAction(CustomerModel model)
        {
            //Variables
            ActionResultModel resultModel = new ActionResultModel();
            crm_Customers     customer    = null;
            crm_Contacts      contact     = null;
            UserInfo          usInfo      = System.Web.HttpContext.Current.Session["UserInfo"] as UserInfo;
            bool   isSaveImageSuccess     = true;
            string pathFiles = "/Tenants/" + _userInfo.TenantAlias;
            long   orgNumber = 0;

            try
            {
                //Check case add or edit
                if (model.CustomerId > 0)
                {
                    customer = _customerService.GetCustomerByID(model.CustomerId);
                    if (model.ContactId > 0)
                    {
                        contact = _contactService.GetContactDefaultByCusID(model.CustomerId);
                    }
                }
                else
                {
                    customer = new crm_Customers();
                }
                #region Validate data
                //Check email vaild
                if (!GlobalFunctions.IsValidEmail(model.Email.Trim()))
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Email is invalid!";
                    return(JsonConvert.SerializeObject(resultModel));
                }

                if (_countryService.GetCountryById(model.CountryId) == null)
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Country is not exist!";
                    return(JsonConvert.SerializeObject(resultModel));
                }

                if (customer == null && model.CustomerId > 0)
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Customer is not exist!";
                    return(JsonConvert.SerializeObject(resultModel));
                }

                if (!long.TryParse(model.OrgNumber, out orgNumber))
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Org number must be numeric!";
                    return(JsonConvert.SerializeObject(resultModel));
                }

                if (!_customerService.CheckOrgNumberExist(model.CustomerId, model.OrgNumber.Trim()))
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Org number is exist!";
                    return(JsonConvert.SerializeObject(resultModel));
                }
                #endregion
                #region Set value for customer entity
                customer.CustomerName    = WebUtility.HtmlEncode(model.CustomerName.Trim());
                customer.Email           = model.Email.Trim();
                customer.PostedAddress   = WebUtility.HtmlEncode(model.PostedAddress.Trim());
                customer.VisitingAddress = WebUtility.HtmlEncode(model.VisitingAddress.Trim());
                customer.CountryId       = model.CountryId;
                customer.Fax             = WebUtility.HtmlEncode(model.Fax.Trim());
                customer.OrgNumber       = model.OrgNumber;
                customer.CreatedDate     = DateTime.Now;
                customer.CreatedBy       = usInfo.ID;
                customer.Description     = WebUtility.HtmlEncode(model.Description.Trim());
                customer.Website         = WebUtility.HtmlEncode(model.Website);
                customer.LinkedURL       = WebUtility.HtmlEncode(model.LinkedURL);
                customer.FacebookURL     = WebUtility.HtmlEncode(model.FacebookURL);
                customer.TwitterURL      = WebUtility.HtmlEncode(model.TwitterURL);
                customer.GoogleplusURL   = WebUtility.HtmlEncode(model.GoogleplusURL);
                customer.CustomerLogo    = _logoModel.FileName != null ? _logoModel.FileName : model.CustomerId > 0?customer.CustomerLogo:"";
                #endregion

                #region Set value for contact entity
                if (model.FirstName.Trim() != string.Empty ||
                    model.LastName.Trim() != string.Empty ||
                    model.Address.Trim() != string.Empty ||
                    model.ContactPhone.Trim() != string.Empty ||
                    model.MobilePhone.Trim() != string.Empty)
                {
                    if (contact != null)
                    {
                        contact.FirstName    = model.FirstName.Trim() != string.Empty ? WebUtility.HtmlEncode(model.FirstName.Trim()) : contact.FirstName;
                        contact.LastName     = model.LastName.Trim() != string.Empty ? WebUtility.HtmlEncode(model.LastName.Trim()) : contact.LastName;
                        contact.ContactPhone = model.ContactPhone.Trim() != string.Empty ? WebUtility.HtmlEncode(model.ContactPhone.Trim()) : contact.ContactPhone;
                        contact.MobilePhone  = model.MobilePhone.Trim() != string.Empty ? WebUtility.HtmlEncode(model.MobilePhone.Trim()) : contact.MobilePhone;
                        contact.Address      = model.Address.Trim() != string.Empty ? WebUtility.HtmlEncode(model.Address.Trim()) : contact.Address;
                    }
                    else
                    {
                        contact              = new crm_Contacts();
                        contact.FirstName    = WebUtility.HtmlEncode(model.FirstName.Trim());
                        contact.LastName     = WebUtility.HtmlEncode(model.LastName.Trim());
                        contact.ContactPhone = WebUtility.HtmlEncode(model.ContactPhone.Trim());
                        contact.MobilePhone  = WebUtility.HtmlEncode(model.MobilePhone.Trim());
                        contact.Address      = WebUtility.HtmlEncode(model.Address.Trim());
                        contact.IsDefault    = true;
                    }
                }
                #endregion

                #region Perform save data
                //Save image
                try
                {
                    if (_logoModel != null && !string.IsNullOrEmpty(_logoModel.FileName))
                    {
                        //move a file from temps file to tenant folder
                        var _sourceFile      = Path.Combine(Server.MapPath(_tempFiles), _logoModel.FileName);
                        var _destinationFile = Path.Combine(Server.MapPath(pathFiles), _logoModel.FileName);
                        if (System.IO.File.Exists(_destinationFile))
                        {
                            System.IO.File.Delete(_destinationFile);
                        }
                        System.IO.File.Move(_sourceFile, _destinationFile);

                        _logoModel = null;
                    }
                }
                catch
                {
                    isSaveImageSuccess = false;
                }
                if (isSaveImageSuccess)
                {
                    //Add
                    if (model.CustomerId <= 0)
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            _customerService.Insert(customer);
                            _unitOfWork.SaveChanges();
                            //_tenantUnitOfWork.SaveChanges();

                            if (contact != null)
                            {
                                contact.CustomerId = customer.CustomerId;
                                _contactService.Insert(contact);
                                _unitOfWork.SaveChanges();

                                //_tenantUnitOfWork.SaveChanges();
                            }
                            scope.Complete();
                        }
                    }
                    else//Edit
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            _customerService.Update(customer);
                            _unitOfWork.SaveChanges();

                            //_tenantUnitOfWork.SaveChanges();
                            if (contact != null)
                            {
                                contact.CustomerId = customer.CustomerId;
                                if (contact.ContactId > 0)
                                {
                                    _contactService.Update(contact);
                                }
                                else
                                {
                                    _contactService.Insert(contact);
                                }
                                _unitOfWork.SaveChanges();

                                //_tenantUnitOfWork.SaveChanges();
                            }
                            scope.Complete();
                        }
                    }
                    resultModel.IsSuccess = 1;
                    resultModel.Message   = "Data were saved successfully!";
                    _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0 ? "Insert new customer" : "Update customer", model.CustomerId <= 0 ? 1 : 2, true);
                }
                else
                {
                    resultModel.IsSuccess = 0;
                    resultModel.Message   = "Save image unsuccessfully!";
                    _helper.InsertLogActive(_logService, _unitOfWork, "Customers", "Save avatar image.", 1, false);
                }
                #endregion
            }
            catch (TransactionAbortedException te)
            {
                _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0? "Insert new customer":"Update customer", model.CustomerId <= 0?1:2, false);
            }
            catch (ApplicationException ex)
            {
                _helper.InsertLogActive(_logService, _unitOfWork, "Customers", model.CustomerId <= 0 ? "Insert new customer" : "Update customer", model.CustomerId <= 0 ? 1 : 2, false);
                resultModel.IsSuccess = 0;
                resultModel.Message   = "Data were saved unsuccessfully!";
            }
            return(JsonConvert.SerializeObject(resultModel));
        }
예제 #31
0
파일: Form1.cs 프로젝트: radtek/ImageEditor
        private void button1_Click(object sender, EventArgs e)
        {
            IWebDriver webDriver = new ChromeDriver();

            webDriver.Navigate().GoToUrl("https://teespring.com/login");

            var divRoot    = webDriver.FindElement(By.XPath("//div[@class='authentication__standalone js-user-auth-standalone authentication--email authentication--login_open']"));
            var divAuth    = divRoot.FindElement(By.XPath("//div[@class='authentication authentication--login js-user-login']"));
            var emailInput = divAuth.FindElement(By.Name("email"));

            DivClick(webDriver, emailInput, "*****@*****.**", 1000);

            var passInput = divAuth.FindElement(By.Name("password"));

            DivClick(webDriver, passInput, "19001560", 1000);

            var loginBtn = divAuth.FindElement(By.XPath("//input[@class='button button--primary authentication__button js-email-login-submit']"));

            loginBtn.Click();
            Thread.Sleep(1500);


            var tag = webDriver.FindElement(By.XPath("//meta[@name='csrf-token']"));

            CookieContainer container = new CookieContainer();

            foreach (var cc in webDriver.Manage().Cookies.AllCookies)
            {
                container.Add(new System.Net.Cookie(cc.Name, cc.Value, cc.Path, cc.Domain));
            }

            CustomWeb web   = new CustomWeb(container);
            string    token = tag.GetAttribute("content");

            web.TOKEN = token;

            //string result = web.SendRequest("https://teespring.com/login", "GET", null, true);
            //var doc = new HtmlAgilityPack.HtmlDocument();
            //doc.LoadHtml(result);
            //var metaNode = doc.DocumentNode.SelectSingleNode("//meta[@name='csrf-token']");
            //token = metaNode.GetAttributeValue("content", string.Empty);
            ////web.TOKEN = token;

            //var htmlWeb = new HtmlAgilityPack.HtmlWeb();
            //doc = htmlWeb.Load("https://teespring.com/login");
            //metaNode = doc.DocumentNode.SelectSingleNode("//meta[@name='csrf-token']");
            //token = metaNode.GetAttributeValue("content", string.Empty);
            ////web.TOKEN = token;

            //string url = "https://teespring.com/sessions";
            NameValueCollection nvc = new NameValueCollection();
            //nvc.Add("email", "*****@*****.**");
            //nvc.Add("password", "19001560");

            //string result = web.SendRequest(url, "POST", nvc, false, "application/x-www-form-urlencoded");

            //Console.WriteLine("login: "******"csrftoken", token, "/", "teespring.com"));
            //Console.WriteLine("result: "+result);

            string responseUrl = "";
            string result      = web.SendRequest("https://teespring.com/designs", "GET", null, ref responseUrl);

            Console.WriteLine("response url: " + responseUrl);

            // signed request
            string imageName = RandomStringOnly(8) + ".png";
            string signedUrl = "https://teespring.com/designs/sign_s3?s3_object_type=image/png&s3_object_name=" + imageName;

            result = web.SendRequest(signedUrl, "GET", null);
            Console.WriteLine("signed url: " + result);
            SignedResponse signedRes = JsonConvert.DeserializeObject <SignedResponse>(result);

            Console.WriteLine(signedUrl);

            // regist 1 signal
            string sign1Url = WebUtility.UrlDecode(signedRes.signed_request);

            Console.WriteLine(sign1Url);
            nvc.Clear();
            string tempUrl = sign1Url.Split('?')[1];

            string[] temp2 = tempUrl.Split('&');
            //nvc.Add("X-Amz-Algorithm", temp2[0].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("X-Amz-Credential", temp2[1].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("X-Amz-Date", temp2[2].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("X-Amz-Expires", temp2[3].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("X-Amz-SignedHeaders", temp2[4].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("x-amz-acl", temp2[5].Replace("X-Amz-Algorithm=", ""));
            //nvc.Add("X-Amz-Signature", temp2[6].Replace("X-Amz-Algorithm=", ""));
            nvc.Add("PNG",
                    ImageToBase64(Image.FromFile(@"D:\Auto\Logo\test.png"),
                                  System.Drawing.Imaging.ImageFormat.Png));
            result = web.SendCustomRequest(sign1Url, "OPTIONS", "teespring-usercontent.s3.amazonaws.com", null, true, "PUT");
            result = web.SendCustomRequest2(sign1Url, "PUT", "teespring-usercontent.s3.amazonaws.com", @"D:\Auto\Logo\test.png", false, "", false, "image/png");
            // result = web.SendCustomRequest(sign1Url, "POST", "teespring-usercontent.s3.amazonaws.com", null);
            Console.WriteLine("sign1url result: " + result);
            string uploadUrl = responseUrl.Replace("edit", "uploads");

            // string uploadImageUrl = "https://teespring.com/designs/lu32t4/uploads";
            string randName = RandomStringOnly(8);
            //LogoModel logo = new LogoModel(@"D:\Auto\Logo\1.png", "png");
            LogoModel logo = new LogoModel(imageName, "png");

            result = web.HttpUploadFileByJson(uploadUrl, JsonConvert.SerializeObject(logo));
            Console.WriteLine(result);


            // check valid url
            string title    = "this-is-ultimate-113";
            string checkUrl = "https://teespring.com/url/availability?url=" + title;

            result = web.SendCustomRequest(checkUrl, "GET", "teespring.com", null);
            Console.WriteLine("check url result: " + result);


            // put upload design
            string uploadDesignUrl = responseUrl.Replace("/edit", "");
            string lookupId        = uploadDesignUrl.Substring(uploadDesignUrl.LastIndexOf("/") + 1);
            //UploadDesignParameters desginParams = new UploadDesignParameters(lookupId, title.Replace("-", " "),
            //    title, "I will write some description on here!", "#ipshirt", imageName,
            //    "https://teespring-usercontent.s3.amazonaws.com/"+ imageName, "test.png");

            DesignParameter designs = new DesignParameter(lookupId, title.Replace("-", " "),
                                                          title, "I will write some description on here!", "#ipshirt", imageName,
                                                          "https://teespring-usercontent.s3.amazonaws.com/" + imageName, "test.png");


            string uploadResult = web.SendCustomRequest(uploadDesignUrl, "PUT", "teespring.com",
                                                        designs.ConvertToNVC(), false, "", false, "application/x-www-form-urlencoded", "application/json");

            //dynamic uploadResult = web.SendRequestWithStringData(uploadDesignUrl, "PUT", "teespring.com",
            //   desginParams.ToString(), false, "", false, "application/json");
            Console.WriteLine("upload reuslt: " + uploadResult);
            // camp id
            dynamic dResult = JsonConvert.DeserializeObject(uploadResult);
            string  campId  = dResult.campaign_id;
            // launch campaign
            string  launchUrl    = string.Format("https://teespring.com/campaigns/{0}/launch", campId);
            dynamic launchResult = web.SendRequestWithStringData(launchUrl, "POST", "teespring.com",
                                                                 "partnership=", false, "", false, "application/x-www-form-urlencoded; charset=UTF-8");
            //Console.WriteLine(launchResult);
            var doc = new HtmlAgilityPack.HtmlDocument();

            doc.LoadHtml(launchResult);
            var metaNode = doc.DocumentNode.SelectSingleNode("//meta[@name='csrf-token']");

            token     = metaNode.GetAttributeValue("content", string.Empty);
            web.TOKEN = token;

            string url = "https://teespring.com/sessions";

            nvc.Clear();
            nvc.Add("email", "*****@*****.**");
            nvc.Add("password", "19001560");

            result = web.SendRequest(url, "POST", nvc, false, "application/x-www-form-urlencoded");


            Console.WriteLine("login2 : " + result);

            launchResult = web.SendRequestWithStringData(launchUrl, "POST", "teespring.com",
                                                         "partnership=", false, "", false, "application/x-www-form-urlencoded; charset=UTF-8");

            string readyUrl = "https://teespring.com/designs/" + lookupId + "/assets_ready";
            //for (int i = 0; i < 5; i++)
            //{
            string finalResult = web.SendRequest(readyUrl, "GET", null);

            Console.WriteLine(finalResult);
            Thread.Sleep(2000);
            //}
        }
예제 #32
0
        public virtual IActionResult CustomLogoAdd(LogoModel logo)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageWidgets))
            {
                return(AccessDeniedView());
            }

            if (!ModelState.IsValid)
            {
                return(Json(new { Result = false, Errors = GetErrorsFromModelState() }));
            }

            //Get 1st product picture we use 1st picture of product to combine with logo
            ProductPicture productPicture = _productPictureModifierService
                                            .GetFirstProductPicture(logo.ProductId);

            if (productPicture == null)
            {
                throw new Exception("Product does not have any image");
            }

            byte[] logoBinary = _pictureService.LoadPictureBinary(_pictureService.GetPictureById(logo.PictureId));

            //Get new product image which has been merged with the logo uploaded
            (int, string)mergedPicture = _logoService.MergeProductPictureWithLogo(
                logoBinary,
                logo.PictureId,
                logo.ProductId,
                ProductPictureModifierUploadType.Predefined,
                logo.Size,
                logo.Opacity,
                logo.XCoordinate,
                logo.YCoordinate,
                overrideThumb: true);

            if (logo.AttributeValueId > 0)
            {
                var existingAttributeValue = _productAttributeService.
                                             GetProductAttributeValueById(logo.AttributeValueId);

                var existingProductPicture = _productService.GetProductPicturesByProductId(logo.ProductId)
                                             .First(x => x.PictureId == existingAttributeValue.PictureId);

                //update product attribute value
                existingAttributeValue.PictureId             = mergedPicture.Item1;
                existingAttributeValue.ImageSquaresPictureId = logo.PictureId;
                _productAttributeService.UpdateProductAttributeValue(existingAttributeValue);

                //update product picture
                existingProductPicture.PictureId = mergedPicture.Item1;
                _productService.UpdateProductPicture(existingProductPicture);

                return(Json(new { Result = true, AttributeId = logo.AttributeValueId }));
            }
            //Insert the image as product picture
            _productService.InsertProductPicture(new ProductPicture
            {
                ProductId    = logo.ProductId,
                PictureId    = mergedPicture.Item1,
                DisplayOrder = ProductPictureModifierDefault.MergedPictureDisplayOrder
            });

            ProductAttribute logoAttribute = _productPictureModifierService
                                             .GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogo)
                                             .FirstOrDefault() ?? throw new ArgumentException("Product Attribute Not Found");

            //get product's attribute for predefined logo attributes
            ProductAttributeMapping logoProductMapping = _productAttributeService
                                                         .GetProductAttributeMappingsByProductId(logo.ProductId)
                                                         .FirstOrDefault(x => x.ProductAttributeId == logoAttribute.Id);

            //create the mapping if it does not exist
            if (logoProductMapping == null)
            {
                logoProductMapping = new ProductAttributeMapping
                {
                    ProductAttributeId     = logoAttribute.Id,
                    ProductId              = logo.ProductId,
                    AttributeControlTypeId = (int)AttributeControlType.ImageSquares
                };
                _productAttributeService.InsertProductAttributeMapping(logoProductMapping);

                ////no logo attribute
                ////todo find a way to use the picture for this
                //_productAttributeService.InsertProductAttributeValue(new ProductAttributeValue
                //{
                //    ProductAttributeMappingId = logoProductMapping.Id,
                //    AttributeValueType = AttributeValueType.Simple,
                //    Name = _localizationService.GetResource("Widgets.ProductPictureModifier.Attributes.NoLogo"),
                //    ImageSquaresPictureId = 1,
                //    PictureId = productPicture.PictureId,
                //});

                //provision for manual upload by user
                Setting customUploadIconSetting = _settingService
                                                  .GetSetting(ProductPictureModifierDefault.UploadIconPictureIdSetting);
                var customUploadForLogoAttribute = new ProductAttributeValue
                {
                    ProductAttributeMappingId = logoProductMapping.Id,
                    AttributeValueType        = AttributeValueType.Simple,
                    Name = _localizationService.GetResource("Widgets.ProductPictureModifier.Attributes.Upload"),
                    ImageSquaresPictureId = int.Parse(customUploadIconSetting.Value),
                };
                _productAttributeService.InsertProductAttributeValue(customUploadForLogoAttribute);

                ProductAttribute productAttributeForCustomUpload = _productPictureModifierService
                                                                   .GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogoUpload)
                                                                   .FirstOrDefault() ?? throw new ArgumentException("Product Attribute Not Found for Custom Upload");

                //custom upload attribute mapping with product based on condition
                var customUploadProductAttributeMapping = new ProductAttributeMapping
                {
                    ProductAttributeId              = productAttributeForCustomUpload.Id,
                    ProductId                       = logo.ProductId,
                    AttributeControlTypeId          = (int)AttributeControlType.FileUpload,
                    ValidationFileAllowedExtensions = "png",
                    ConditionAttributeXml           = _productAttributeParser.AddProductAttribute(null, logoProductMapping,
                                                                                                  customUploadForLogoAttribute.Id.ToString())
                };
                _productAttributeService.InsertProductAttributeMapping(customUploadProductAttributeMapping);
            }

            //save the actual logo attribute
            var productAttributeValue = new ProductAttributeValue
            {
                ProductAttributeMappingId = logoProductMapping.Id,
                AttributeValueType        = AttributeValueType.Simple,
                Name = "Custom Logo",
                ImageSquaresPictureId = logo.PictureId,
                PictureId             = mergedPicture.Item1,
            };

            _productAttributeService.InsertProductAttributeValue(productAttributeValue);

            //Logo Position for custom upload
            LogoPosition logoPosition = _logoPositionService.GetByProductId(logo.ProductId);

            if (logo.MarkAsDefault || IsLogoSettingNew(logoPosition))
            {
                logoPosition.Size        = logo.Size;
                logoPosition.XCoordinate = logo.XCoordinate;
                logoPosition.YCoordinate = logo.YCoordinate;
                logoPosition.Opacity     = logo.Opacity;
                _logoPositionService.Update(logoPosition);
            }

            return(Json(new { Result = true, AttributeId = productAttributeValue.Id }));
        }
예제 #33
0
 private void InitLogo(LogoModel logoModel)
 {
     if (logoModel.HasLogo)
     {
         AddChildToMaterialChilds(logoModel);
     }
     logoModel.PropertyChanged += (s, e) =>
     {
         if (e.PropertyName == "HasLogo")
         {
             if (MaterialModel.LogoModel.HasLogo && MaterialChilds.Contains(logoModel) == false)
             {
                 AddChildToMaterialChilds(logoModel);
             }
             if (MaterialModel.LogoModel.HasLogo == false && MaterialChilds.Contains(logoModel))
             {
                 RemoveChildFromMaterialChilds(logoModel);
             }
         }
     };
 }
예제 #34
0
        private Image CreateLogoImage(LogoModel logoModel)
        {
            var createdLogoImage = new Image
            {
                DataContext = logoModel,
                Stretch = Stretch.Fill,
                Focusable = CanManipulateLogos,
                Tag = logoModel
            };

            if (CanManipulateLogos)
            {
                createdLogoImage.Cursor = Cursors.Hand;
                createdLogoImage.PreviewKeyUp += element_PreviewKeyUp;
            }

            var sourceBinding = new Binding(nameof(LogoModel.LogoImage)) {Mode = BindingMode.OneWay};
            createdLogoImage.SetBinding(Image.SourceProperty, sourceBinding);

            var heightBinding = new Binding(nameof(LogoModel.Height)) {Mode = BindingMode.TwoWay};
            createdLogoImage.SetBinding(HeightProperty, heightBinding);

            var widthBinding = new Binding(nameof(LogoModel.Width)) {Mode = BindingMode.TwoWay};
            createdLogoImage.SetBinding(WidthProperty, widthBinding);

            var topBinding = new Binding(nameof(LogoModel.TopMargin)) {Mode = BindingMode.TwoWay};
            createdLogoImage.SetBinding(TopProperty, topBinding);

            var leftBinding = new Binding(nameof(LogoModel.LeftMargin)) {Mode = BindingMode.TwoWay};
            createdLogoImage.SetBinding(LeftProperty, leftBinding);

            createdLogoImage.SetValue(AutomationProperties.AutomationIdProperty, "CanvasLogoImage");
            Children.Add(createdLogoImage);
            return createdLogoImage;
        }