Beispiel #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.FileName         = "default.txt";
            ofd.InitialDirectory = @"C:\";
            ofd.Filter           =
                "テキストファイル(*.txt)|*.txt|すべてのファイル(*.*)|*.*";
            ofd.FilterIndex      = 2;
            ofd.Title            = "開くファイルを選択してください";
            ofd.RestoreDirectory = true;
            ofd.CheckFileExists  = true;
            ofd.CheckPathExists  = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FullText = File.ReadAllText(ofd.FileName, System.Text.Encoding.GetEncoding("Shift_JIS"));
            }
            else
            {
                this.Close();
            }

            FormatText = System.Text.RegularExpressions.Regex.Replace(
                FullText.Replace("\r", "").Replace("\n", "").Replace(" ", ""),
                @"《.*?》 ", "");

            //MessageBox.Show(FormatText);

            TextQ = new Queue <string>(FormatText.Split(' '));
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            FormatText format = FormatText.None;

            Console.WriteLine("Параметры надписи: {0}", format);
            Console.WriteLine("Введите:\n\t1: bold\n\t2: italic\n\t3: underline\n");
            while (true)
            {
                int n = int.Parse(Console.ReadLine());
                switch (n)
                {
                case 1: format = format ^ FormatText.Bold;
                    break;

                case 2: format = format ^ FormatText.Italic;
                    break;

                case 3: format = format ^ FormatText.Underline;
                    break;

                default: Console.WriteLine("invalid value, please input a number from 1 to 3");
                    break;
                }
                Console.WriteLine("Параметры надписи: " + format);
                Console.WriteLine("Введите:\n\t1: bold\n\t2: italic\n\t3: underline\n");
            }
        }
        /// <summary>
        /// Formats the order note text
        /// </summary>
        /// <param name="orderNote">Order note</param>
        /// <returns>Formatted text</returns>
        public static string FormatOrderNoteText(this OrderNote orderNote)
        {
            if (orderNote == null)
                throw new ArgumentNullException("orderNote");

            return FormatText.ConvertText(orderNote.Note);
        }
        public virtual async Task PrepareVendorReviewModel(VendorReviewModel model,
            VendorReview vendorReview, bool excludeProperties, bool formatReviewText)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (vendorReview == null)
                throw new ArgumentNullException("vendorReview");
            var vendor = await _vendorService.GetVendorById(vendorReview.VendorId);
            var customer = await _customerService.GetCustomerById(vendorReview.CustomerId);

            model.Id = vendorReview.Id;
            model.VendorId = vendorReview.VendorId;
            model.VendorName = vendor.Name;
            model.CustomerId = vendorReview.CustomerId;
            model.CustomerInfo = customer != null ? customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest") : "";
            model.Rating = vendorReview.Rating;
            model.CreatedOn = _dateTimeHelper.ConvertToUserTime(vendorReview.CreatedOnUtc, DateTimeKind.Utc);
            if (!excludeProperties)
            {
                model.Title = vendorReview.Title;
                if (formatReviewText)
                    model.ReviewText = FormatText.ConvertText(vendorReview.ReviewText);
                else
                    model.ReviewText = vendorReview.ReviewText;
                model.IsApproved = vendorReview.IsApproved;
            }
        }
Beispiel #5
0
        /// <summary>
        /// метод для проверки модульного теста
        /// к полученной из метода Read() строке добавляет лишние координаты "555.555,555.555"
        /// в тесте при помощи Moq мы заменяем ожидаемое от него значение строки
        /// на входящее значение "11.11,22.22", игнорируя код, который в нем реализован
        /// </summary>
        /// <param name="AllText"></param>
        /// <returns></returns>
        public static string Convert2(string AllText)
        {
            FormatText Text1  = new FormatText();
            string     MyText = Text1.FormatMyText(AllText);

            return(MyText);
        }
Beispiel #6
0
 static void Main(string[] args)
 {
     try
     {
         // ask for a string input and read it
         Console.WriteLine("Syötä merkkijono: ");
         string inputText = Console.ReadLine();
         while (true)
         {
             try
             {
                 // asks what user want to do with the input string and reads the selection(s)
                 Console.WriteLine("\nValitse haluamasi käsittely, voit antaa useamman käsittelyn kerralla yhtenä merkkijonona (esim '123'): ");
                 Console.WriteLine("- 1: isoiksi kirjaimiksi");
                 Console.WriteLine("- 2: pieniksi kirjaimiksi");
                 Console.WriteLine("- 3: otsikoksi");
                 Console.WriteLine("- 4: palindromiksi");
                 Console.WriteLine("- 0: Lopettaa ohjelman\n");
                 Console.Write("Valinta: ");
                 string inputNmbs = Console.ReadLine();
                 Console.WriteLine();
                 FormatText formatter = new FormatText(StartDelegate); // create a delegate instance
                 if (inputNmbs.Contains("1"))                          // sets delegate to include method Format1
                 {
                     formatter += Format1;
                 }
                 if (inputNmbs.Contains("2")) // sets delegate to include method Format2
                 {
                     formatter += Format2;
                 }
                 if (inputNmbs.Contains("3")) // sets delegate to include method Format3
                 {
                     formatter += Format3;
                 }
                 if (inputNmbs.Contains("4")) // sets delegate to include method Format4
                 {
                     formatter += Format4;
                 }
                 if (inputNmbs.Contains("0")) // ends program
                 {
                     Console.WriteLine("Ohjelma lopettiin onnistuneesti.");
                     break;
                 }
                 formatter(inputText);
             }
             catch (ArgumentNullException ex)
             {
                 Console.WriteLine("Parametrissa ongelma: " + ex.Message);
             }
         }
     }
     catch (OutOfMemoryException ex)
     {
         Console.WriteLine("Muisti loppu: " + ex.Message);
     }
     catch (ArgumentOutOfRangeException ex)
     {
         Console.WriteLine("Syötteessä ongelma: " + ex.Message);
     }
 }
Beispiel #7
0
        public void DrawString(string text, FormatText format, double x, double y, double height, double width, XStringFormat location)
        {
            XFont font;

            switch (format)
            {
            case FormatText.Title:
                font = new XFont(FONT, 18, XFontStyle.Bold);
                break;

            case FormatText.Bold:
                font = new XFont(FONT, 11, XFontStyle.Bold);
                break;

            case FormatText.Italic:
                font = new XFont(FONT, 11, XFontStyle.Italic);
                break;

            case FormatText.BoldItalic:
                font = new XFont(FONT, 11, XFontStyle.BoldItalic);
                break;

            case FormatText.Regular:
            default:
                font = new XFont(FONT, 11, XFontStyle.Regular);
                break;
            }

            _gfx.DrawString(text, font, XBrushes.Black, new XRect(x, y, width, height), location);
        }
        public async Task <bool> Handle(SendProductAskQuestionMessageCommand request, CancellationToken cancellationToken)
        {
            await _workflowMessageService.SendProductQuestionMessage(request.Customer, request.Store,
                                                                     request.Language.Id, request.Product, request.Model.Email, request.Model.FullName, request.Model.Phone,
                                                                     FormatText.ConvertText(request.Model.Message));

            return(true);
        }
    public static LineScript interpret(string rowText)
    {
        string mainText;
        int    indentLevel = 0;

        mainText = rowText;
        while (mainText.StartsWith("  ") || mainText.StartsWith("\t"))
        {
            indentLevel++;
            if (mainText.StartsWith("  "))
            {
                mainText = mainText.Remove(0, 2);
            }
            else
            {
                mainText = mainText.Remove(0, 1);
            }
        }
        mainText.Trim();

        if (Label.isMatch(mainText))
        {
            Debug.Log("la " + mainText);
            return(new Label(rowText, "", indentLevel, mainText));
        }
        else if (Speaker.isMatch(mainText))
        {
            Debug.Log("spe " + mainText);
            return(new Speaker(rowText, "", indentLevel, mainText));
        }
        else if (Material.isMatch(mainText))
        {
            Debug.Log("mat " + mainText);
            return(new Material(rowText, "", indentLevel, mainText));
        }
        else if (Assignment.isMatch(mainText))
        {
            Debug.Log("ass " + mainText);
            return(new Assignment(rowText, "", indentLevel, mainText));
        }
        else if (Order.isMatch(mainText))
        {
            Debug.Log("ode " + mainText);
            return(new Order(rowText, "", indentLevel, mainText));
        }
        else if (Selection.isMatch(mainText))
        {
            Debug.Log("sel " + mainText);
            return(new Selection(rowText, "", indentLevel, mainText));
        }
        else if (FormatText.isMatch(mainText))
        {
            Debug.Log("sel " + mainText);
            return(new FormatText(rowText, mainText, indentLevel, ""));
        }

        return(new LineScript(rowText, mainText, indentLevel, ""));
    }
