コード例 #1
0
        public ActionResult Create(Article article, int[] authorIds, int[] themeIds, string[] fileName, int[] typeId, int[] version)
        {
            if (ModelState.IsValid)
            {
                db.Article.AddObject(article);

                for(int i =0; i < fileName.Length;i++)
                {
                    FileArticle file = new FileArticle {type_id = typeId[i], name = fileName[i], version = version[i]};
                    var fileElement = Request.Files[i];
                    file.content_type = fileElement.ContentType;
                    file.article_id = article.id;
                    Stream stream = fileElement.InputStream;
                    byte[] fileData = new byte[stream.Length];
                    stream.Read(fileData, 0, (int)stream.Length);
                    file.data = fileData;
                    db.FileArticle.AddObject(file);
                    article.FileArticle.Add(file);
                }

                SetArticleAuthors(article.Author, authorIds);
                SetArticleThemes(article.Theme, themeIds);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(article);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: bstaykov/Telerik-DSA
        private static OrderedMultiDictionary<int, Article> GenerateArticles(int count)
        {
            var barcodes = new HashSet<string>();

            Console.Write("Generating barcodes...");
            while (barcodes.Count < count)
            {
                var barcode = RandomGenerator.GetRandomString(BarcodeLength);
                barcodes.Add(barcode);
                if (barcodes.Count % (count / 10) == 0)
                {
                    Console.Write('.');
                }
            }

            Console.Write("\n\nGenerating articles...");
            var articles = new OrderedMultiDictionary<int, Article>(true);
            foreach (var barcode in barcodes)
            {
                var vendor = RandomGenerator.GetRandomString(5);
                var title = RandomGenerator.GetRandomString(7);
                var price = RandomGenerator.GeneratRandomNumber(0, count);
                var article = new Article(barcode, vendor, title, price);
                articles.Add(price, article);
                if (articles.Count % (count / 10) == 0)
                {
                    Console.Write('.');
                }
            }

            Console.WriteLine();
            return articles;
        }
コード例 #3
0
ファイル: MiscellaneousTests.cs プロジェクト: svn2github/awb
        public void AutoTag()
        {
            #if DEBUG
            const string LongText =
            @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dictum ultrices augue. Fusce sem diam, vestibulum sit amet, vehicula id, congue a, nisl. Phasellus pulvinar posuere purus. Donec elementum justo mattis nulla. Sed a purus dictum lacus pharetra adipiscing. Nam non dui non ante viverra iaculis. Fusce euismod lacus id nulla vulputate gravida. Suspendisse lectus pede, tempus sed, tristique id, pharetra eget, urna. Integer mattis libero vel quam accumsan suscipit. Vivamus molestie dapibus est. Quisque quis metus eget nisl accumsan aliquet. Donec tempus pellentesque tellus. Aliquam lacinia gravida justo. Aliquam erat volutpat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris ultricies suscipit urna. Ut mollis tempor leo. Pellentesque fringilla mattis enim. Proin sapien enim, congue non, aliquet et, sollicitudin nec, mauris. Sed porta.

            Curabitur luctus mollis massa. Nullam consectetur mollis lacus. Suspendisse turpis. Fusce velit. Morbi egestas dui. Donec commodo ornare lorem. Vestibulum sodales. Curabitur egestas libero ut metus. Sed eget orci a ligula consectetur vestibulum. Cras sapien.

            Sed libero. Ut volutpat massa. Donec nulla pede, porttitor eu, sodales et, consectetur nec, quam. Pellentesque vestibulum hendrerit est. Nulla facilisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis et nibh eu lacus iaculis pretium. Fusce sed turpis. In cursus. Etiam interdum augue. Morbi commodo auctor ligula. In imperdiet, neque nec hendrerit consequat, lacus purus tristique turpis, eu hendrerit ipsum ligula at libero. Duis varius nunc vel tortor. Praesent tempor. Nunc non pede at velit congue feugiat. Curabitur gravida, nisl quis mattis porttitor, purus nulla viverra dui, non suscipit augue nunc ac libero. Donec lacinia est non augue.

            Nulla quam dui, tristique id, condimentum sed, sodales in, ante. Vestibulum vitae diam. Integer placerat ante non orci. Nulla gravida. Integer magna enim, iaculis ut, ornare dignissim, ultrices a, urna. Donec urna. Fusce fringilla, pede vitae pulvinar ullamcorper, est nisi eleifend ipsum, ac adipiscing odio massa vehicula neque. Sed blandit est. Morbi faucibus, nisl vel commodo vulputate, mi ipsum tincidunt sem, id ornare orci orci et velit. Morbi commodo sollicitudin ligula. Pellentesque vitae urna. Duis massa arcu, accumsan id, euismod eu, tincidunt et, odio. Phasellus purus leo, rhoncus sed, condimentum nec, vestibulum vel, lacus. In egestas, lectus vitae lacinia tristique, elit magna consequat risus, id sodales metus nulla ac pede. Suspendisse potenti.

            Fusce massa. Nullam lacinia purus nec ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse potenti. Proin augue. Donec mi magna, interdum a, elementum quis, bibendum sit amet, felis. Donec vel libero eget magna hendrerit ultrices. Suspendisse potenti. Sed scelerisque lacinia nisi. Quisque elementum, nunc nec luctus iaculis, ante quam aliquet orci, et ullamcorper dui ipsum at mi. Vestibulum a dolor id tortor posuere elementum. Sed mauris nisl, ultrices a, malesuada non, convallis ac, velit. Sed aliquam elit id metus. Donec malesuada, lorem ut pharetra auctor, mi risus viverra enim, vitae pulvinar urna metus at lorem. Vivamus id lorem. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla facilisi. Ut vel odio. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque lobortis sem.

            Proin in odio. Pellentesque [[habitant]] [[morbi]] [[tristique]] senectus et netus et malesuada fames ac turpis egestas. Vivamus bibendum arcu nec risus. Nulla iaculis ligula in purus. Etiam vulputate nibh sit amet lectus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse potenti. Suspendisse eleifend. Donec blandit nibh hendrerit turpis. Integer accumsan posuere odio. Ut commodo augue malesuada risus. Curabitur augue. Praesent volutpat nunc a diam. Nulla lobortis interdum dolor. Nunc imperdiet, ipsum ac tempor iaculis, nunc.
            ";
            Article a = new Article("A", "ABC");
            Parsers p = new Parsers(500, true);
            a.AutoTag(p, true, true);
            Assert.IsFalse(a.NoArticleTextChanged);

            a = new Article("A", LongText);
            Globals.UnitTestIntValue = 1;
            Globals.UnitTestBoolValue = false;
            a.AutoTag(p, true, true);
            Assert.IsTrue(a.NoArticleTextChanged);
            #endif
        }
コード例 #4
0
ファイル: Content.cs プロジェクト: irobinson/DnnSimpleArticle
        /// <summary>
        /// This should only run after the Article exists in the data store. 
        /// </summary>
        /// <returns>The newly created ContentItemID from the data store.</returns>
        public ContentItem CreateContentItem(Article objArticle, int tabId)
        {
            var typeController = new ContentTypeController();
            var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t);
            int contentTypeId;

            if (colContentTypes.Count() > 0)
            {
                var contentType = colContentTypes.Single();
                contentTypeId = contentType == null ? CreateContentType() : contentType.ContentTypeId;
            }
            else
            {
                contentTypeId = CreateContentType();
            }

            var objContent = new ContentItem
            {
                Content = objArticle.Title + " " + HttpUtility.HtmlDecode(objArticle.Description),
                ContentTypeId = contentTypeId,
                Indexed = false,
                ContentKey = "aid=" + objArticle.ArticleId,
                ModuleID = objArticle.ModuleId,
                TabID = tabId
            };

            objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent);

            // Add Terms
            var cntTerm = new Terms();
            cntTerm.ManageArticleTerms(objArticle, objContent);

            return objContent;
        }
コード例 #5
0
ファイル: DynamicId.cs プロジェクト: kpantos/ravendb
		public void AddEntity()
		{
            //Please use a normal running database and not the ones contained in the Base Class
			using (var store = new DocumentStore())
			{
				store.Conventions.FindIdentityPropertyNameFromEntityName = typeName => "ID";
				store.Conventions.FindIdentityProperty = prop => prop.Name == "ID";

				IDocumentSession session = store.OpenSession();

				var article = new Article
				{
					Title = "Article 1",
					SubTitle = "Article 1 subtitle",
					PublishDate = DateTime.UtcNow.Add(TimeSpan.FromDays(1))
				};
				session.Store(article);
				session.SaveChanges();

				Assert.True(article.ID > 0);

				var insertedArticle = session.Query<Article>().Where(
					a => a.ID.In(new int[] {article.ID}) && a.PublishDate > DateTime.UtcNow).FirstOrDefault();

				Assert.NotNull(insertedArticle);
			}
		}