Beispiel #10
0
        /// <summary>
        /// Formats the customer note text
        /// </summary>
        /// <param name="customerNote">Customer note</param>
        /// <returns>Formatted text</returns>
        public static string FormatCustomerNoteText(this CustomerNote customerNote)
        {
            if (customerNote == null)
            {
                throw new ArgumentNullException("customerNote");
            }

            return(FormatText.ConvertText(customerNote.Note));
        }
        public static string FormatReturnRequestNoteText(this ReturnRequestNote returnRequestNote)
        {
            if (returnRequestNote == null)
            {
                throw new ArgumentNullException("returnRequestNote");
            }

            return(FormatText.ConvertText(returnRequestNote.Note));
        }
Beispiel #12
0
        public async Task <bool> Handle(SendProductEmailAFriendMessageCommand request, CancellationToken cancellationToken)
        {
            await _messageProviderService.SendProductEmailAFriendMessage(request.Customer, request.Store,
                                                                         request.Language.Id, request.Product,
                                                                         request.Model.YourEmailAddress, request.Model.FriendEmail,
                                                                         FormatText.ConvertText(request.Model.PersonalMessage));

            return(true);
        }
Beispiel #13
0
        /// <summary>
        /// Formats the vendor note text
        /// </summary>
        /// <param name="vendorNote">Vendor note</param>
        /// <returns>Formatted text</returns>
        public static string FormatVendorNoteText(this VendorNote vendorNote)
        {
            if (vendorNote == null)
            {
                throw new ArgumentNullException("vendorNote");
            }

            return(FormatText.ConvertText(vendorNote.Note));
        }
        /// <summary>
        /// Formats the order note text
        /// </summary>
        /// <param name="orderNote">Order note</param>
        /// <returns>Formatted text</returns>
        public static string FormatOrderNoteText(this ShipmentNote shipmentNote)
        {
            if (shipmentNote == null)
            {
                throw new ArgumentNullException("orderNote");
            }

            return(FormatText.ConvertText(shipmentNote.Note));
        }
Beispiel #15
0
 public string FullTrace()
 {
     return(FormatText.JoinLines(
                "Allocation settings:",
                $"  Count: {Count}",
                $"  Size: {Size}; IsRandomized: {RandomizeLength}",
                $"  In Parallel: {InParallel}",
                $"  AllocDelay: {AllocDelayMS}ms; IsRandomized: {RandomizeAllocDelay}",
                $"  AllocTries: {AllocTries}",
                $"  AwaitDisposal: {AwaitFragmentDisposal}; {FragmentDisposeAfterMS}ms; IsRandomized: {RandomizeFragDisposal}"
                ));
 }
Beispiel #16
0
        public void ShouldFormatTextIntoString()
        {
            //Arrange
            Text       textToFormat = new TextOf("any text {0} {1}");
            FormatText subject      = new FormatText(textToFormat, new TextOf("Brian"), new TextOf("Peg"));

            //Act
            string actual = subject;

            //Assert
            actual.Should().Be("any text Brian Peg");
        }
        public async Task <ContactVendorModel> Handle(ContactVendorSendCommand request, CancellationToken cancellationToken)
        {
            var subject = _commonSettings.SubjectFieldOnContactUsForm ? request.Model.Subject : null;
            var body    = FormatText.ConvertText(request.Model.Enquiry);

            await _workflowMessageService.SendContactVendorMessage(_workContext.CurrentCustomer, request.Store, request.Vendor, _workContext.WorkingLanguage.Id,
                                                                   request.Model.Email.Trim(), request.Model.FullName, subject, body);

            request.Model.SuccessfullySent = true;
            request.Model.Result           = _localizationService.GetResource("ContactVendor.YourEnquiryHasBeenSent");
            return(request.Model);
        }
        /// <summary>
        /// Called by in business entity sub-classes in their property setters to set the value of the property.
        /// If the business Object is not in a loading state, this method performs validation on the property
        /// <example>Example:
        /// <code>
        ///   Set(ByVal Value As String)
        ///       MyBase.SetPropertyValue("SL_DatabaseConnection", _strSL_DatabaseConnection, Value)
        ///   End Set
        /// </code>
        /// </example>
        /// </summary>
        /// <param name="propertyName">Property Name</param>
        /// <param name="currentValue">Current property value</param>
        /// <param name="newValue">New property value</param>
        protected void SetPropertyValue(String propertyName, ref String currentValue, String newValue)
        {
            if (currentValue == null)
            {
                if (newValue == null)
                {
                    return;
                }
            }
            else if (newValue != null && currentValue.Equals(newValue))
            {
                return;
            }

            if (!this.IsLoading)
            {
                _hasBeenValidated = false;
                _isDirty          = true;
                this.BeforePropertyChanged(propertyName);

                //only apply character casing rules after the Object is loaded.
                CharacterCasing characterCasing = SharedCharacterCasingRules.GetManager(this.GetType()).GetRuleForProperty(propertyName);

                currentValue = characterCasing != CharacterCasing.None ? FormatText.ApplyCharacterCasing(newValue, characterCasing) : newValue;

                CheckRulesForProperty(propertyName);
                InternalRaisePropertyChanged(propertyName);
                InternalRaisePropertyChanged(_STRING_ISDIRTY);
                InternalRaisePropertyChanged(_STRING_HASBEENVALIDATED);
                InternalRaisePropertyChanged(_STRING_ERROR);
                InternalRaisePropertyChanged(_STRING_HASERRORS);
                InternalRaisePropertyChanged(_STRING_HASNOERRORS);

                if (this.ThrowExceptionFromPropertySetters)
                {
                    String error = this[propertyName];

                    if (!(String.IsNullOrEmpty(error)))
                    {
                        throw new Exception(error);
                    }
                }

                this.AfterPropertyChanged(propertyName);
            }
            else
            {
                //since we are loading, just set the value
                currentValue = newValue;
            }
        }