コード例 #6
0
        public static async Task<Article> CreateNewAsync(Article article = null)
        {
            Console.WriteLine("Creating new article");
            var now = DateTime.Now;
            dynamic obj = article ?? new Article("object");
            if (article == null)
            {
                obj.intfield = 1;
                obj.decimalfield = 10.0m;
                obj.datefield = "2012-12-20";
                obj.datetimefield = now.ToString("o");
                obj.stringfield = "string value";
                obj.textfield = "text value";
                obj.boolfield = false;
                obj.geofield = "11.5,12.5";
                obj.listfield = "a";
                obj.SetAttribute("attr1", "value1");
                obj.SetAttribute("attr2", "value2");
            }

            var service = ObjectFactory.Build<IArticleService>();
            CreateArticleResponse response = null;

            response = await service.CreateArticleAsync(new CreateArticleRequest()
            {
                Article = obj,
                Environment = Environment.Sandbox
            });
            ApiHelper.EnsureValidResponse(response);
            Assert.IsNotNull(response.Article);
            Console.WriteLine("Created article id {0}", response.Article.Id);
            return response.Article;
        }
コード例 #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (((DataView)odsDieuTriHo.Select()).Count <= DataPager1.PageSize)
            {
                DataPager1.Visible = false;
            }

            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["di"]))
            {
                var oArticle = new Article();
                var oArticleCategory = new ArticleCategory();
                var dv = oArticle.ArticleSelectOne(Request.QueryString["di"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                strTitle = Server.HtmlDecode(row["ArticleTitleEn"].ToString());
                strDescription = Server.HtmlDecode(row["DescriptionEn"].ToString());
                strMetaTitle = Server.HtmlDecode(row["MetaTittleEn"].ToString());
                strMetaDescription = Server.HtmlDecode(row["MetaDescriptionEn"].ToString());
            }
            else
            {
                strTitle = strMetaTitle = "Cough Treatment";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);
        }
    }
コード例 #8
0
ファイル: Content.aspx.cs プロジェクト: Botas1991/tomas
 protected void Button4_Click(object sender, EventArgs e)
 {
     Article a = new Article();
     a.Delete(TextBox6.Text);
     Button2_Click(sender, e);
     TextBox6.Text = "";
 }
コード例 #9
0
        static void Main(string[] args)
        {
            OrderedMultiDictionary<double, Article> articles = new OrderedMultiDictionary<double, Article>(true);

            //filling the dictionary takes a few seconds
            for (int i = 0; i <= 2000000; i++)
            {
                double price = i / 100.3;
                Article article = new Article(i * 971, Math.Round(price, 2), i.ToString(), i.ToString());
                
                articles.Add(price, article);
            }

            
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var articlesInRange = GetArticlesInPriceRange(articles, 1d, 300000d);
            stopwatch.Stop();

            //Uncomment to see found items title and price
            StringBuilder sb = new StringBuilder();
            //foreach (var node in articlesInRange)
            //{
            //    foreach (var item in node.Value)
            //    {
            //        sb.AppendFormat("{0}: {1}\n", item.Title, item.Price);

            //    }
            //}

            Console.WriteLine(sb.ToString());
            Console.WriteLine("Found count: {0}", articlesInRange.Count);
            Console.WriteLine("Items in range found in: {0}", stopwatch.Elapsed);
        }
コード例 #10
0
ファイル: ArticleTests.cs プロジェクト: greaterwinner/ra-brix
        public void VerifySavingParentParentObjectPreservesDeepestChildren()
        {
            SetUp();
            User user = new User();
            user.Username = "******";
            Role role = new Role();
            role.Name = "admin";
            user.Roles.Add(role);
            user.Save();

            user = User.SelectFirst();
            Assert.AreEqual(1, user.Roles.Count);
            Assert.AreEqual("admin", user.Roles[0].Name);

            Article a = new Article();
            a.Header = "sdfihsdf";
            a.Body = "sdfiojhsdf";
            a.Followers.Add(user);
            a.Author = user;
            a.Save();

            user = User.SelectFirst();
            Assert.AreEqual(1, user.Roles.Count);
            Assert.AreEqual("admin", user.Roles[0].Name);
        }
コード例 #11
0
ファイル: ArticleButton.cs プロジェクト: fhoner/Kasse
        public ArticleButton(Article art)
        {
            ArticleButtonDesign design = null;
            string designdef = DatabaseHandler.GetArticleButtonDesignXml(art);
            if (designdef == "")
                design = ArticleButtonDesign.GetDefaultDesign();
            else
            {                
                design = new ArticleButtonDesign();
                XmlReader reader = XmlReader.Create(new StringReader(designdef));
                design.ReadXml(reader);
            }


            this.BackColor = design.BackColor;
            this.ForeColor = design.ForeColor;
            this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.FlatAppearance.BorderSize = 0;
            this.FlatAppearance.BorderColor = Color.Black;
            this.Size = new Size(120, 30);

            this.Location = CalculateArticleLocation(art.Position);

            if (!art.IsEnabled)
            {
                this.Enabled = false;
                this.Font = new Font(this.Font, FontStyle.Strikeout);
                this.BackColor = Color.FromArgb(234, 234, 234);
            }
            if (!art.IsVisible) this.Visible = false;
            if (!art.DoPrint) this.Font = new Font(this.Font, FontStyle.Italic);

            this.Text = art.Name;
        }
コード例 #12
0
ファイル: NewsService.cs プロジェクト: dbeattie71/HDP-Mobil
        public async Task<List<Article>> GetArticlesAfterAsync (Article latestArticle, Priority priority)
        {
            List<Article> articles = new List<Article> ();
            Task<List<Article>> getArticlesTask;

            var timestamp = latestArticle.CreatedAt.ToUnixTimestamp ();

            switch (priority) {
            case Priority.Background:
                getArticlesTask = _apiService.Background.GetArticlesAfter (timestamp, ApiService.Device);
                break;
            case Priority.UserInitiated:
                getArticlesTask = _apiService.UserInitiated.GetArticlesAfter (timestamp, ApiService.Device);
                break;
            case Priority.Speculative:
                getArticlesTask = _apiService.Speculative.GetArticlesAfter (timestamp, ApiService.Device);
                break;
            default:
                getArticlesTask = _apiService.UserInitiated.GetArticlesAfter (timestamp, ApiService.Device);
                break;
            }

            if (CrossConnectivity.Current.IsConnected)
            {
                articles = await Policy
                    .Handle<WebException> ()
                    .WaitAndRetryAsync (2, retryAttempt => TimeSpan.FromSeconds (Math.Pow (2, retryAttempt)))
                    .ExecuteAsync(async () => await getArticlesTask);
            }

            return articles.Select(article => {
                article.ImageUrl = ApiService.ApiBaseAddress + article.ImageUrl;
                return article;
            }).ToList();
        }
コード例 #13
0
        public List<string> GetFilesByArticle(Article article)
        {
            var findNameBom = GetFileNameToFindBom(article);
            var findNameDoc = GetFileNameToFindDoc(article);

            var pathDataBom = Path.Combine(LocationDirectory, "BOM");
            var pathDataDoc = Path.Combine(LocationDirectory, "Doc");

            var dataFilesPatchBom = new List<string>();
            var taskBom = new Task(() =>
            {
                dataFilesPatchBom.AddRange(Directory.GetFiles(pathDataBom, "*.pdf", SearchOption.AllDirectories));
                dataFilesPatchBom.AddRange(Directory.GetFiles(pathDataBom, "*.tif*", SearchOption.AllDirectories));
            });

            taskBom.Start();

            var dataFilesPatchDoc = new List<string>();
            var taskDoc = new Task(() =>
            {
                dataFilesPatchDoc.AddRange(Directory.GetFiles(pathDataDoc, "*.pdf", SearchOption.AllDirectories));
                dataFilesPatchDoc.AddRange(Directory.GetFiles(pathDataDoc, "*.tif*", SearchOption.AllDirectories));
            });

            taskDoc.Start();

            Task.WaitAll(taskDoc, taskBom);

            var files = dataFilesPatchBom.Where(x => x.Replace(pathDataBom, string.Empty).Contains(findNameBom)).Union(dataFilesPatchDoc.Where(y => y.Replace(pathDataDoc, string.Empty).Contains(findNameDoc))).ToList();

            return files;
        }
コード例 #14
0
 public void GetListTest()
 {
     var obj = new Article("object");
     obj.SetList<int>("multifield", new[] { 1, 2, 3, 4, 5 });
     var list = obj.GetList<decimal>("multifield");
     Assert.IsTrue(list.Intersect(new decimal[] { 1, 2, 3, 4, 5 }).Count() == 5);
 }
コード例 #15
0
ファイル: DyanmicId.cs プロジェクト: 925coder/ravendb
        public void AddEntity()
        {
            //SetUp
            using (var store = NewDocumentStore())
            {
                store.Conventions.FindIdentityPropertyNameFromEntityName = (typeName) => "ID";
                store.Conventions.FindIdentityProperty = prop => prop.Name == "ID";

                using (IDocumentSession session = store.OpenSession())
                {

                    var article = new Article()
                    {
                        Title = "Article 1",
                        SubTitle = "Article 1 subtitle",
                        PublishDate = DateTime.UtcNow.Add(TimeSpan.FromDays(1))
                    };
                    session.Store(article);
                    session.SaveChanges();

                    Assert.True(article.ID > 0);

                    var insertedArticle = session.Query<Article>().Where(
                        a => a.ID.In(new int[] {article.ID}) && a.PublishDate > DateTime.UtcNow).FirstOrDefault();

                    Assert.NotNull(insertedArticle);
                }
            }
        }
コード例 #16
0
ファイル: Mappers.cs プロジェクト: AmiraSh/WebSite
 public static Article MapToArticle(CreateArticleViewModel articleVM)
 {
     Article article = new Article();
     article.Name = articleVM.Name;
     article.Text = articleVM.Text;
     return article;
 }
コード例 #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BLArticle bll = new BLArticle();
            art = bll.SelectOne(Request.QueryString["Id"]);
            if (art != null)
            {
                this.artName.InnerText = art.ArticleName;
                this.artDate.InnerText = art.AddDate.ToString("yyyy-MM-dd HH:mm:ss");

                string path = GetPath(art.ArticlePath);
                string artContent="出错了...";
                try
                {
                    artContent = System.Text.Encoding.Default.GetString(System.IO.File.ReadAllBytes(path));
                }
                catch { }

                //artContent = System.Text.Encoding.Default.GetString(System.IO.File.ReadAllBytes(art.ArticlePath));
                this.articleContent.InnerHtml = artContent;
                fileName=art.ArticleName+art.AddDate.ToString("yyyy-MM-dd.HH-mm-ss");

                listReview = new BLReview().SelectByArticleId(art.Id.ToString());
            }
        }
    }
コード例 #18
0
ファイル: Program.cs プロジェクト: dtopalov/IReporter
        public static void Main()
        {
            var db = new ApplicationDbContext();
            var repo = new DbRepository<Category>(db);
            var categoriesService = new CategoriesService(repo);

            var configuration = Configuration.Default.WithDefaultLoader();
            var browsingContext = BrowsingContext.New(configuration);

            for (int i = 1; i <= 10000; i++)
            {
                var url = $"http://vicove.com/vic-{i}";
                var document = browsingContext.OpenAsync(url).Result;
                var articleContent = document.QuerySelector("#content_box .post-content").TextContent.Trim();
                if (!string.IsNullOrWhiteSpace(articleContent))
                {
                    var categoryName = document.QuerySelector("#content_box .thecategory a").TextContent.Trim();
                    var category = categoriesService.EnsureCategory(categoryName);
                    var article = new Article { Category = category, Content = articleContent };
                    db.Articles.Add(article);
                    db.SaveChanges();
                    Console.WriteLine(i);
                }
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Billmate/Billmate.NET
        static void Main(string[] args)
        {
        	//Eid: 1111 Replace with your eid. You can find it in Billmate-Online
        	//Secret: 111111111111 Replace with your secret. You can find it in Billmate-Online
        	//SSL: false SSl should be enabled or not
        	//Debug: true View more detailed information about the server communication
        	//Invoiceid: 111 View more detailed information about the server communication
        	//Personal number: 556000-0753
        	
            Console.WriteLine("Start");
            Billmate bm = new Billmate(1111, "111111111111", false, true);
            Address adress = new Address("*****@*****.**", "0760123456", "0760123456", "Test.net", "test api", "streetname no", "zipcode", "city", 209);
            AdditionalInfo ai = new AdditionalInfo("");

            Article[] articles = new Article[3];
            articles[0] = new Article(1, "VGN-TXN27N/B", "Sony VAIO VGN-TXN27N/B 11.1 Notebook PC", 337499, 25, 0, 32);
            articles[1] = new Article(1, "flatrate_flatrate", "Frakt - Fixed", 6250, 25, 0, 40);
            articles[2] = new Article(1, "invoice_fee", "Faktureringsavgift", 3625, 25, 0, 48);
            object[] result = (object[])bm.ActivateReservation("111", "556000-0753", adress, adress, articles, ai);

            foreach (object row in result)
            {
                Console.WriteLine(row.ToString());
            }

            Console.ReadLine();
        }
コード例 #20
0
        private void PopulateBodyTransitions(Article a)
        {
            List<string> tokens = Tokenize(a.Body);
            List<string> history = new List<string>();

            for (int i = 0; i < tokens.Count; i++) {
                List<string> previous = new List<string>(history);
                Context ctx;

                while (previous.Count > 0) {
                    Dictionary<string, int> next;
                    int count = 0;

                    ctx = new Context(previous.ToArray());

                    _BodyModel.TryGetValue(ctx, out next);
                    if (next == null) next = new Dictionary<string, int>();

                    next.TryGetValue(tokens[i], out count);
                    if (next.Count == 0) _BodyModel[ctx] = next;

                    next[tokens[i]] = count + 1;

                    Console.WriteLine("Set transition for {0} -> {2} to weight {1}", ctx.ToString(), count + 1, tokens[i]);

                    previous.RemoveAt(0);
                }

                history.Add(tokens[i]);

                while (history.Count > MaxDegree) {
                    history.RemoveAt(0);
                }
            }
        }
コード例 #21
0
        private void PopulateRecordLabel(Article a)
        {
            int lblCount = 0;

            _Labels.TryGetValue(a.Label, out lblCount);
            _Labels[a.Label] = lblCount + 1;
        }
コード例 #22
0
 public ActionResult DoUpdate(Article article)
 {
     DataOperator dop = new DataOperator(Runtime.SqlConfig);
     article.ATime = DateTime.Now;
     dop.Update(article);
     return Redirect("/Admin/Success.do");
 }
コード例 #23
0
 public void Add(Article article)
 {
     ArticleBundle targetBundle = null;
     foreach (ArticleBundle bundle in articleBundleSet)
     {
         if (bundle.MainArticle.Blog != article.Blog && AreSame(bundle.MainArticle, article))
         {
             targetBundle = bundle;
             break;
         }
     }
     if (targetBundle != null)
     {
         articleBundleSet.Remove(targetBundle);
         targetBundle.Bundle(article);
         articleBundleSet.Add(targetBundle);
     }
     else
     {
         articleBundleSet.Add(new ArticleBundle(article));
         while (articleBundleSet.Count > maxNumArticleBundles)
         {
             articleBundleSet.Remove(articleBundleSet.Max);
         }
     }
 }
コード例 #24
0
        public override IEnumerable<Article> ParsePagingPage(string rawHtml)
        {
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(rawHtml);

            var articleNodes = htmlDoc.DocumentNode.SelectNodes("//tr[@height=28 and @bgcolor='white']");
            if (articleNodes == null)
            {
                yield break;
            }

            foreach (var articleNode in articleNodes)
            {
                var link = articleNode.SelectSingleNode("td[@class='bbsSubject']").SelectSingleNode("a").Attributes["href"].Value;
                const string token = "=&l=";
                var articleId = int.Parse(link.Substring(link.LastIndexOf(token) + token.Length));

                var article = new Article
                {
                    Game = (int)Games.tera,
                    TargetSite = (int)TargetSites.inven,
                    CategoryId = CategoryId,
                    ArticleId = articleId,
                    Link = link,
                    Author = articleNode.SelectSingleNode("td[@align='left']").InnerText.Trim(),
                };

                yield return article;
            }
        }
コード例 #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["tv"]))
            {
                var oTuVan = new Article();
                var dv = oTuVan.ArticleSelectOne(Request.QueryString["tv"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                strTitle = Server.HtmlDecode(row["ArticleTitle"].ToString());
                strDescription = Server.HtmlDecode(row["Description"].ToString());
                strMetaTitle = Server.HtmlDecode(row["MetaTittle"].ToString());
                strMetaDescription = Server.HtmlDecode(row["MetaDescription"].ToString());

                //hdnSanPham.Value = progressTitle(dv[0]["ProductCategoryName"].ToString()) + "-pci-" + dv[0]["ProductCategoryID"].ToString() + ".aspx";
            }
            else
            {
                strTitle = strMetaTitle = "Tư Vấn";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);

            lblTitle.Text = strTitle;
            lblTitle2.Text = strTitle;
        }
    }
コード例 #26
0
 public AbstractResponse GetResponse(ReplyInfo reply, string openId)
 {
     if (reply.MessageType == MessageType.Text)
     {
         TextReplyInfo info = reply as TextReplyInfo;
         TextResponse response = new TextResponse {
             CreateTime = DateTime.Now,
             Content = info.Text
         };
         if (reply.Keys == "登录")
         {
             string str = string.Format("http://{0}/Vshop/Login.aspx?SessionId={1}", HttpContext.Current.Request.Url.Host, openId);
             response.Content = response.Content.Replace("$login$", string.Format("<a href=\"{0}\">一键登录</a>", str));
         }
         return response;
     }
     NewsResponse response2 = new NewsResponse {
         CreateTime = DateTime.Now,
         Articles = new List<Article>()
     };
     foreach (NewsMsgInfo info2 in (reply as NewsReplyInfo).NewsMsg)
     {
         Article item = new Article {
             Description = info2.Description,
             PicUrl = string.Format("http://{0}{1}", HttpContext.Current.Request.Url.Host, info2.PicUrl),
             Title = info2.Title,
             Url = string.IsNullOrEmpty(info2.Url) ? string.Format("http://{0}/Vshop/ImageTextDetails.aspx?messageId={1}", HttpContext.Current.Request.Url.Host, info2.Id) : info2.Url
         };
         response2.Articles.Add(item);
     }
     return response2;
 }
コード例 #27
0
        public static Repository GetMockRepository(
            Article article = null,
            ArticleRevision articleRevision = null,
            ArticleRedirect articleRedirect = null)
        {
            var documentStore =
                new EmbeddableDocumentStore
                    {
                        Configuration =
                            {
                                RunInUnreliableYetFastModeThatIsNotSuitableForProduction
                                    = true,
                                DefaultStorageTypeName = "munin",
                                RunInMemory = true,
                            }
                    }.Initialize();

            DocumentStoreInitializer.InitDocumentStore(documentStore);

            var repository = new Repository(documentStore);

            if (article != null)
            {
                repository.SaveArticle(article, articleRevision);
            }

            if (articleRedirect != null)
            {
                string articleId = articleRedirect.RedirectToArticleSlug;
                repository.SaveArticleRedirects(articleId, articleRedirect);
            }

            return new Repository(documentStore);
        }
コード例 #28
0
 public ActionResult DoDelete(Article article)
 {
     article.ACategoryName = "recycle";
     DataOperator dop = new DataOperator(Runtime.SqlConfig);
     dop.Update(article);
     return Redirect("/Admin/Success.do");
 }
コード例 #29
0
 private static void addSentencesToArticle(string file, Article article)
 {
     Sentence current = new Sentence();
     string sentence = null;
     string[] words = file.Split('\n');
     for (int i = 0; i < words.Length; i++)
     {
         if (words[i] == "")
         {
             //now we are at the end of a sentence
             if (sentence != null)
             {
                 addWordsToSentence(sentence, current);
                 sentence = null;
                 article.addSentence(current); //add sentence to the article
                 current = new Sentence(); //empty the sentence;
             }
         }
         else
         {
             sentence += (words[i] + '\n'.ToString());
         }
     }
     if (sentence != null) //maybe the last sentence
     {
         addWordsToSentence(sentence, current);
         article.addSentence(current);
     }
 }
コード例 #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["tt"]))
            {
                var oArticle = new Article();
                var oArticleCategory = new ArticleCategory();
                var dv = oArticle.ArticleSelectOne(Request.QueryString["tt"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                var dv2 = oArticleCategory.ArticleCategorySelectOne(row["ArticleCategoryID"].ToString()).DefaultView;
                
                strTitle = Server.HtmlDecode(row["ArticleTitleEn"].ToString());
                strDescription = Server.HtmlDecode(row["DescriptionEn"].ToString());
                strMetaTitle = Server.HtmlDecode(row["MetaTittleEn"].ToString());
                strMetaDescription = Server.HtmlDecode(row["MetaDescriptionEn"].ToString());

                lblTitleNews.Text = dv2[0]["ArticleCategoryNameEn"].ToString();
            }
            else
            {
                strTitle = strMetaTitle = "News";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);
        }
    }
コード例 #31
0
 public static async Task <Article> getArticle(this Article a, int id)
 {
     return(await articlesRepo.GetAsync(id));
 }
コード例 #32
0
        public async Task IsBodyOnlyProperlyResolved()
        {
            Article result = await reader.ReadAsync(new Uri("http://calebjacob.com/tooltipster/"));

            Assert.True(result.Content.Substring(0, 4) == "<div");
        }
コード例 #33
0
        public async Task ReadArticleWithNoImagesTest()
        {
            Article result = await reader.ReadAsync(new Uri("http://getpocket.com/hits/awards/2013/"));

            Assert.True(result.Images == null || result.Images.Count() < 1);
        }
コード例 #34
0
        public static Article GetByPKID(SqlConnection connection, int PKID)
        {
            Article _Article   = null;
            var     parameters = new[]
            {
                new SqlParameter("@PKID", PKID)
            };
            var sqlcmd = @"SELECT TOP 1 
									PKID,
									Catalog,
									Image,
									SmallImage,
									SmallTitle,
									BigTitle,
									TitleColor,
									Brief,
									Content,
									ContentUrl,
									Source,
									PublishDateTime,
									RedirectUrl,
									Vote,
									Category,
									CommentIsActive,
                                    ArticleBanner,
                                    SmallBanner,
                                    Bestla,
                                    Type,
                                    IsShow,
                                    CategoryTags,
                                    ShowImages,
                                    ShowType,
                                    IsDescribe ,
                                    IsShowTouTiao
					FROM Marketing.dbo.tbl_Article WHERE PKID=@PKID"                    ;

            using (var _DR = SqlHelper.ExecuteReader(connection, CommandType.Text, sqlcmd, parameters))
            {
                if (_DR.Read())
                {
                    _Article                 = new Article();
                    _Article.PKID            = _DR.GetTuhuValue <int>(0);
                    _Article.Catalog         = _DR.GetTuhuValue <int>(1);
                    _Article.Image           = _DR.GetTuhuString(2);
                    _Article.SmallImage      = _DR.GetTuhuString(3);
                    _Article.SmallTitle      = _DR.GetTuhuString(4);
                    _Article.BigTitle        = _DR.GetTuhuString(5);
                    _Article.TitleColor      = _DR.GetTuhuString(6);
                    _Article.Brief           = _DR.GetTuhuString(7);
                    _Article.Content         = _DR.GetTuhuString(8);
                    _Article.ContentUrl      = _DR.GetTuhuString(9);
                    _Article.Source          = _DR.GetTuhuString(10);
                    _Article.PublishDateTime = _DR.GetTuhuValue <DateTime>(11);
                    _Article.RedirectUrl     = _DR.GetTuhuString(12);
                    _Article.Vote            = _DR.GetTuhuValue <int>(13);
                    _Article.Category        = _DR.GetTuhuString(14);
                    _Article.CommentIsActive = _DR.GetTuhuValue <bool>(15);
                    _Article.ArticleBanner   = _DR.GetTuhuString(16);
                    _Article.SmallBanner     = _DR.GetTuhuString(17);
                    _Article.Bestla          = _DR.GetTuhuValue <bool>(18);
                    _Article.Type            = _DR.GetTuhuValue <int>(19);
                    _Article.IsShow          = _DR.GetTuhuValue <int>(20);
                    _Article.CategoryTags    = _DR.GetTuhuString(21);
                    _Article.ShowImages      = _DR.GetTuhuString(22);
                    _Article.ShowType        = _DR.GetTuhuValue <int>(23);
                    _Article.IsDescribe      = _DR.GetTuhuValue <bool>(24);
                    _Article.IsShowTouTiao   = _DR.GetTuhuValue <bool>(25) ? 1 : 0;
                    _Article.IsFaxianChannel = _Article.Type == 99 ? 0 : 1;//type 为 99 代表不用于发现频道
                }
            }
            return(_Article);
        }
コード例 #35
0
        public static void Add(SqlConnection connection, Article article)
        {
            var sqlParamters = new[]
            {
                new SqlParameter("@Catalog", article.Catalog),
                new SqlParameter("@Image", article.Image ?? string.Empty),
                new SqlParameter("@SmallImage", article.SmallImage ?? string.Empty),
                new SqlParameter("@SmallTitle", article.SmallTitle ?? string.Empty),
                new SqlParameter("@BigTitle", article.BigTitle ?? string.Empty),
                new SqlParameter("@TitleColor", article.TitleColor ?? string.Empty),
                new SqlParameter("@Brief", article.Brief ?? string.Empty),
                new SqlParameter("@Content", article.Content ?? string.Empty),
                new SqlParameter("@ContentUrl", article.ContentUrl ?? string.Empty),
                new SqlParameter("@Source", article.Source ?? string.Empty),
                new SqlParameter("@PublishDateTime", article.PublishDateTime),
                new SqlParameter("@CreateDateTime", DateTime.Now),
                new SqlParameter("@LastUpdateDateTime", DateTime.Now),
                new SqlParameter("@RedirectUrl", article.RedirectUrl ?? string.Empty),
                new SqlParameter("@Vote", article.Vote),
                new SqlParameter("@Category", article.Category),
                new SqlParameter("@CommentIsActive", article.CommentIsActive),
                new SqlParameter("@ArticleBanner", article.ArticleBanner ?? string.Empty),
                new SqlParameter("@SmallBanner", article.SmallBanner ?? string.Empty),
                new SqlParameter("@ShowImages", article.ShowImages ?? string.Empty),
                new SqlParameter("@ShowType", article.ShowType),
                new SqlParameter("@IsDescribe", article.IsDescribe)
            };

            SqlHelper.ExecuteNonQuery(connection, CommandType.Text,
                                      @"INSERT  INTO Marketing.dbo.tbl_Article
                                ( Catalog ,
                                  Image ,
                                  SmallImage ,
                                  SmallTitle ,
                                  BigTitle ,
                                  TitleColor ,
                                  Brief ,
                                  Content ,
                                  ContentUrl ,
                                  Source ,
                                  PublishDateTime ,
                                  CreateDateTime ,
                                  LastUpdateDateTime ,
                                  RedirectUrl ,
                                  Vote ,
                                  Category ,
                                  CommentIsActive ,
                                  ArticleBanner ,
                                  SmallBanner,
                                  ShowImages,
                                  ShowType,
                                  IsDescribe
                                )
                        VALUES  ( @Catalog ,
                                  @Image ,
                                  @SmallImage ,
                                  @SmallTitle ,
                                  @BigTitle ,
                                  @TitleColor ,
                                  @Brief ,
                                  @Content ,
                                  @ContentUrl ,
                                  @Source ,
                                  @PublishDateTime ,
                                  @CreateDateTime ,
                                  @LastUpdateDateTime ,
                                  @RedirectUrl ,
                                  @Vote ,
                                  @Category ,
                                  @CommentIsActive ,
                                  @ArticleBanner ,
                                  @SmallBanner,
                                  @ShowImages,
                                  @ShowType,
                                  @IsDescribe
                                )"
                                      , sqlParamters);
        }
コード例 #36
0
        public static void Add(SqlConnection connection, Article article, out string contentUrl, out int id, string locationAddress)
        {
            const string sql = @"SET @ContentUrl = @LocationAddress + convert(varchar(200),NEWID())
            IF (@PKID = 0)
	            BEGIN
		            INSERT INTO Marketing.dbo.tbl_Article
		            (
			            [Catalog] ,
			            [Image] ,
			            SmallImage ,
			            SmallTitle ,
			            BigTitle ,
			            TitleColor ,
			            Brief ,
			            Content ,
			            ContentUrl ,
			            [Source] ,
			            PublishDateTime ,
			            CreateDateTime ,
			            LastUpdateDateTime ,
			            RedirectUrl ,
			            Vote ,
			            Category ,
			            CommentIsActive ,
			            ArticleBanner ,
			            SmallBanner,
			            Type,
			            IsShow,
			            CategoryTags,
			            ShowImages,
			            ShowType,
			            IsDescribe,
			            ContentHtml,
                        IsShowTouTiao
		            )
		            VALUES
		            (
			            @Catalog ,
			            @Image ,
			            @SmallImage ,
			            @SmallTitle ,
			            @BigTitle ,
			            @TitleColor ,
			            @Brief ,
			            @Content ,
			            @ContentUrl + '_' +CONVERT(VARCHAR(200),IDENT_CURRENT('Marketing.dbo.tbl_Article')) + '.html',
			            @Source ,
			            @PublishDateTime ,
			            @CreateDateTime ,
			            @LastUpdateDateTime ,
			            @RedirectUrl ,
			            @Vote ,
			            @Category ,
			            @CommentIsActive ,
			            @ArticleBanner ,
			            @SmallBanner,
			            @Type,
			            @IsShow,
			            @CategoryTags,
			            @ShowImages,
			            @ShowType,
			            @IsDescribe,
			            @ContentHtml ,
                        @IsShowTouTiao
		            )
		            SET @ReturnUrl = @ContentUrl + '_' +CONVERT(VARCHAR(200),IDENT_CURRENT('Marketing.dbo.tbl_Article')) + '.html'
		            SET @ReturnID = IDENT_CURRENT('Marketing.dbo.tbl_Article')
	            END
            ELSE
	            BEGIN
		            UPDATE  Marketing.dbo.tbl_Article
		            SET     [Catalog] = @Catalog ,
				            [Image] = @Image ,
				            SmallImage = @SmallImage ,
				            SmallTitle = @SmallTitle ,
				            BigTitle = @BigTitle ,
				            TitleColor = @TitleColor ,
				            Brief = @Brief ,
				            Content = @Content ,
				            ContentUrl = @ContentUrl + '_' + CONVERT(VARCHAR(2000),@PKID) + '.html' ,
				            [Source] = @Source ,
				            PublishDateTime = @PublishDateTime ,
				            LastUpdateDateTime = @LastUpdateDateTime ,
				            RedirectUrl = @RedirectUrl ,
				            Vote = @Vote ,
				            Category = @Category ,
				            CommentIsActive = @CommentIsActive ,
				            ArticleBanner = @ArticleBanner ,
				            SmallBanner = @SmallBanner,
				            Type=@Type,
				            IsShow=@IsShow,
				            CategoryTags=@CategoryTags,
				            ShowImages=@ShowImages,
				            ShowType=@ShowType,
				            IsDescribe=@IsDescribe,
				            ContentHtml=@ContentHtml ,
                            IsShowTouTiao=@IsShowTouTiao
		            WHERE   PKID = @PKID
		            SET @ReturnUrl = @ContentUrl + '_' + CONVERT(VARCHAR(2000),@PKID) + '.html'
		            SET @ReturnID = @PKID
	            END"    ;

            try
            {
                SqlParameter[] sqlParamters = new SqlParameter[]
                {
                    new SqlParameter("@PKID", SqlDbType.Int),
                    new SqlParameter("@Catalog", SqlDbType.Int),
                    new SqlParameter("@Image", SqlDbType.VarChar),
                    new SqlParameter("@SmallImage", SqlDbType.VarChar),
                    new SqlParameter("@SmallTitle", SqlDbType.NVarChar),
                    new SqlParameter("@BigTitle", SqlDbType.NVarChar),
                    new SqlParameter("@TitleColor", SqlDbType.Char),
                    new SqlParameter("@Brief", SqlDbType.NVarChar),
                    new SqlParameter("@Content", SqlDbType.NVarChar),
                    new SqlParameter("@ContentUrl", SqlDbType.VarChar),
                    new SqlParameter("@Source", SqlDbType.NVarChar),
                    new SqlParameter("@PublishDateTime", SqlDbType.SmallDateTime),
                    new SqlParameter("@CreateDateTime", SqlDbType.DateTime),
                    new SqlParameter("@LastUpdateDateTime", SqlDbType.DateTime),
                    new SqlParameter("@RedirectUrl", SqlDbType.NVarChar),
                    new SqlParameter("@Vote", SqlDbType.Int),
                    new SqlParameter("@Category", SqlDbType.NVarChar),
                    new SqlParameter("@CommentIsActive", SqlDbType.Bit),
                    new SqlParameter("@ArticleBanner", SqlDbType.VarChar),
                    new SqlParameter("@SmallBanner", SqlDbType.VarChar),
                    new SqlParameter("@ReturnUrl", SqlDbType.VarChar, 2000),
                    new SqlParameter("@ReturnID", SqlDbType.Int),
                    new SqlParameter("@LocationAddress", SqlDbType.VarChar),
                    new SqlParameter("@Type", SqlDbType.Int),
                    new SqlParameter("@IsShow", SqlDbType.Int),
                    new SqlParameter("@CategoryTags", SqlDbType.NVarChar),
                    new SqlParameter("@ShowImages", SqlDbType.NVarChar),
                    new SqlParameter("@ShowType", SqlDbType.Int),
                    new SqlParameter("@IsDescribe", SqlDbType.Bit),
                    new SqlParameter("@ContentHtml", SqlDbType.NVarChar),
                    new SqlParameter("@IsShowTouTiao", SqlDbType.Int)
                };
                sqlParamters[0].Value      = article.PKID;
                sqlParamters[1].Value      = article.Catalog;
                sqlParamters[2].Value      = article.Image ?? string.Empty;
                sqlParamters[3].Value      = article.SmallImage ?? string.Empty;
                sqlParamters[4].Value      = article.SmallTitle ?? string.Empty;
                sqlParamters[5].Value      = article.BigTitle ?? string.Empty;
                sqlParamters[6].Value      = article.TitleColor ?? string.Empty;
                sqlParamters[7].Value      = article.Brief ?? string.Empty;
                sqlParamters[8].Value      = article.Content ?? string.Empty;
                sqlParamters[9].Value      = article.ContentUrl ?? string.Empty;
                sqlParamters[10].Value     = article.Source ?? string.Empty;
                sqlParamters[11].Value     = article.PublishDateTime;
                sqlParamters[12].Value     = DateTime.Now;
                sqlParamters[13].Value     = DateTime.Now;
                sqlParamters[14].Value     = article.RedirectUrl ?? string.Empty;
                sqlParamters[15].Value     = article.Vote;
                sqlParamters[16].Value     = article.Category;
                sqlParamters[17].Value     = article.CommentIsActive;
                sqlParamters[18].Value     = article.ArticleBanner ?? string.Empty;
                sqlParamters[19].Value     = article.SmallBanner ?? string.Empty;
                sqlParamters[20].Direction = ParameterDirection.Output;
                sqlParamters[21].Direction = ParameterDirection.Output;
                sqlParamters[22].Value     = locationAddress ?? string.Empty;
                sqlParamters[23].Value     = article.Type;
                sqlParamters[24].Value     = article.IsShow;
                sqlParamters[25].Value     = article.CategoryTags;
                sqlParamters[26].Value     = article.ShowImages;
                sqlParamters[27].Value     = article.ShowType;
                sqlParamters[28].Value     = article.IsDescribe;
                sqlParamters[29].Value     = article.ContentHtml;
                sqlParamters[30].Value     = article.IsShowTouTiao;

                SqlHelper.ExecuteNonQuery(connection, CommandType.Text, sql, sqlParamters);
                contentUrl = sqlParamters[20].Value == DBNull.Value ? "" : (string)sqlParamters[20].Value;
                id         = sqlParamters[21].Value == DBNull.Value ? 0 : (int)sqlParamters[21].Value;
            }
            catch (Exception ex)
            {
                contentUrl = "";
                id         = 0;
            }
        }
コード例 #37
0
        public ActionResult Article(int id)
        {
            Article article = SqlFuDAL.FindArticleById(id);

            return(View(article));
        }
コード例 #38
0
 public IActionResult Add(Article a)
 {
     article.create(a);
     return(RedirectToAction("Index", "Articles"));
 }
コード例 #39
0
 public ArticleBodyPage(Article article)
 {
     InitializeComponent();
     TitleLabel.Text = article.Title;
     BodyLabel.Text  = article.Body;
 }
コード例 #40
0
        public void When_relationship_object_multiple_times_should_add_singe_included()
        {
            var person = new Person
            {
                Id        = "333",
                FirstName = "John",
                LastName  = "Smith",
                Twitter   = "jsmi"
            };
            var root = new Article
            {
                Id       = "1234",
                Title    = "My Article",
                Author   = person,
                Comments = new List <Comment>
                {
                    new Comment
                    {
                        Id     = "c1",
                        Author = person,
                        Body   = "comment 1"
                    },
                    new Comment
                    {
                        Id     = "c2",
                        Author = person,
                        Body   = "comment 2"
                    }
                }
            };


            var json         = JsonConvert.SerializeObject(root, settings);
            var expectedjson = @"{
                ""data"": {
                    ""id"": ""1234"",
                    ""type"": ""articles"",
                    ""attributes"": {
                        ""title"": ""My Article""
                    },
                    ""relationships"": {
                        ""author"": {
                            ""data"": { 
                                ""id"":""333"", 
                                ""type"":""people""
                            }
                        },
                        ""comments"": {
                            ""data"": [
                                { 
                                    ""id"":""c1"", 
                                    ""type"":""comments""
                                },
                                { 
                                    ""id"":""c2"", 
                                    ""type"":""comments""
                                }
                            ]
                        }
                    }
                },
                ""included"" : [
                    {
                        ""id"": ""333"",
                        ""type"": ""people"",
                        ""attributes"":{
                            ""first-name"": ""John"",
                            ""last-name"": ""Smith"",
                            ""twitter"": ""jsmi""
                        }
                    },
                    {
                        ""id"": ""c1"",
                        ""type"": ""comments"",
                        ""attributes"":{
                            ""body"": ""comment 1""
                        },
                        ""relationships"": {
                            ""author"": {
                                ""data"": { 
                                    ""id"":""333"", 
                                    ""type"":""people""
                                }
                            }
                        }
                    },
                    {
                        ""id"": ""c2"",
                        ""type"": ""comments"",
                        ""attributes"":{
                            ""body"": ""comment 2""
                        },
                        ""relationships"": {
                            ""author"": {
                                ""data"": { 
                                    ""id"":""333"", 
                                    ""type"":""people""
                                }
                            }
                        }
                    }
                ]
            }";

            Assert.Equal(expectedjson, json, JsonStringEqualityComparer.Instance);
        }
コード例 #41
0
 public void Add(Article value)
 {
     _article.Add(value);
 }
コード例 #42
0
        public decimal?CalculateDefaultAccountingPriceByRule(AccountingPriceList accountingPriceList, Article article, out bool accPriceCalc, out bool lastDigitError, User user)
        {
            var rule = accountingPriceCalcRuleService.GetReadyAccountingPriceCalcRule(accountingPriceList.AccountingPriceCalcRule, article.Id, user);

            var digitRule = accountingPriceCalcRuleService.GetReadyLastDigitCalcRule(accountingPriceList.LastDigitCalcRule, article.Id, user);

            var calculatedAccountingPrice = accountingPriceCalcService.CalculateAccountingPrice(rule, digitRule, article, out accPriceCalc, out lastDigitError);

            return(calculatedAccountingPrice);
        }
コード例 #43
0
        public void Test_CreateUpdateDeleteArticle()
        {
            IUserBasic         userBasic          = Test_WorkmateMembershipProvider.CreateUser(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, this.DummyDataManager);
            MessageBoard       messageBoard       = Test_MessageBoards.Create(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, this.Random);
            ArticleGroup       articleGroup       = Test_ArticleGroups.Create(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, this.Random);
            ArticleGroupThread articleGroupThread = Test_ArticleGroupThreads.Create(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, articleGroup, this.Random);

            ArticleManager manager = new ArticleManager(this.DataStore);
            Article        record  = Create(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, userBasic
                                            , articleGroupThread, messageBoard, this.Random);

            MessageBoardThreadManager messageBoardThreadManager = new MessageBoardThreadManager(this.DataStore);

            Article recordToCompare;

            for (int i = 0; i < this.DefaultUpdateTestIterations; i++)
            {
                PopulateWithRandomValues(record, this.DummyDataManager, this.Random);
                recordToCompare = record;

                manager.Update(record);
                record = manager.GetArticle(record.ArticleId);

                string errors = string.Empty;
                // TODO (Roman): relax datetime comparisons
                Assert.IsTrue(DebugUtility.ArePropertyValuesEqual(record, recordToCompare, out errors), errors);
                Trace.WriteLine("Update test successfull.");
            }

            IArticleModel articleModel = manager.GetArticleModel(record.ArticleId);

            Assert.AreEqual(0, articleModel.TotalComments);

            #region messageboards
            MessageBoardThread messageBoardThread = messageBoardThreadManager.GetMessageBoardThread(articleModel.MessageBoardThreadId);
            Assert.IsNotNull(messageBoardThread);

            MessageManager messageManager = new MessageManager(this.DataStore);

            messageManager.Create(new Message(userBasic, messageBoardThread, "Test Message Subject 1", "Body1"));
            messageManager.Create(new Message(userBasic, messageBoardThread, "Test Message Subject 2", "Body2"));

            Message message = new Message(userBasic, messageBoardThread, "Test Message Subject 3", "Body3");
            messageManager.Create(message);

            articleModel = manager.GetArticleModel(record.ArticleId);
            Assert.AreEqual(3, articleModel.TotalComments);

            Assert.AreEqual(DataRepositoryActionStatus.Success, messageManager.Delete(message).Status);
            articleModel = manager.GetArticleModel(record.ArticleId);
            Assert.AreEqual(2, articleModel.TotalComments);
            #endregion

            #region attachments
            IArticleAttachmentModel articleAttachmentModel = AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);
            AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);

            DeleteAttachment(this.DataStore, articleModel, articleAttachmentModel.AttachmentId, this.Random);

            AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);
            AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);

            articleAttachmentModel = AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);
            DeleteAttachment(this.DataStore, articleModel, articleAttachmentModel.AttachmentId, this.Random);

            AddAttachment(this.DataStore, this.Application.ApplicationId, articleModel, userBasic, this.Random);
            #endregion

            #region contentnodelevels
            if (articleModel.ContentLevelNodeId.HasValue)
            {
                string newName = "Some Name" + this.Random.Next(10000, 100000);
                CMSContentLevelNodeManager contentLevelNodeManager = new CMSContentLevelNodeManager(this.DataStore);
                contentLevelNodeManager.RenameContentLevelNode(articleModel.ContentLevelNodeId.Value, newName);

                articleModel = manager.GetArticleModel(record.ArticleId);
                Assert.AreEqual(articleModel.ContentLevelNodes[articleModel.ContentLevelNodes.Count - 1], newName);
            }
            #endregion

            Delete(this.DataStore, record);
            Test_ArticleGroups.Delete(this.DataStore, articleGroup);

            Assert.IsNull(messageBoardThreadManager.GetMessageBoardThread(articleModel.MessageBoardThreadId));

            ArticleAttachmentManager articleAttachmentManager = new ArticleAttachmentManager(this.DataStore);
            Assert.IsEmpty(articleAttachmentManager.GetArticleAttachments(articleModel.ArticleId));
        }