Beispiel #19
0
        private void button_2_Click(object sender, EventArgs e)
        {
            string[] shortDateString;
            DateTime today;

            if (Configs.CmsName == "Qiwen")
            {
                TextBox textBox0 = this.textBox_0;
                shortDateString    = new string[] { "SELECT * FROM [Ws_BookList] WHERE bookupdatetime BETWEEN '", null, null, null, null };
                today              = DateTime.Today;
                shortDateString[1] = today.ToShortDateString();
                shortDateString[2] = "' AND '";
                today              = DateTime.Today.AddDays(1);
                shortDateString[3] = today.ToShortDateString();
                shortDateString[4] = "' ORDER BY bookupdatetime ASC";
                textBox0.Text      = string.Concat(shortDateString);
            }
            else if (Configs.CmsName == "Jieqi")
            {
                TextBox textBox = this.textBox_0;
                shortDateString = new string[] { "SELECT * FROM `jieqi_article_article` WHERE `lastupdate` BETWEEN '", null, null, null, null };
                int time = FormatText.GetTime(DateTime.Today);
                shortDateString[1] = time.ToString();
                shortDateString[2] = "' AND '";
                today = DateTime.Today;
                time  = FormatText.GetTime(today.AddDays(1));
                shortDateString[3] = time.ToString();
                shortDateString[4] = "' ORDER BY `lastupdate` ASC";
                textBox.Text       = string.Concat(shortDateString);
            }
            else if (Configs.CmsName != "Cnend")
            {
                this.textBox_0.Text = Localization.Get("请输入SQL语句");
            }
            else
            {
                TextBox textBox01 = this.textBox_0;
                shortDateString = new string[] { "SELECT * FROM [list_book] WHERE list_gxdate BETWEEN ", null, null, null, null };
                decimal value = this.numericUpDown_1.Value;
                shortDateString[1] = value.ToString();
                shortDateString[2] = " AND ";
                value = this.numericUpDown_0.Value;
                shortDateString[3] = value.ToString();
                shortDateString[4] = " ORDER BY list_gxdate ASC";
                textBox01.Text     = string.Concat(shortDateString);
            }
        }
Beispiel #20
0
        public void ConvertTest()
        {
            //arange
            Mock <FormatText> mock = new Mock <FormatText>();

            mock.Setup(m => m.FormatMyText(It.IsAny <string>())).Returns <string>(total => total);
            FormatText target = mock.Object;
            string     s      = target.FormatMyText("11.11,22.22");

            //act

            string s1 = ReadDataNew.Convert(s);


            //assert
            Assert.AreEqual("X: 11,11Y: 22,22", s1);
        }
Beispiel #21
0
        public virtual async Task PrepareProductReviewModel(ProductReviewModel model,
                                                            ProductReview productReview, bool excludeProperties, bool formatReviewText)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (productReview == null)
            {
                throw new ArgumentNullException("productReview");
            }
            var product = await _productService.GetProductById(productReview.ProductId);

            var customer = await _customerService.GetCustomerById(productReview.CustomerId);

            var store = await _storeService.GetStoreById(productReview.StoreId);

            model.Id           = productReview.Id;
            model.StoreName    = store != null ? store.Shortcut : "";
            model.ProductId    = productReview.ProductId;
            model.ProductName  = product.Name;
            model.CustomerId   = productReview.CustomerId;
            model.CustomerInfo = customer != null?customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest") : "";

            model.Rating    = productReview.Rating;
            model.CreatedOn = _dateTimeHelper.ConvertToUserTime(productReview.CreatedOnUtc, DateTimeKind.Utc);
            model.Signature = productReview.Signature;
            if (!excludeProperties)
            {
                model.Title = productReview.Title;
                if (formatReviewText)
                {
                    model.ReviewText = FormatText.ConvertText(productReview.ReviewText);
                    model.ReplyText  = FormatText.ConvertText(productReview.ReplyText);
                }
                else
                {
                    model.ReviewText = productReview.ReviewText;
                    model.ReplyText  = productReview.ReplyText;
                }
                model.IsApproved = productReview.IsApproved;
            }
        }
 protected override void OnClosing(CancelEventArgs e)
 {
     for (int i = 0; i < ListClients.work_collection.Count(); i++)
     {
         if (ListClients.work_collection[i] != null)
         {
             if (ListClients.work_collection[i].BackgroundWorker5.IsBusy)
             {
                 ListClients.work_collection[i].BackgroundWorker5.CancelAsync();
             }
         }
     }
     if (FormatText.Timer_1_State())
     {
         FormatText.Stop();
     }
     tbi.Dispose();
     this.Width = 640;
     Nirvana.Properties.Settings.Default.Save();
     base.OnClosing(e);
     Application.Current.Shutdown();
 }
        public virtual async Task <(IEnumerable <NewsCommentModel> newsCommentModels, int totalCount)> PrepareNewsCommentModel(string filterByNewsItemId, int pageIndex, int pageSize)
        {
            IList <NewsComment> comments;

            if (!String.IsNullOrEmpty(filterByNewsItemId))
            {
                //filter comments by news item
                var newsItem = await _newsService.GetNewsById(filterByNewsItemId);

                comments = newsItem.NewsComments.OrderBy(bc => bc.CreatedOnUtc).ToList();
            }
            else
            {
                //load all news comments
                comments = await _newsService.GetAllComments("");
            }
            var customerService = _serviceProvider.GetRequiredService <ICustomerService>();
            var items           = new List <NewsCommentModel>();

            foreach (var newsComment in comments.PagedForCommand(pageIndex, pageSize))
            {
                var commentModel = new NewsCommentModel
                {
                    Id            = newsComment.Id,
                    NewsItemId    = newsComment.NewsItemId,
                    NewsItemTitle = (await _newsService.GetNewsById(newsComment.NewsItemId))?.Title,
                    CustomerId    = newsComment.CustomerId
                };
                var customer = await customerService.GetCustomerById(newsComment.CustomerId);

                commentModel.CustomerInfo = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest");
                commentModel.CreatedOn    = _dateTimeHelper.ConvertToUserTime(newsComment.CreatedOnUtc, DateTimeKind.Utc);
                commentModel.CommentTitle = newsComment.CommentTitle;
                commentModel.CommentText  = FormatText.ConvertText(newsComment.CommentText);
                items.Add(commentModel);
            }
            return(items, comments.Count);
        }
        public virtual async Task PrepareVendorReviewModel(VendorReviewModel model,
                                                           VendorReview vendorReview, bool excludeProperties, bool formatReviewText)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (vendorReview == null)
            {
                throw new ArgumentNullException(nameof(vendorReview));
            }

            var vendor = await _vendorService.GetVendorById(vendorReview.VendorId);

            var customer = await _customerService.GetCustomerById(vendorReview.CustomerId);

            model.Id           = vendorReview.Id;
            model.VendorId     = vendorReview.VendorId;
            model.VendorName   = vendor.Name;
            model.CustomerId   = vendorReview.CustomerId;
            model.CustomerInfo = customer != null ? !string.IsNullOrEmpty(customer.Email) ? customer.Email : _translationService.GetResource("Admin.Customers.Guest") : "";
            model.Rating       = vendorReview.Rating;
            model.CreatedOn    = _dateTimeService.ConvertToUserTime(vendorReview.CreatedOnUtc, DateTimeKind.Utc);
            if (!excludeProperties)
            {
                model.Title = vendorReview.Title;
                if (formatReviewText)
                {
                    model.ReviewText = FormatText.ConvertText(vendorReview.ReviewText);
                }
                else
                {
                    model.ReviewText = vendorReview.ReviewText;
                }
                model.IsApproved = vendorReview.IsApproved;
            }
        }