コード例 #44
0
ファイル: ArticleController.cs プロジェクト: polopalay/VNPost
 public IActionResult Upsert([FromQuery] int id)
 {
     Article = _unitOfWork.Article.Get(id);
     return(View(Article ?? new Article()));
 }
コード例 #45
0
 public static IEnumerable <ArticleViewModel> GetArticlesViewModels(Article article)
 {
     articlesViewModels.Clear();
     ListFiller(article);
     return(articlesViewModels);
 }
コード例 #46
0
 public void Save(Article editPublish)
 {
     _latestId++;
     editPublish.Id = _latestId;
     _article.Add(editPublish);
 }
コード例 #47
0
 // POST: api/Article
 public int Create([FromBody] Article form)
 {
     return(_articleRepo.Insert(form));
 }
コード例 #48
0
ファイル: HomeController.cs プロジェクト: yonghu86/siyouku
        public ActionResult CrawlerToDb()
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();

            var taglist = Db.Tag.ToList();
            var result  = new BaijiaArticel();
            var icount  = 0;

            for (int j = 0; j < 20; j++)
            {
                string url =
                    $"http://baijia.baidu.com/ajax/labellatestarticle?page={j}&pagesize=20&prevarticalid=765376&flagtogether=1&labelid=3";

                var str = url.GetPostPage(null);
                if (str != null)
                {
                    result = str.JsonConvert <BaijiaArticel>();
                }
                if (result.errno.Equals(0))
                {
                    result.data.list.ForEach(i =>
                    {
                        if (!Db.Articles.Any(x => x.CollectId == i.ID))
                        {
                            var listTag = new List <Tag>();
                            i.m_label_names.ForEach(w => {
                                var tag = taglist.FirstOrDefault <Tag>(t => t.CatName == w.m_name);
                                if (tag == null)
                                {
                                    listTag.Add(new Tag()
                                    {
                                        CatName = w.m_name, CreateTime = DateTime.Now, UpdateTime = DateTime.Now
                                    });
                                }
                                else
                                {
                                    listTag.Add(tag);
                                }
                            });
                            var x = new Article()
                            {
                                Img         = DownLoadImg(i.m_image_url),
                                Title       = i.m_title,
                                CategoryId  = "百度百家",
                                Summary     = i.m_summary,
                                Content     = GetContent(i.m_display_url),
                                CollectTime = i.m_create_time,
                                CollectUser = i.m_writer_name,
                                //Pviews = i.hotcount,
                                CollectId   = i.ID,
                                UserId      = "1",
                                PublishTime = DateTime.Now,
                                Tags        = listTag
                            };
                            if (!string.IsNullOrEmpty(x.Content) && !string.IsNullOrEmpty(x.Img))
                            {
                                Db.Articles.Add(x);
                                icount++;
                            }
                        }
                    });
                    Db.SaveChanges();
                }
            }

            watch.Stop();

            var lts = watch.ElapsedMilliseconds;

            return(Json(new { result = "ok", TimeSpan = lts, count = icount }));
        }