Beispiel #25
0
        public virtual async Task <(IEnumerable <BlogCommentModel> blogComments, int totalCount)> PrepareBlogPostCommentsModel(string filterByBlogPostId, int pageIndex, int pageSize)
        {
            IList <BlogComment> comments;
            var storeId = string.IsNullOrEmpty(_workContext.CurrentCustomer.StaffStoreId) ? "" : _workContext.CurrentCustomer.StaffStoreId;

            if (!string.IsNullOrEmpty(filterByBlogPostId))
            {
                //filter comments by blog
                var blogPost = await _blogService.GetBlogPostById(filterByBlogPostId);

                comments = await _blogService.GetBlogCommentsByBlogPostId(blogPost.Id);
            }
            else
            {
                //load all blog comments
                comments = await _blogService.GetAllComments("", storeId);
            }
            var commentsList = new List <BlogCommentModel>();

            foreach (var blogComment in comments.Skip((pageIndex - 1) * pageSize).Take(pageSize))
            {
                var commentModel = new BlogCommentModel
                {
                    Id            = blogComment.Id,
                    BlogPostId    = blogComment.BlogPostId,
                    BlogPostTitle = blogComment.BlogPostTitle,
                    CustomerId    = blogComment.CustomerId
                };
                var customer = await _customerService.GetCustomerById(blogComment.CustomerId);

                commentModel.CustomerInfo = !string.IsNullOrEmpty(customer.Email) ? customer.Email : _translationService.GetResource("Admin.Customers.Guest");
                commentModel.CreatedOn    = _dateTimeService.ConvertToUserTime(blogComment.CreatedOnUtc, DateTimeKind.Utc);
                commentModel.Comment      = FormatText.ConvertText(blogComment.CommentText);
                commentsList.Add(commentModel);
            }
            return(commentsList, comments.Count);
        }
Beispiel #26
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="customAttributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual async Task <string> FormatAttributes(IList <CustomAttribute> customAttributes,
                                                            Customer customer,
                                                            string serapator     = "<br />",
                                                            bool htmlEncode      = true,
                                                            bool renderPrices    = true,
                                                            bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            if (customAttributes == null || !customAttributes.Any())
            {
                return(result.ToString());
            }

            var attributes = await _checkoutAttributeParser.ParseCheckoutAttributes(customAttributes);

            for (int i = 0; i < attributes.Count; i++)
            {
                var attribute = attributes[i];
                var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
                for (var j = 0; j < valuesStr.Count; j++)
                {
                    var valueStr           = valuesStr[j];
                    var formattedAttribute = "";
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentStore.Url.TrimEnd('/'), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        var attributeValue = attribute.CheckoutAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                        if (attributeValue != null)
                        {
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id));
                            if (renderPrices)
                            {
                                double priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer)).checkoutPrice;
                                double priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                if (priceAdjustmentBase > 0)
                                {
                                    string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
                                    formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                }
                            }
                        }
                        //encode (if required)
                        if (htmlEncode)
                        {
                            formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                        }
                    }

                    if (!String.IsNullOrEmpty(formattedAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(formattedAttribute);
                    }
                }
            }

            return(result.ToString());
        }