コード例 #49
0
        public ActionResult ArticleEdit(int id, FormCollection collection) //id为ArticleID
        {
            //判断这篇文章是否是已经提交过一次编辑,这个已经在get函数重定向了,这儿不用考虑了

            //判断字段是否符合标准
            //第一部分:文章
            TempArticle temparticle = new TempArticle();

            //判断文章类型
            temparticle.ArticleID    = id;
            temparticle.TypeID       = Article.GetTypeIDByArticleID(id);//注意,这儿是调用Article的函数,不是TempArticle
            temparticle.Title        = Request["Title"].Trim();
            temparticle.Introduction = Request["Introduction"].Trim();
            temparticle.EditTime     = DateTime.Now;//提交时间不再改变

            HttpCookie cookie = Request.Cookies["Employer"];

            if (cookie != null)
            {
                string EmployerAccount = cookie.Values["EmployerAccount"];
                temparticle.EditorAccount = EmployerAccount;//获取单位的Account
            }
            temparticle.ContactInfo        = Request["ContactInfo"].Trim();
            temparticle.FileAddr           = ""; //下面上传文件时会赋值
            temparticle.IsAudit            = 1;  //待定
            temparticle.ArticleDescription = Request["ArticleDescription"].Trim();

            int bigarticle = -1;//初始值

            //判断文章类型
            if (temparticle.TypeID == 1)
            {
                temparticle.PlaceFirstID = Convert.ToInt32(Request["PlaceFirstID"]);
                temparticle.RecruitTime  = Convert.ToDateTime(Request["RecruitTime"]);
            }
            else if (temparticle.TypeID == 2)
            {
                if (Request["bigarticle2"] == null || Request["bigarticle2"] == "")
                {
                    return(Json(new { message = "必须选择一个要加入的双选会" }));//退出
                }
                bigarticle = Convert.ToInt32(Request["bigarticle2"]);
            }
            else if (temparticle.TypeID == 3)
            {
                if (Request["bigarticle3"] == null || Request["bigarticle3"] == "")
                {
                    return(Json(new { message = "必须选择一个要加入的组团招聘" }));//退出
                }
                bigarticle = Convert.ToInt32(Request["bigarticle3"]);
            }
            temparticle.BigArticleID = bigarticle;//默认-1是未选择大型招聘会文章的

            //第二部分:需求
            string[] PositionName     = Request.Form.GetValues("PositionName");
            string[] EducationalLevel = Request.Form.GetValues("EducationalLevel");
            string[] Major            = Request.Form.GetValues("Major");
            string[] DemandNum        = Request.Form.GetValues("DemandNum");
            string[] PositionDec      = Request.Form.GetValues("PositionDec");

            List <TempDemandInfo> tempdemandInfo = new List <TempDemandInfo>();

            //判断有几个需求
            for (int i = 0; i < PositionName.Count(); ++i)
            {
                TempDemandInfo temp = new TempDemandInfo();
                //temp.TempArticleID = 1;//得到刚上传的文章ID,在下面的插入后会有赋值
                temp.PositionName     = PositionName[i].ToString().Trim();
                temp.EducationalLevel = EducationalLevel[i].ToString().Trim();
                temp.Major            = Major[i].ToString().Trim();
                temp.DemandNum        = Convert.ToInt32(DemandNum[i].ToString().Trim());
                temp.PositionDec      = PositionDec[i].ToString().Trim();

                tempdemandInfo.Add(temp);
            }
            if (Request["IsDeleteFile"].ToString().Trim() == "yes")//yes既表示删除原文件(重新上传),也表示第一次上传
            {
                //处理文件上传
                if (Request.Files.Count > 0)
                {
                    //支持的类型
                    List <string> FileType = new List <string>();
                    FileType.Add("jpg");
                    FileType.Add("gif");
                    FileType.Add("png");
                    FileType.Add("bmp");
                    FileType.Add("jpeg");

                    FileType.Add("pdf");
                    FileType.Add("txt");
                    FileType.Add("xls");
                    FileType.Add("xlsx");
                    FileType.Add("doc");
                    FileType.Add("docx");

                    FileType.Add("rar");
                    FileType.Add("zip");

                    //获取文件
                    HttpPostedFileBase uploadFile = Request.Files[0];
                    //判断是否为空文件
                    if (uploadFile == null)//|| uploadFile.ContentLength == 0)
                    {
                        return(Json(new { message = "fileerror" }));
                    }

                    //截取文件后缀名,判断文件类型是否被支持
                    if (FileType.Contains(uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf(".") + 1)))
                    {
                        //用jobsky作为分段符号
                        var fileTime   = DateTime.Now.ToFileTime().ToString() + Path.GetFileName(uploadFile.FileName); //新命名的文件名(包含时间的整数形式)
                        var tofileName = Path.Combine(Request.MapPath("~/UploadFiles"), fileTime);                     //把两个名字连接起来
                        try
                        {
                            if (Directory.Exists(Server.MapPath("~/UploadFiles")) == false)//如果不存在就创建file文件夹
                            {
                                Directory.CreateDirectory(Server.MapPath("~/UploadFiles"));
                            }
                            uploadFile.SaveAs(tofileName);
                            temparticle.FileAddr = fileTime;//获得上传后的文件名
                        }
                        catch
                        {
                            return(Json(new { message = "fileerror" }));
                        }
                    }
                    else
                    {
                        return(Json(new { message = "fileerror" }));//不支持此格式文件上传
                    }
                }
            }
            else
            {
                temparticle.FileAddr = Request["IsDeleteFile"].ToString().Trim();//没有删除,则获得到的就是原来的文件名
            }

            //添加文章到数据库
            int newTempArticleID = TempArticle.InsertTempArticleFromArticle(temparticle);

            if (newTempArticleID > 0)
            {
                //插入需求到数据库
                foreach (var t in tempdemandInfo)
                {
                    t.TempArticleID = newTempArticleID;
                    if (TempDemandInfo.Insert(t))
                    {
                        //插入成功
                    }
                    else
                    {
                        return(Json(new { message = "inserterror1" }));
                    }
                }
            }

            return(Json(new { message = "success" }));
        }
コード例 #50
0
 // PUT: api/Article/Edit
 public int Edit(int id, [FromBody] Article form)
 {
     form.PrixAchat = (float)form.PrixAchat;
     return(_articleRepo.Update(id, form));
 }
コード例 #51
0
        public override bool Insert(PanelContext data)
        {
            CheckModelData(data);

            Article article = new Article();

            article.ID             = GetValue <string>(data, "ID");
            article.Title          = GetValue <string>(data, "Title");
            article.Description    = GetValue <string>(data, "Description");
            article.SubTitle       = GetValue <string>(data, "SubTitle");
            article.Index          = GetValue <int>(data, "Index");
            article.AllowComments  = GetValue <int>(data, "AllowComments");
            article.Author         = GetValue <string>(data, "Author");
            article.ContentType    = GetValue <int>(data, "ContentType");
            article.ContentUrl     = GetValue <string>(data, "ContentUrl");
            article.Content        = GetValue <string>(data, "Content");
            article.KeyWord        = GetValue <string>(data, "KeyWord");
            article.DescriptionKey = GetValue <string>(data, "DescriptionKey");
            article.Overdue        = GetValue <DateTime>(data, "Overdue");
            article.OwnerID        = GetValue <string>(data, "OwnerID");
            article.Tags           = GetValue <string>(data, "Tags");
            article.PrivacyLevel   = GetValue <int>(data, "PrivacyLevel");
            article.Source         = SiteConfigs.GetConfig().SiteName;
            article.Created        = DateTime.Now;
            article.Updated        = DateTime.Now;
            article.Thumbnail      = GetValue <string>(data, "Thumbnail");
            article.ListKeys       = GetValue <string>(data, "ListKeys");
            article.ListKeys2      = GetValue <string>(data, "ListKeys2");
            article.ListKeys3      = GetValue <string>(data, "ListKeys3");
            article.ListKeys4      = GetValue <string>(data, "ListKeys4");
            article.ListKeys5      = GetValue <string>(data, "ListKeys5");

            string config, schema;

            article.ModelXml    = GetModelDataXml(data, article.ModelXml, out schema, out config);//获取模型数据
            article.ModelConfig = config;
            article.ModelSchema = schema;

            if (article.ModelXml.Length >= MaxCount)
            {
                UIHelper.Message.AppendInfo(MessageType.ERROR, "输入内容过长,请重新输入");
                Logger.WriteLine();
                Logger.WriteDate();
                Logger.Write("输入内容过长");
                Logger.Write(article.ModelXml);
                return(false);
            }

            article.ModelName = data.Model.ModelName;
            article.TableName = data.Table.Name;
            article.State     = GetValue <int>(data, "State");

            if (!String.IsNullOrEmpty(article.OwnerID))
            {
                Channel ch = ChannelHelper.GetChannel(article.OwnerID, null);
                if (ch != null)
                {
                    article.ChannelFullUrl  = ch.FullUrl;
                    article.ChannelName     = ch.FullPath;
                    article.FullChannelPath = ch.FullPath;
                    article.State           = ch.Process != null && ch.Process == "1" ? 2 : article.State;
                }
            }
            int type = 0;

            article.EnumState = StateMgr.StateProcess(article.EnumState, EnumLibrary.Business.ArticleType, type);

            article.AccountID = GetValue <string>(data, "AccountID");
            if (String.IsNullOrEmpty(article.AccountID))
            {
                try
                {
                    article.AccountID = Security.CurrentAccountID;
                }
                catch { }
            }

            ArticleHelper.AddArticle(article);
            ArticleIndexHelper.InsertData(article.ID, 0);
            return(true);
        }