Beispiel #27
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            double lineSpacing = 0;
            List <FormattedText> _listFormattedText = new List <FormattedText>();
            List <FormatText>    _listFormatText    = new List <FormatText>();
            List <ListText>      _listText          = new List <ListText>();
            //Khai bao toa do boi den.
            Point p1 = new Point(15, 6.8);
            Point p2 = new Point(25.5, 56.8);
            List <ItemFormatText> listFont = new List <ItemFormatText>();

            listFont.Add(new ItemFormatText {
                viTriKetThuc = 8, _fontSize = 10, _fontType = "Arial"
            });
            listFont.Add(new ItemFormatText {
                viTriKetThuc = 13, _fontSize = 30, _fontType = "Arial"
            });
            listFont.Add(new ItemFormatText {
                viTriKetThuc = 16, _fontSize = 18, _fontType = "Arial"
            });
            listFont.Add(new ItemFormatText {
                viTriKetThuc = 32, _fontSize = 22, _fontType = "Arial"
            });
            List <ItemText> listText = new List <ItemText>();

            listText.Add(new ItemText {
                _text = "___123", _fontSize = 10, _fontType = "Arial"
            });
            listText.Add(new ItemText {
                _text = "__4567", _fontSize = 30, _fontType = "Arial"
            });
            listText.Add(new ItemText {
                _text = "897__12345678", _fontSize = 18, _fontType = "Arial"
            });
            listText.Add(new ItemText {
                _text = "___456", _fontSize = 22, _fontType = "Arial"
            });
            List <TemplateFormattedText> listTu = new List <TemplateFormattedText>();

            if (Text[0] == '_')
            {
                listTu.Add(new TemplateFormattedText()
                {
                    Tu = "", KhoangTrang = Text.Substring(0, viTriDauTienKhacKT(Text, 0))
                });
            }
            var    listCat  = Text.Split('_');
            string sumSpace = "";

            for (int i = 0; i < listCat.Length; i++)
            {
                if (!string.IsNullOrEmpty(listCat[i]))
                {
                    sumSpace = "";
                    int j = i + 1;
                    for (j = i + 1; j < listCat.Length; j++)
                    {
                        if (string.IsNullOrEmpty(listCat[j]))
                        {
                            sumSpace += "_";
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (i < viTriKhacKTCuoiList(listCat))
                    {
                        sumSpace += "_";
                    }
                    listTu.Add(new TemplateFormattedText()
                    {
                        Tu = listCat[i], KhoangTrang = sumSpace
                    });
                    i = j - 1;
                }
            }
            string xauHoanChinh   = "";
            double sumWidth       = 0;
            int    viTriCuoiChuoi = 0;
            int    viTriCuoiKT    = 0;
            int    viTriDauChuoi  = 0;
            int    viTriDauKT     = 0;
            int    positionFontTu = 0;
            int    positionFontKT = 0;
            double maxBaseline    = 0;
            double _height        = 0;
            double x     = 0;
            double check = 0;

            foreach (var item in listTu)
            {
                if (item.Tu.Length > 0)
                {
                    viTriCuoiChuoi = viTriCuoiKT + item.Tu.Length;
                }
                if (viTriCuoiChuoi == 0)
                {
                    viTriCuoiKT = viTriCuoiChuoi + item.KhoangTrang.Length - 1;
                }
                else
                {
                    viTriCuoiKT = viTriCuoiChuoi + item.KhoangTrang.Length;
                }
                positionFontTu = viTriDinhDang(listFont, viTriCuoiChuoi);
                positionFontKT = viTriDinhDang(listFont, viTriCuoiKT);
                if (item.Tu.Length > 0)
                {
                    viTriDauChuoi = viTriCuoiChuoi - item.Tu.Length + 1;
                }
                if (item.KhoangTrang.Length > 0)
                {
                    viTriDauKT = viTriCuoiKT - item.KhoangTrang.Length + 1;
                }
                // sumWidth += widthXau(item.Tu, listFont[positionFontTu]);
                check     = widthXau(item.Tu, listFont[positionFontTu]) - widthXau(listFont, item.Tu, viTriDauChuoi, viTriCuoiChuoi);
                sumWidth += widthXau(listFont, item.Tu, viTriDauChuoi, viTriCuoiChuoi);
                if (sumWidth > ActualWidth)
                {
                    //Vẽ hàng
                    x = 0;
                    for (int j = 0; j < _listFormattedText.Count; j++)
                    {
                        Typeface typeface = new Typeface(("Arial"));
                        Point    origin   = new Point(x, maxBaseline + _height + lineSpacing);
                        GlyphRun run      = CreateGlyphRun(typeface, _listFormatText[j].textToFormat, _listFormatText[j].emSize, origin);
                        drawingContext.DrawGlyphRun(Brushes.Black, run);
                        _listText.Add(new ListText {
                            text = _listFormatText[j].textToFormat, size = _listFormatText[j].emSize, typeface = typeface, foreground = _listFormatText[j].foreground, x = x, y = maxBaseline + _height + lineSpacing, maxBaseline = maxBaseline
                        });
                        // drawingContext.DrawText(_listFormattedText[j], new Point(x, maxBaseline - _listFormattedText[j].Baseline+_height+lineSpacing));
                        x += _listFormattedText[j].WidthIncludingTrailingWhitespace;
                    }
                    //Gan lai height,max base
                    _height    += maxBaseline;
                    maxBaseline = 0;
                    _listFormattedText.Clear();
                    _listFormatText.Clear();

                    /*
                     *
                     * if (widthXau(item.Tu, listFont[positionFontTu]) > ActualWidth)
                     * {
                     *  sumWidth = 0;
                     *  int vitri = 0;
                     *  for (int i = 0; i < item.Tu.Length; i++)
                     *  {
                     *      var charKiTu = new FormattedText(item.Tu[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
                     *                                           new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                     *      sumWidth += charKiTu.WidthIncludingTrailingWhitespace;
                     *      if (sumWidth > ActualWidth)
                     *      {
                     *          var tu = new FormattedText(item.Tu.Substring(vitri,i-vitri), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                     *          vitri = i;
                     *          maxBaseline = tu.Baseline;
                     *          drawingContext.DrawText(tu, new Point(0, maxBaseline - tu.Baseline + _height+lineSpacing));
                     *          _height += maxBaseline;
                     *          sumWidth = charKiTu.WidthIncludingTrailingWhitespace;
                     *      }
                     *
                     *  }
                     *  if (vitri < item.Tu.Length)
                     *  {
                     *      var kt = new FormattedText(item.Tu.Substring(vitri, item.Tu.Length - vitri), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                     *
                     *      var KT = new FormattedText(item.KhoangTrang, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontKT]._fontSize, Brushes.Black);
                     *      if (kt.Baseline > maxBaseline) maxBaseline = kt.Baseline;
                     *      _listFormattedText.Add(kt);
                     *      _listFormattedText.Add(KT);
                     *      sumWidth = KT.WidthIncludingTrailingWhitespace + kt.WidthIncludingTrailingWhitespace;
                     *  }
                     * }*/
                    if (widthXau(listFont, item.Tu, viTriDauChuoi, viTriCuoiChuoi) > ActualWidth)
                    {
                        maxBaseline = 0;
                        sumWidth    = 0;
                        int vitri = 0;
                        for (int i = 0; i < item.Tu.Length; i++)
                        {
                            /* var charKiTu = new FormattedText(item.Tu[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
                             *                                    new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);*/
                            var charKiTu = new FormattedText(item.Tu[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriDauChuoi + i)]._fontSize, Brushes.Black);

                            var charKiTu2 = new FormatText(item.Tu[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriDauChuoi + i)]._fontSize, Brushes.Black);


                            if (charKiTu.Baseline > maxBaseline)
                            {
                                maxBaseline = charKiTu.Baseline;
                            }
                            sumWidth += charKiTu.WidthIncludingTrailingWhitespace;
                            if (sumWidth > ActualWidth)
                            {
                                /*var tu = new FormattedText(item.Tu.Substring(vitri, i - vitri), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                                 * vitri = i;
                                 * maxBaseline = tu.Baseline;
                                 * drawingContext.DrawText(tu, new Point(0, maxBaseline - tu.Baseline + _height + lineSpacing));
                                 * _height += maxBaseline;
                                 * sumWidth = charKiTu.WidthIncludingTrailingWhitespace;*/
                                x = 0;
                                for (int j = 0; j < _listFormattedText.Count; j++)
                                {
                                    Typeface typeface = new Typeface(("Arial"));
                                    Point    origin   = new Point(x, maxBaseline + _height + lineSpacing);
                                    GlyphRun run      = CreateGlyphRun(typeface, _listFormatText[j].textToFormat, _listFormatText[j].emSize, origin);
                                    drawingContext.DrawGlyphRun(Brushes.Black, run);
                                    //drawingContext.DrawText(_listFormattedText[j], new Point(x, maxBaseline - _listFormattedText[j].Baseline + _height + lineSpacing));
                                    _listText.Add(new ListText {
                                        text = _listFormatText[j].textToFormat, size = _listFormatText[j].emSize, typeface = typeface, foreground = _listFormatText[j].foreground, x = x, y = maxBaseline + _height + lineSpacing, maxBaseline = maxBaseline
                                    });
                                    x += _listFormattedText[j].WidthIncludingTrailingWhitespace;
                                }
                                //Gan lai height,max base
                                _height    += maxBaseline;
                                maxBaseline = charKiTu.Baseline;
                                _listFormattedText.Clear();
                                _listFormatText.Clear();
                                sumWidth = charKiTu.WidthIncludingTrailingWhitespace;
                                _listFormattedText.Add(charKiTu);
                                _listFormatText.Add(charKiTu2);
                                vitri = i;
                            }
                            else
                            {
                                // if (charKiTu.Baseline > maxBaseline) maxBaseline = charKiTu.Baseline;
                                _listFormattedText.Add(charKiTu);
                                _listFormatText.Add(charKiTu2);
                            }
                        }
                        if (vitri < item.Tu.Length)
                        {
                            /* var kt = new FormattedText(item.Tu.Substring(vitri, item.Tu.Length - vitri), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                             *
                             * var KT = new FormattedText(item.KhoangTrang, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontKT]._fontSize, Brushes.Black);
                             * if (kt.Baseline > maxBaseline) maxBaseline = kt.Baseline;
                             * _listFormattedText.Add(kt);
                             * _listFormattedText.Add(KT);
                             * sumWidth = KT.WidthIncludingTrailingWhitespace + kt.WidthIncludingTrailingWhitespace;*/
                            /* for (int i = 0; i < item.Tu.Length; i++)
                             * {
                             *
                             *   var charKiTu = new FormattedText(item.Tu[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriDauChuoi + i)]._fontSize, Brushes.Black);
                             *   if (charKiTu.Baseline > maxBaseline) maxBaseline = charKiTu.Baseline;
                             *   sumWidth += charKiTu.WidthIncludingTrailingWhitespace;
                             * //   _listFormattedText.Add(charKiTu);
                             * }*/
                            for (int i = 0; i < item.KhoangTrang.Length; i++)
                            {
                                var charKT  = new FormattedText(item.KhoangTrang[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriDauKT + i)]._fontSize, Brushes.Black);
                                var charKT2 = new FormatText(item.KhoangTrang[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriDauKT + i)]._fontSize, Brushes.Black);
                                // if (charKT.Baseline > maxBaseline) maxBaseline = charKT.Baseline;
                                sumWidth += charKT.WidthIncludingTrailingWhitespace;
                                _listFormattedText.Add(charKT);
                                _listFormatText.Add(charKT2);
                            }
                        }
                    }
                    else
                    {
                        /* var tu = new FormattedText(item.Tu, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontTu]._fontSize, Brushes.Black);
                         * var KT = new FormattedText(item.KhoangTrang, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontKT]._fontSize, Brushes.Black);
                         * if (tu.Baseline > maxBaseline) maxBaseline = tu.Baseline;
                         * _listFormattedText.Add(tu);
                         * _listFormattedText.Add(KT);
                         * //  maxBaseline = tu.Baseline;
                         * sumWidth = KT.WidthIncludingTrailingWhitespace+tu.WidthIncludingTrailingWhitespace;*/
                        sumWidth = 0;
                        int toaDo = 0;
                        int i     = 0;
                        for (i = viTriDinhDang(listFont, viTriDauChuoi); i < viTriDinhDang(listFont, viTriCuoiChuoi); i++)
                        {
                            var xau   = new FormattedText(item.Tu.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauChuoi - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                            var xau21 = new FormatText(item.Tu.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauChuoi - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                            toaDo = listFont[i].viTriKetThuc - viTriDauChuoi + 1;
                            if (xau.Baseline > maxBaseline)
                            {
                                maxBaseline = xau.Baseline;
                            }
                            sumWidth += xau.WidthIncludingTrailingWhitespace;
                            _listFormattedText.Add(xau);
                            _listFormatText.Add(xau21);
                        }
                        if (item.Tu.Length > 0)
                        {
                            var xau2  = new FormattedText(item.Tu.Substring(toaDo, viTriCuoiChuoi - toaDo - viTriDauChuoi + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiChuoi)]._fontSize, Brushes.Black);
                            var xau22 = new FormatText(item.Tu.Substring(toaDo, viTriCuoiChuoi - toaDo - viTriDauChuoi + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiChuoi)]._fontSize, Brushes.Black);
                            if (xau2.Baseline > maxBaseline)
                            {
                                maxBaseline = xau2.Baseline;
                            }
                            sumWidth += xau2.WidthIncludingTrailingWhitespace;
                            _listFormattedText.Add(xau2);
                            _listFormatText.Add(xau22);
                        }

                        //dinh dang va add vao list cac kt
                        toaDo = 0;
                        i     = 0;
                        if (!string.IsNullOrEmpty(item.KhoangTrang))
                        {
                            for (i = viTriDinhDang(listFont, viTriDauKT); i < viTriDinhDang(listFont, viTriCuoiKT); i++)
                            {
                                string t    = item.KhoangTrang;
                                var    kt   = new FormattedText(item.KhoangTrang.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauKT - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                                var    kt21 = new FormatText(item.KhoangTrang.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauKT - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                                toaDo = listFont[i].viTriKetThuc - viTriDauKT + 1;
                                _listFormattedText.Add(kt);
                                _listFormatText.Add(kt21);
                                sumWidth += kt.WidthIncludingTrailingWhitespace;
                            }
                            if (item.KhoangTrang.Length > 0)
                            {
                                var kt2  = new FormattedText(item.KhoangTrang.Substring(toaDo, viTriCuoiKT - toaDo - viTriDauKT + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiKT)]._fontSize, Brushes.Black);
                                var kt22 = new FormatText(item.KhoangTrang.Substring(toaDo, viTriCuoiKT - toaDo - viTriDauKT + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiKT)]._fontSize, Brushes.Black);
                                _listFormattedText.Add(kt2);
                                _listFormatText.Add(kt22);
                                sumWidth += kt2.WidthIncludingTrailingWhitespace;
                            }
                        }
                    }
                }
                else
                {/*
                  * var tu = new FormattedText(item.Tu, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"),listFont[positionFontTu]._fontSize, Brushes.Black);
                  * var KT = new FormattedText(item.KhoangTrang, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[positionFontKT]._fontSize, Brushes.Black);
                  * if (tu.Baseline > maxBaseline) maxBaseline = tu.Baseline;
                  * _listFormattedText.Add(tu);
                  * _listFormattedText.Add(KT);
                  * sumWidth += KT.WidthIncludingTrailingWhitespace;
                  */
                 //dinh dang va add vao list cac tu

                    int toaDo = 0;
                    int i     = 0;
                    i = viTriDinhDang(listFont, viTriDauChuoi);
                    i = viTriCuoiChuoi;
                    for (i = viTriDinhDang(listFont, viTriDauChuoi); i < viTriDinhDang(listFont, viTriCuoiChuoi); i++)
                    {
                        var xau   = new FormattedText(item.Tu.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauChuoi - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                        var xau21 = new FormatText(item.Tu.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauChuoi - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                        toaDo = listFont[i].viTriKetThuc - viTriDauChuoi + 1;
                        if (xau.Baseline > maxBaseline)
                        {
                            maxBaseline = xau.Baseline;
                        }
                        _listFormattedText.Add(xau);
                        _listFormatText.Add(xau21);
                    }
                    if (item.Tu.Length > 0)
                    {
                        var xau2  = new FormattedText(item.Tu.Substring(toaDo, viTriCuoiChuoi - toaDo - viTriDauChuoi + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiChuoi)]._fontSize, Brushes.Black);
                        var xau22 = new FormatText(item.Tu.Substring(toaDo, viTriCuoiChuoi - toaDo - viTriDauChuoi + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiChuoi)]._fontSize, Brushes.Black);
                        if (xau2.Baseline > maxBaseline)
                        {
                            maxBaseline = xau2.Baseline;
                        }
                        _listFormattedText.Add(xau2);
                        _listFormatText.Add(xau22);
                    }

                    //dinh dang va add vao list cac kt
                    toaDo = 0;
                    i     = 0;
                    if (!string.IsNullOrEmpty(item.KhoangTrang))
                    {
                        for (i = viTriDinhDang(listFont, viTriDauKT); i < viTriDinhDang(listFont, viTriCuoiKT); i++)
                        {
                            string t    = item.KhoangTrang;
                            var    kt   = new FormattedText(item.KhoangTrang.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauKT - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                            var    kt21 = new FormatText(item.KhoangTrang.Substring(toaDo, listFont[i].viTriKetThuc - viTriDauKT - toaDo + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[i]._fontSize, Brushes.Black);
                            toaDo = listFont[i].viTriKetThuc - viTriDauKT + 1;
                            _listFormattedText.Add(kt);
                            _listFormatText.Add(kt21);
                            sumWidth += kt.WidthIncludingTrailingWhitespace;
                        }
                        if (item.KhoangTrang.Length > 0)
                        {
                            var kt2  = new FormattedText(item.KhoangTrang.Substring(toaDo, viTriCuoiKT - toaDo - viTriDauKT + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiKT)]._fontSize, Brushes.Black);
                            var kt22 = new FormatText(item.KhoangTrang.Substring(toaDo, viTriCuoiKT - toaDo - viTriDauKT + 1), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), listFont[viTriDinhDang(listFont, viTriCuoiKT)]._fontSize, Brushes.Black);
                            _listFormattedText.Add(kt2);
                            _listFormatText.Add(kt22);
                            sumWidth += kt2.WidthIncludingTrailingWhitespace;
                        }
                    }
                }
            }
            x = 0;
            for (int j = 0; j < _listFormattedText.Count; j++)
            {
                Typeface typeface = new Typeface(("Arial"));

                Point    origin = new Point(x, maxBaseline + _height + lineSpacing);
                GlyphRun run    = CreateGlyphRun(typeface, _listFormatText[j].textToFormat, _listFormatText[j].emSize, origin);
                drawingContext.DrawGlyphRun(Brushes.Black, run);
                _listText.Add(new ListText {
                    text = _listFormatText[j].textToFormat, size = _listFormatText[j].emSize, typeface = typeface, foreground = _listFormatText[j].foreground, x = x, y = maxBaseline + _height + lineSpacing, maxBaseline = maxBaseline
                });
                //drawingContext.DrawText(_listFormattedText[j], new Point(x, maxBaseline - _listFormattedText[j].Baseline + _height + lineSpacing));
                x += _listFormattedText[j].WidthIncludingTrailingWhitespace;
            }
            _listFormattedText.Clear();
            _listFormatText.Clear();
            FormattedText _formattedText = new FormattedText(
                string.Format(xauHoanChinh, Environment.NewLine), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
                new Typeface("Arial"), 14, Brushes.Black);
            //   drawingContext.DrawText(_formattedText, new Point(0, 0));
            // List<ListText> a = _listText;


            //Xử lý bôi đen xâu.
            Point pTam1         = new Point(0, 0); //Xác định vị trí bắt đầu con trỏ bôi đen
            Point pTam2         = new Point(0, 0); //Xác định vị trí kết thúc con trỏ bôi đen
            int   _viTriBoiDen1 = 0;
            int   _viTriBoiDen2 = 0;

            //Xác định vị trí từ bôi đen bắt đầu
            for (int i = 0; i < _listText.Count; i++)
            {
                if (_listText[i].y - _listText[i].maxBaseline > p1.Y)
                {
                    break;
                }
                if (_listText[i].x <= p1.X)
                {
                    _viTriBoiDen1 = i;
                }
            }
            string a = _listText[_viTriBoiDen1].text;
            //Xác định vi trí con trỏ bắt đầu
            double vitriCheck1 = _listText[_viTriBoiDen1].x;

            for (int i = 0; i < _listText[_viTriBoiDen1].text.Length; i++)
            {
                var charKiTu = new FormattedText(_listText[_viTriBoiDen1].text[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), _listText[_viTriBoiDen1].size, Brushes.Black);
                if (p1.X < vitriCheck1 + charKiTu.WidthIncludingTrailingWhitespace / 2.0)
                {
                    pTam1.X = vitriCheck1;
                    pTam1.Y = _listText[_viTriBoiDen1].y;
                    break;
                }
                vitriCheck1 += charKiTu.WidthIncludingTrailingWhitespace;
                if (i == _listText[_viTriBoiDen1].text.Length - 1)
                {
                    pTam1.X = vitriCheck1;
                    pTam1.Y = _listText[_viTriBoiDen1].y;
                }
            }
            //Xác định vị trí từ bôi đen kết thúc
            for (int i = 0; i < _listText.Count; i++)
            {
                if (_listText[i].y - _listText[i].maxBaseline > p2.Y)
                {
                    break;
                }
                if (_listText[i].x <= p2.X)
                {
                    //pTam2.X = _listText[i].x;
                    // pTam2.Y = _listText[i].y - _listText[i].maxBaseline;
                    _viTriBoiDen2 = i;
                }
            }
            string b = _listText[_viTriBoiDen2].text;
            //Xác định vi trí con trỏ kết thúc
            double vitriCheck2 = _listText[_viTriBoiDen2].x;

            for (int i = 0; i < _listText[_viTriBoiDen2].text.Length; i++)
            {
                var charKiTu = new FormattedText(_listText[_viTriBoiDen2].text[i].ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), _listText[_viTriBoiDen2].size, Brushes.Black);
                if (p2.X < vitriCheck2 + charKiTu.WidthIncludingTrailingWhitespace / 2.0)
                {
                    pTam2.X = vitriCheck2;
                    pTam2.Y = _listText[_viTriBoiDen2].y;
                    break;
                }
                vitriCheck2 += charKiTu.WidthIncludingTrailingWhitespace;
                if (i == _listText[_viTriBoiDen2].text.Length - 1)
                {
                    pTam2.X = vitriCheck2;
                    pTam2.Y = _listText[_viTriBoiDen2].y;
                }
            }
            //Vẽ bôi đen
            if (_listText[_viTriBoiDen1].y == _listText[_viTriBoiDen2].y)
            {
                Rect  rect  = new Rect(pTam1.X, pTam1.Y - _listText[_viTriBoiDen1].maxBaseline, Math.Abs(pTam2.X - pTam1.X), _listText[_viTriBoiDen1].maxBaseline);
                Brush brush = new SolidColorBrush(Colors.Blue);
                drawingContext.DrawRectangle(brush, null, rect);
            }
            else
            {
                /*Rect rect = new Rect(pTam1.X, pTam1.Y-_listText[_viTriBoiDen1].maxBaseline, ActualWidth - pTam1.X, _listText[_viTriBoiDen1].maxBaseline);
                 * Brush brush = new SolidColorBrush(Colors.Blue);
                 * drawingContext.DrawRectangle(brush, null, rect);*/
                for (int i = _viTriBoiDen1; i < _viTriBoiDen2; i++)
                {
                    if (_listText[i + 1].y > _listText[i].y)
                    {
                        var charKiTu = new FormattedText(_listText[i].text.ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), _listText[i].size, Brushes.Black);
                        //Vẽ hàng
                        Rect  rect2  = new Rect(pTam1.X, pTam1.Y - _listText[_viTriBoiDen1].maxBaseline, _listText[i].x + charKiTu.WidthIncludingTrailingWhitespace - pTam1.X, _listText[i].maxBaseline);
                        Brush brush2 = new SolidColorBrush(Colors.Blue);
                        drawingContext.DrawRectangle(brush2, null, rect2);
                        break;
                    }
                }
                if (pTam1.Y < pTam2.Y - _listText[_viTriBoiDen2].maxBaseline)
                {
                    /*Rect rect2 = new Rect(0, pTam1.Y, ActualWidth, pTam2.Y - _listText[_viTriBoiDen2].maxBaseline - pTam1.Y);
                     * Brush brush2 = new SolidColorBrush(Colors.Blue);
                     * drawingContext.DrawRectangle(brush2, null, rect2);*/
                    for (int i = _viTriBoiDen1; i < _viTriBoiDen2; i++)
                    {
                        if (_listText[i].y > pTam1.Y)
                        {
                            if (_listText[i].y < pTam2.Y)
                            {
                                if (_listText[i + 1].y > _listText[i].y)
                                {
                                    var charKiTu = new FormattedText(_listText[i].text.ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), _listText[i].size, Brushes.Black);
                                    //Vẽ hàng
                                    Rect  rect2  = new Rect(0, _listText[i].y - _listText[i].maxBaseline, _listText[i].x + charKiTu.WidthIncludingTrailingWhitespace, _listText[i].maxBaseline);
                                    Brush brush2 = new SolidColorBrush(Colors.Blue);
                                    drawingContext.DrawRectangle(brush2, null, rect2);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                Rect  rect3  = new Rect(0, pTam2.Y - _listText[_viTriBoiDen2].maxBaseline, pTam2.X, _listText[_viTriBoiDen2].maxBaseline);
                Brush brush3 = new SolidColorBrush(Colors.Blue);
                drawingContext.DrawRectangle(brush3, null, rect3);
            }
            //Vẽ điểm kéo thả
            Brush brushc = new SolidColorBrush(Colors.Red);

            drawingContext.DrawEllipse(brushc, null, p1, 2, 2);
            drawingContext.DrawEllipse(brushc, null, p2, 2, 2);
            // Pen pen = new Pen(Brushes.Black, 1);
            //VẼ VĂN BẢN
            for (int i = 0; i < _listText.Count; i++)
            {
                Typeface typeface = new Typeface(("Arial"));
                Point    origin   = new Point(_listText[i].x, _listText[i].y);
                GlyphRun run      = CreateGlyphRun(typeface, _listText[i].text, _listText[i].size, origin);
                drawingContext.DrawGlyphRun(Brushes.Black, run);
            }
        }
Beispiel #28
0
        public virtual async Task <IActionResult> ApplyVendorSubmit(ApplyVendorModel model, bool captchaValid, IFormFile uploadedFile)
        {
            if (!_vendorSettings.AllowCustomersToApplyForVendorAccount)
            {
                return(RedirectToRoute("HomePage"));
            }

            if (!_workContext.CurrentCustomer.IsRegistered())
            {
                return(Challenge());
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            string pictureId   = string.Empty;
            string contentType = string.Empty;

            byte[] vendorPictureBinary = null;

            if (uploadedFile != null && !string.IsNullOrEmpty(uploadedFile.FileName))
            {
                try
                {
                    contentType = uploadedFile.ContentType;
                    if (string.IsNullOrEmpty(contentType))
                    {
                        ModelState.AddModelError("", "Empty content type");
                    }
                    else
                    if (!contentType.StartsWith("image"))
                    {
                        ModelState.AddModelError("", "Only image content type is allowed");
                    }

                    vendorPictureBinary = uploadedFile.GetPictureBits();
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Vendors.ApplyAccount.Picture.ErrorMessage"));
                }
            }

            if (ModelState.IsValid)
            {
                if (vendorPictureBinary != null && !string.IsNullOrEmpty(contentType))
                {
                    var picture = await _pictureService.InsertPicture(vendorPictureBinary, contentType, null);

                    if (picture != null)
                    {
                        pictureId = picture.Id;
                    }
                }

                var description = FormatText.ConvertText(model.Description);
                var address     = new Address();
                //disabled by default
                var vendor = new Vendor {
                    Name        = model.Name,
                    Email       = model.Email,
                    Description = description,
                    PageSize    = 6,
                    PictureId   = pictureId,
                    AllowCustomersToSelectPageSize = true,
                    PageSizeOptions      = _vendorSettings.DefaultVendorPageSizeOptions,
                    AllowCustomerReviews = _vendorSettings.DefaultAllowCustomerReview,
                };
                model.Address.ToEntity(vendor.Address, true);
                await _vendorService.InsertVendor(vendor);

                //search engine name (the same as vendor name)
                var seName = await vendor.ValidateSeName(vendor.Name, vendor.Name, true, HttpContext.RequestServices.GetRequiredService <SeoSettings>(),
                                                         HttpContext.RequestServices.GetRequiredService <IUrlRecordService>(), HttpContext.RequestServices.GetRequiredService <ILanguageService>());

                await _urlRecordService.SaveSlug(vendor, seName, "");

                //associate to the current customer
                //but a store owner will have to manually add this customer role to "Vendors" role
                //if he wants to grant access to admin area
                _workContext.CurrentCustomer.VendorId = vendor.Id;
                await _customerService.UpdateCustomerVendor(_workContext.CurrentCustomer);

                //notify store owner here (email)
                await _workflowMessageService.SendNewVendorAccountApplyStoreOwnerNotification(_workContext.CurrentCustomer,
                                                                                              vendor, _storeContext.CurrentStore, _localizationSettings.DefaultAdminLanguageId);

                model.DisableFormInput = true;
                model.Result           = _localizationService.GetResource("Vendors.ApplyAccount.Submitted");
                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            model.DisplayCaptcha        = _captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage;
            model.TermsOfServiceEnabled = _vendorSettings.TermsOfServiceEnabled;
            model.TermsOfServicePopup   = _commonSettings.PopupForTermsOfServiceLinks;

            var countries = await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id);

            model.Address = await _mediator.Send(new GetVendorAddress()
            {
                Language                      = _workContext.WorkingLanguage,
                Address                       = null,
                Model                         = model.Address,
                ExcludeProperties             = false,
                PrePopulateWithCustomerFields = true,
                Customer                      = _workContext.CurrentCustomer,
                LoadCountries                 = () => countries,
            });

            return(View(model));
        }
Beispiel #29
0
        public virtual async Task <IActionResult> Info(VendorInfoModel model, IFormFile uploadedFile)
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
            {
                return(Challenge());
            }

            if (_workContext.CurrentVendor == null || !_vendorSettings.AllowVendorsToEditInfo)
            {
                return(RedirectToRoute("CustomerInfo"));
            }

            string pictureId   = string.Empty;
            string contentType = string.Empty;

            byte[] vendorPictureBinary = null;

            if (uploadedFile != null && !string.IsNullOrEmpty(uploadedFile.FileName))
            {
                try
                {
                    contentType = uploadedFile.ContentType;
                    if (string.IsNullOrEmpty(contentType))
                    {
                        ModelState.AddModelError("", "Empty content type");
                    }
                    else
                    if (!contentType.StartsWith("image"))
                    {
                        ModelState.AddModelError("", "Only image content type is allowed");
                    }

                    vendorPictureBinary = uploadedFile.GetPictureBits();
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Account.VendorInfo.Picture.ErrorMessage"));
                }
            }

            var vendor      = _workContext.CurrentVendor;
            var prevPicture = await _pictureService.GetPictureById(vendor.PictureId);

            if (ModelState.IsValid && ModelState.ErrorCount == 0)
            {
                var description = FormatText.ConvertText(model.Description);

                vendor.Name        = model.Name;
                vendor.Email       = model.Email;
                vendor.Description = description;

                if (vendorPictureBinary != null && !string.IsNullOrEmpty(contentType))
                {
                    var picture = await _pictureService.InsertPicture(vendorPictureBinary, contentType, null);

                    if (picture != null)
                    {
                        vendor.PictureId = picture.Id;
                    }
                }
                if (prevPicture != null)
                {
                    await _pictureService.DeletePicture(prevPicture);
                }

                //update picture seo file name
                await UpdatePictureSeoNames(vendor);

                model.Address.ToEntity(vendor.Address, true);

                await _vendorService.UpdateVendor(vendor);

                //notifications
                if (_vendorSettings.NotifyStoreOwnerAboutVendorInformationChange)
                {
                    await _workflowMessageService.SendVendorInformationChangeNotification(vendor, _storeContext.CurrentStore, _localizationSettings.DefaultAdminLanguageId);
                }

                return(RedirectToAction("Info"));
            }
            var countries = await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id);

            model.Address = await _mediator.Send(new GetVendorAddress()
            {
                Language          = _workContext.WorkingLanguage,
                Model             = model.Address,
                Address           = vendor.Address,
                ExcludeProperties = false,
                LoadCountries     = () => countries,
            });

            return(View(model));
        }
        private async Task <StringBuilder> PrepareFormattedAttribute(Product product, IList <CustomAttribute> customAttributes, string langId,
                                                                     string serapator, bool htmlEncode, bool renderPrices,
                                                                     bool allowHyperlinks, bool showInAdmin)
        {
            var result     = new StringBuilder();
            var attributes = _productAttributeParser.ParseProductAttributeMappings(product, customAttributes);

            for (int i = 0; i < attributes.Count; i++)
            {
                var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);

                var attribute = attributes[i];
                var valuesStr = _productAttributeParser.ParseValues(customAttributes, attribute.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr           = valuesStr[j];
                    string formattedAttribute = string.Empty;
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = productAttribute.GetLocalized(a => a.Name, langId);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = productAttribute.GetLocalized(a => a.Name, langId);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        //attributes with values
                        if (product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault() != null)
                        {
                            var attributeValue = product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                            if (attributeValue != null)
                            {
                                formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), attributeValue.GetLocalized(a => a.Name, langId));

                                if (renderPrices)
                                {
                                    decimal attributeValuePriceAdjustment = await _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue);

                                    var prices = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);

                                    decimal priceAdjustmentBase = prices.productprice;
                                    decimal taxRate             = prices.taxRate;
                                    decimal priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                    if (priceAdjustmentBase > 0)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false);
                                        formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                    }
                                    else if (priceAdjustmentBase < decimal.Zero)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false);
                                        formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                    }
                                }

                                //display quantity
                                if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity &&
                                    attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                {
                                    //render only when more than 1
                                    if (attributeValue.Quantity > 1)
                                    {
                                        //TODO localize resource
                                        formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity);
                                    }
                                }
                            }
                            else
                            {
                                if (showInAdmin)
                                {
                                    formattedAttribute += string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), "");
                                }
                            }

                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(formattedAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(formattedAttribute);
                    }
                }
            }
            return(result);
        }