コード例 #52
0
ファイル: ArticleDao.cs プロジェクト: truongdx271/Company
 public int Insert(Article entity)
 {
     db.Articles.Add(entity);
     db.SaveChanges();
     return(entity.Id);
 }
コード例 #53
0
        public IActionResult Index()
        {
            var allArticles = Article.GetArticles("9LWx79tU9QPjIubaRLscjuGoFyngxkKx");

            return(View(allArticles));
        }
コード例 #54
0
 public void CreateArticle(Article article)
 {
     _context.Articles.Add(article);
     Save();
 }
コード例 #55
0
 protected abstract string CreateArticle(Article article);
コード例 #56
0
        public override bool Update(PanelContext data)
        {
            try
            {
                CheckModelData(data);

                Article article = ArticleHelper.GetArticle(GetValue <string>(data, "ID"));
                if (article == null)
                {
                    Insert(data);
                }
                else
                {
                    article.Title          = GetValue <string>(data, "Title");
                    article.Description    = GetValue <string>(data, "Description");
                    article.SubTitle       = GetValue <string>(data, "SubTitle");
                    article.Index          = GetValue <int>(data, "Index");
                    article.AllowComments  = GetValue <int>(data, "AllowComments");
                    article.Author         = GetValue <string>(data, "Author");
                    article.ContentType    = GetValue <int>(data, "ContentType");
                    article.ContentUrl     = GetValue <string>(data, "ContentUrl");
                    article.Content        = GetValue <string>(data, "Content");
                    article.KeyWord        = GetValue <string>(data, "KeyWord");
                    article.DescriptionKey = GetValue <string>(data, "DescriptionKey");
                    article.Overdue        = GetValue <DateTime>(data, "Overdue");
                    article.IsShow         = GetValue <int>(data, "IsShow");
                    article.Tags           = GetValue <string>(data, "Tags");
                    article.OwnerID        = GetValue <string>(data, "OwnerID");
                    article.PrivacyLevel   = GetValue <int>(data, "PrivacyLevel");
                    article.Source         = SiteConfigs.GetConfig().SiteName;
                    article.ListKeys       = GetValue <string>(data, "ListKeys");
                    article.ListKeys2      = GetValue <string>(data, "ListKeys2");
                    article.ListKeys3      = GetValue <string>(data, "ListKeys3");
                    article.ListKeys4      = GetValue <string>(data, "ListKeys4");
                    article.ListKeys5      = GetValue <string>(data, "ListKeys5");

                    article.State = GetValue <int>(data, "State");
                    if (!String.IsNullOrEmpty(article.OwnerID))
                    {
                        Channel ch = ChannelHelper.GetChannel(article.OwnerID, null);
                        if (ch != null)
                        {
                            article.ChannelFullUrl  = ch.FullUrl;
                            article.ChannelName     = ch.FullPath;
                            article.FullChannelPath = ch.FullPath;
                        }
                    }
                    int type = 0;
                    article.EnumState = StateMgr.StateProcess(article.EnumState, EnumLibrary.Business.ArticleType, type);

                    article.Updated = DateTime.Now;

                    string config, schema;
                    article.ModelXml = GetModelDataXml(data, article.ModelXml, out schema, out config);//获取模型数据

                    if (article.ModelXml.Length >= MaxCount)
                    {
                        UIHelper.Message.AppendInfo(MessageType.ERROR, "输入内容过长,请重新输入");
                        Logger.WriteLine();
                        Logger.WriteDate();
                        Logger.Write("输入内容过长");
                        Logger.Write(article.ModelXml);
                        return(false);
                    }
                    article.ModelConfig = config;
                    article.ModelSchema = schema;

                    article.ModelName = data.Model.ModelName;
                    article.TableName = data.Table.Name;
                    string[] updatefields = new string[] { "OwnerID", "ChannelFullUrl", "ChannelName", "FullChannelPath", "Description", "Title", "Content", "ListKeys", "ListKeys2", "ListKeys3", "ListKeys4", "ListKeys5", "Updated", "Index", "EnumState", "Source", "AllowComments", "Author", "State", "IsShow", "SubTitle", "ContentUrl", "ContentType", "Overdue", "Tags", "KeyWord", "DescriptionKey", "ModelXml", "ModelName", "TableName", "ModelConfig", "ModelSchema" };
                    ArticleHelper.UpdateArticle(article, updatefields);

                    // 往全文检索里更新数据
                    ArticleIndexHelper.InsertData(article.ID, 1);
                }
            }
            catch { }

            return(true);
        }
コード例 #57
0
 public void Create(Article article)
 {
     this.articles.Add(article);
     this.articles.SaveChanges();
 }
コード例 #58
0
 public void AddToArticle(Article article)
 {
     base.AddObject("Article", article);
 }
コード例 #59
0
        /// <summary>
        /// Purchase article
        /// </summary>
        public void PurchaseArticles()
        {
            string      answer        = "";
            string      bill          = "";
            int         number        = 0;
            int         currentAmount = 0;
            double      totalPrice    = 0;
            Validations val           = new Validations();

            Console.WriteLine("==============================================\n" +
                              "Return option is disabled until purchase is completed." +
                              "\n==============================================");

            // Do until User presses No as an answer
            do
            {
                int count = ShowAllArticles();

                using (ArticleServiceClient wcf = new ArticleServiceClient())
                {
                    List <Article> allArticles = wcf.GetAllArticles().ToList();

                    // Do until a valid item is selected
                    do
                    {
                        Console.Write("\nSelect an article number: ");
                        number        = val.ValidMaxPositiveNumber(count);
                        currentAmount = allArticles[number - 1].Amount;
                        if (currentAmount == 0)
                        {
                            Console.Write("Cannot select an article that is out of stock.");
                        }
                    } while (currentAmount == 0);

                    // Select amount
                    Console.Write("Choose the amount: ");
                    int amount = val.ValidMaxPositiveNumber(allArticles[number - 1].Amount);

                    // Changed article after reducing the total amount
                    Article article = new Article()
                    {
                        Name   = allArticles[number - 1].Name,
                        Amount = allArticles[number - 1].Amount - amount,
                        Price  = allArticles[number - 1].Price
                    };

                    // Calculate total price and save the item on the bill
                    totalPrice += amount * article.Price;
                    bill       += article.Name + " - " + (amount * article.Price) + " rsd" + "\t\t(" + amount + "*" + article.Price + ")" + "|";
                    wcf.ModifyArticle(article);
                }

                Console.Write("\nWould you like to purchase more items? (yes/no): ");
                answer = val.YesNo();
                Console.Clear();
            } while (answer.ToLower() == "yes");

            // Update bill with all the info before saving it
            bill += "|-----------------------|Total price: " + totalPrice + " rsd|" + "Hour: " + DateTime.Now.ToString("HH:mm:ss") + "|";

            // Save the bill
            using (ArticleServiceClient wcf = new ArticleServiceClient())
            {
                wcf.SaveBill(bill);
            }

            // Bill preview
            Console.WriteLine("Successfult finished the purchase!\n");
            string[] billInfo = bill.Split('|');
            foreach (var item in billInfo)
            {
                Console.WriteLine(item);
            }
        }
コード例 #60
0
ファイル: LineErp.cs プロジェクト: Bargsteen/P5-MI-AAU
 public Line(Article article, int quantity, DateTime timeStamp)
 {
     Article   = article;
     Quantity  = quantity;
     Timestamp = timeStamp;
 }