public static void Main()
        {
            //Serialization
            BlogSite bsObj = new BlogSite()
            {
                Name        = "C-SharpYouCrackedMeUp",
                Description = "Share Knowledge"
            };

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
            MemoryStream msObj            = new MemoryStream();

            js.WriteObject(msObj, bsObj);
            msObj.Position = 0;
            StreamReader sr = new StreamReader(msObj);

            string json = sr.ReadToEnd();

            sr.Close();
            msObj.Close();



            //Deserialization
            json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
                BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
                Console.WriteLine("Name: {0}", bsObj2.Name);
                Console.WriteLine("Description: {0}", bsObj2.Description);
                Console.ReadKey();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Seed database.
        /// </summary>
        /// <param name="context">The <see cref="BlogDbContext"/> to use.</param>
        public static void Seed(BlogDbContext context)
        {
            var blog = new BlogSite {
                Title = "Fluss", SubTitle = "Cnblogs"
            };

            context.Add(blog);
            context.SaveChanges();
            var body = new ContentBlock
            {
                BlogId        = blog.Id,
                Raw           = "<p>content block</p>",
                Content       = "<p>content block</p>",
                RenderConfigs = new List <ContentRenderConfig> {
                    new() { RendererId = Guid.Empty }
                }
            };
            var post = new BlogPost
            {
                Title       = "Fluss is an open-source blog engine",
                Description =
                    "based on .NET,fluss can save and display your work plan or blog post. Content block referring can save your time of maintaining same content between different posts",
                AutoDesc =
                    "based on .NET,fluss can save and display your work plan or blog posts. Content block referring can save your time of maintaining same content between different posts",
                ContentBlocks = new List <ContentBlock> {
                    body
                }
            };

            blog.BlogPosts = new List <BlogPost> {
                post
            };
            context.SaveChanges();
        }
Esempio n. 3
0
        public static void Seed(BlogDbContext context)
        {
            context.Database.EnsureCreated();
            var blog = new BlogSite {
                Title = "Fluss", SubTitle = "Cnblogs"
            };

            context.Add(blog);
            context.SaveChanges();
            var body = new ContentBlock()
            {
                BlogId = blog.Id, Content = "<p>content block can be referred</p>"
            };
            var post = new BlogPost
            {
                Title         = "Fluss is a open-source blog engine",
                Description   = "based on .NET,fluss can save and display your work plan or blog posts。Content block referring can save your time of maintaining same content between different posts",
                AutoDesc      = "based on .NET,fluss can save and display your work plan or blog posts。Content block referring can save your time of maintaining same content between different posts",
                ContentBlocks = new List <ContentBlock> {
                    body
                }
            };

            blog.BlogPosts = new List <BlogPost> {
                post
            };
            context.SaveChanges();
            var referBlock = new ContentBlock()
            {
                BlogId = blog.Id, Refer = body.Id
            };

            post.ContentBlocks.Add(referBlock);
            context.SaveChanges();
        }
Esempio n. 4
0
    public string PurchaseIKeyByCoinpayment(double dblAmount, int IntUserID, int intEpinTypeID, int intEpinCount, double dblEpinPrice, double dblTotPrice)
    {
        string status_url = "";
        SortedList <string, string> listParam = new SortedList <string, string>();

        //add the elements in sortedlist
        listParam.Add("amount", (dblAmount).ToString());
        listParam.Add("currency1", "USD");
        listParam.Add("currency2", "BTC");
        listParam.Add("address", "37KfikBRm8q9b6efZ5pKbggQeA8pKfvyCc");
        listParam.Add("item_name", "A-Code Purchase");
        listParam.Add("ipn_url", "https://www.mysuccesswork.com/portal/user/success_bitcoin.aspx");

        var ret = new Dictionary <string, object>();

        ret = CallAPI("create_transaction", listParam);

        string error = ret["error"].ToString();

        if (error == "ok")
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string   objectString           = serializer.Serialize(ret["result"]);
            BlogSite bsObj = new BlogSite()
            {
                amount          = "",
                txn_id          = "",
                address         = "",
                confirms_needed = "",
                status_url      = "",
                qrcode_url      = ""
            };

            string amount = "", txn_id = "", address = "", confirms_needed = "", qrcode_url = "";
            var    json = new JavaScriptSerializer().Serialize(ret["result"]);
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                // Deserialization from JSON
                DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
                BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
                amount          = bsObj2.amount;
                txn_id          = bsObj2.txn_id;
                address         = bsObj2.address;
                confirms_needed = bsObj2.confirms_needed;
                status_url      = bsObj2.status_url;
                qrcode_url      = bsObj2.qrcode_url;
            }

            clsWallet objwallet = new clsWallet();
            ODBC      clsOdbc   = new ODBC();

            clsOdbc.executeNonQuery("INSERT INTO `mlm_temp_invest_bitcoin`(`userid`, `amount`, `invest_by`, `error`, `btc_amount`, `txn_id`, `address`, `confirms_needed`, `status_url`, `qrcode_url`, `created_on`, epin_type_id, epin_cost, epin_count, total_cost) VALUES (" + IntUserID + ", " + dblAmount + ", " + IntUserID + ", '" + error + "','" + amount + "','" + txn_id + "','" + address + "','" + confirms_needed + "','" + status_url + "','" + qrcode_url + "','" + objwallet.getCurDateTimeString() + "', " + intEpinTypeID + ", " + dblEpinPrice + "," + intEpinCount + ", " + dblTotPrice + "  ) ");
        }

        CommonMessages.ShowAlertMessage(error.ToString());
        return(status_url);
    }
Esempio n. 5
0
        private async Task <BlogSite> LoadWordPressExportAsync(string wpexportFilePath)
        {
            BlogSite blogSite;

            Console.WriteLine($"Reading {wpexportFilePath}");

            using (var reader = File.OpenText(wpexportFilePath))
            {
                var document = await XDocument.LoadAsync(reader, LoadOptions.None, CancellationToken.None).ConfigureAwait(false);

                blogSite = new BlogSite(document);
            }

            return(blogSite);
        }
        public async Task <IActionResult> Seed()
        {
            // Get the default site
            var site = await _api.Sites.GetDefaultAsync();

            site.SiteTypeId = nameof(BlogSite);
            await _api.Sites.SaveAsync(site);

            // Add media assets
            var bannerId = Guid.NewGuid();

            using (var stream = System.IO.File.OpenRead("seed/pexels-photo-355423.jpeg"))
            {
                await _api.Media.SaveAsync(new Piranha.Models.StreamMediaContent()
                {
                    Id       = bannerId,
                    Filename = "pexels-photo-355423.jpeg",
                    Data     = stream
                });
            }
            var banner = await _api.Media.GetByIdAsync(bannerId);

            var logoId = Guid.NewGuid();

            using (var stream = System.IO.File.OpenRead("seed/logo.png"))
            {
                await _api.Media.SaveAsync(new Piranha.Models.StreamMediaContent()
                {
                    Id       = logoId,
                    Filename = "logo.png",
                    Data     = stream
                });
            }

            // Add the site info
            var blogSite = await BlogSite.CreateAsync(_api);

            blogSite.Information.SiteLogo  = logoId;
            blogSite.Information.SiteTitle = "Piranha CMS";
            blogSite.Information.Tagline   = "A lightweight & unobtrusive CMS for Asp.NET Core.";
            await _api.Sites.SaveContentAsync(site.Id, blogSite);

            // Add the blog archive
            var blogId   = Guid.NewGuid();
            var blogPage = await BlogArchive.CreateAsync(_api);

            blogPage.Id              = blogId;
            blogPage.SiteId          = site.Id;
            blogPage.Title           = "Blog Archive";
            blogPage.MetaKeywords    = "Inceptos, Tristique, Pellentesque, Lorem, Vestibulum";
            blogPage.MetaDescription = "Morbi leo risus, porta ac consectetur ac, vestibulum at eros.";
            blogPage.NavigationTitle = "Blog";
            blogPage.Published       = DateTime.Now;

            await _api.Pages.SaveAsync(blogPage);

            // Add a blog post
            var post = await BlogPost.CreateAsync(_api);

            post.BlogId   = blogPage.Id;
            post.Category = "Piranha CMS";
            post.Tags.Add("Welcome", "Fresh Start", "Information");
            post.Title             = "Welcome to Piranha CMS!";
            post.MetaKeywords      = "Welcome, Piranha CMS, AspNetCore, MVC, .NET Core";
            post.MetaDescription   = "Piranha is the fun, fast and lightweight framework for developing cms-based web applications with ASP.Net Core.";
            post.Hero.PrimaryImage = bannerId;
            post.Hero.Ingress      = "<p>Piranha CMS is a <strong>lightweight</strong>, <strong>cross-platform</strong> CMS <string>library</string> for <code>NetStandard 2.0</code>, <code>.NET Core</code> & <code>Entity Framework Core</code>. It can be used to add CMS functionality to your existing application or to build a new website from scratch. It has an extensible & pluggable architecture that can support a wide variety of runtime scenarios.</p>";
            post.Blocks.Add(new HtmlBlock
            {
                Body = "<p>Piranha CMS is a <strong>lightweight</strong>, <strong>cross-platform</strong> CMS <string>library</string> for <code>NetStandard 2.0</code>, <code>.NET Core</code> & <code>Entity Framework Core</code>. It can be used to add CMS functionality to your existing application or to build a new website from scratch. It has an extensible & pluggable architecture that can support a wide variety of runtime scenarios.</p><p>Piranha CMS is totally <strong>package based</strong> and available on <code>NuGet</code>. You can read more about the different packages available in the documentation.</p>"
            });
            post.Blocks.Add(new HtmlBlock
            {
                Body = "<h2>Getting Started</h2><p>To log into the manager interface and start writing content simply go the URL <code>/manager</code> and login with <code>admin</code> / <code>password</code> as your username and password.</p>"
            });
            post.Blocks.Add(new HtmlBlock
            {
                Body = "<h2>Licensing</h2><p>Piranha CMS is released under the <strong>MIT</strong> license. It is a permissive free software license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms and the copyright notice.</p>"
            });
            post.Published = DateTime.Now;
            await _api.Posts.SaveAsync(post);

            // Add about page
            var page = await StandardPage.CreateAsync(_api);

            page.SiteId          = site.Id;
            page.SortOrder       = 1;
            page.Title           = "About Me";
            page.MetaKeywords    = "Inceptos, Tristique, Pellentesque, Lorem, Vestibulum";
            page.MetaDescription = "Morbi leo risus, porta ac consectetur ac, vestibulum at eros.";
            page.Blocks.Add(new HtmlBlock
            {
                Body = "<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Vestibulum id ligula porta felis euismod semper. Nulla vitae elit libero, a pharetra augue. Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla.</p>"
            });
            page.Blocks.Add(new QuoteBlock
            {
                Body = "Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod."
            });
            page.Blocks.Add(new ColumnBlock
            {
                Items = new List <Block>
                {
                    new HtmlBlock
                    {
                        Body = $"<p><img src=\"{banner.PublicUrl.Replace("~", "")}\"></p>"
                    },
                    new HtmlBlock
                    {
                        Body = "<p>Maecenas faucibus mollis interdum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</p>"
                    }
                }
            });
            page.Published = DateTime.Now;
            await _api.Pages.SaveAsync(page);

            return(Redirect("~/"));
        }
Esempio n. 7
0
        public Command Create()
        {
            var cmd = new Command("markdown", "Convert WordPress export files into a markdown format.")
            {
                Handler = CommandHandler.Create(async(string wpexportFilePath, string exportFilePath) =>
                {
                    this.settings = this.settingsManager.LoadSettings(nameof(StackerSettings));

                    if (!File.Exists(wpexportFilePath))
                    {
                        Console.WriteLine($"File not found {wpexportFilePath}");

                        return;
                    }

                    this.serializer = this.serializerFactory.GetSerializer();

                    BlogSite blogSite = await this.LoadWordPressExportAsync(wpexportFilePath).ConfigureAwait(false);

                    var feed = this.LoadFeed(blogSite);

                    var sb      = new StringBuilder();
                    FileInfo fi = new FileInfo(exportFilePath);
                    DirectoryInfo tempHtmlFolder     = new DirectoryInfo(Path.Join(Path.GetTempPath(), "stacker", "html"));
                    DirectoryInfo tempMarkdownFolder = new DirectoryInfo(Path.Join(Path.GetTempPath(), "stacker", "md"));
                    string inputTempHtmlFilePath;
                    string outputTempMarkdownFilePath;
                    string outputFilePath;

                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }

                    if (!tempHtmlFolder.Exists)
                    {
                        tempHtmlFolder.Create();
                    }

                    if (!tempMarkdownFolder.Exists)
                    {
                        tempMarkdownFolder.Create();
                    }

                    await this.downloadTasks.DownloadAsync(feed, exportFilePath).ConfigureAwait(false);

                    foreach (var ci in feed)
                    {
                        var contentItem = this.cleanerManager.PostDownload(ci);

                        sb.AppendLine("---");
                        sb.Append(this.CreateYamlHeader(contentItem));
                        sb.Append("---");
                        sb.Append(Environment.NewLine);
                        sb.Append(Environment.NewLine);

                        await using (var writer = File.CreateText(Path.Combine(tempHtmlFolder.FullName, contentItem.UniqueId + ".html")))
                        {
                            await writer.WriteAsync(contentItem.Content.Body).ConfigureAwait(false);
                        }

                        inputTempHtmlFilePath      = Path.Combine(tempHtmlFolder.FullName, contentItem.UniqueId + ".html");
                        outputTempMarkdownFilePath = Path.Combine(tempMarkdownFolder.FullName, contentItem.UniqueId + ".md");
                        outputFilePath             = Path.Combine(exportFilePath, contentItem.Author.Username.ToLowerInvariant(), contentItem.UniqueId + ".md");

                        FileInfo outputFile = new FileInfo(outputFilePath);

                        if (!outputFile.Directory.Exists)
                        {
                            outputFile.Directory.Create();
                        }

                        if (this.ExecutePandoc(inputTempHtmlFilePath, outputTempMarkdownFilePath))
                        {
                            sb.Append(await File.ReadAllTextAsync(outputTempMarkdownFilePath).ConfigureAwait(false));

                            string content = sb.ToString();

                            Console.WriteLine(outputFilePath);

                            try
                            {
                                content = this.cleanerManager.PostConvert(content);
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine(exception.Message);
                            }

                            await using (var writer = File.CreateText(outputFilePath))
                            {
                                await writer.WriteAsync(content).ConfigureAwait(false);
                            }
                        }

                        // Remote the temporary html file.
                        File.Delete(inputTempHtmlFilePath);

                        sb.Clear();
                    }
                }),
            };

            cmd.AddArgument(new Argument <string>("wp-export-file-path")
            {
                Description = "WordPress Export file path."
            });
            cmd.AddArgument(new Argument <string>("export-file-path")
            {
                Description = "File path for the exported files."
            });

            return(cmd);
        }
Esempio n. 8
0
        private List <ContentItem> LoadFeed(BlogSite blogSite)
        {
            Console.WriteLine($"Processing...");

            var feed     = new List <ContentItem>();
            var settings = this.settingsManager.LoadSettings(nameof(StackerSettings));
            var posts    = blogSite.GetAllPostsInAllPublicationStates().ToList();

            Console.WriteLine($"Total Posts: {posts.Count}");

            // var attachments = posts.Where(x => x.Attachments.Any());
            foreach (var post in posts)
            {
                var user = settings.Users.Find(u => string.Equals(u.Email, post.Author.Email, StringComparison.InvariantCultureIgnoreCase));

                if (user == null)
                {
                    throw new NotImplementedException($"User {post.Author.Email} has not been configured. Update the settings file.");
                }

                var ci = new ContentItem
                {
                    Author = new AuthorDetails
                    {
                        DisplayName   = post.Author.DisplayName,
                        Email         = post.Author.Email,
                        TwitterHandle = user.Twitter,
                        Username      = post.Author.Username,
                    },
                    Categories = post.Categories.Select(c => c.Name).Where(x => !this.IsCategoryExcluded(x)),
                    Content    = new ContentDetails
                    {
                        Attachments = post.Attachments.Select(x => new ContentAttachment {
                            Path = x.Path, Url = x.Url
                        }).ToList(),
                        Body    = post.Body,
                        Excerpt = post.Excerpt,
                        Link    = post.Link,
                        Title   = post.Title,
                    },
                    Id           = post.Id,
                    PublishedOn  = post.PublishedAtUtc,
                    Promote      = post.Promote,
                    PromoteUntil = post.PromoteUntil,
                    Slug         = post.Slug,
                    Status       = post.Status,
                    Tags         = post.Tags.Where(t => t != null).Select(t => t.Name),
                };

                // Search the body for any missing images.
                var matches = Regex.Matches(post.Body, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        if (!ci.Content.Attachments.Any(x => string.Equals(x.Url, match.Groups[1].Value, StringComparison.InvariantCultureIgnoreCase)) && this.IsRelevantHost(match.Groups[1].Value))
                        {
                            ci.Content.Attachments.Add(new ContentAttachment {
                                Path = match.Groups[1].Value, Url = match.Groups[1].Value
                            });
                        }
                    }
                }

                ci = this.cleanerManager.PreDownload(ci);

                feed.Add(ci);
            }

            return(feed);
        }
        public Command Create()
        {
            var cmd = new Command("universal", "Convert WordPress export files into a universal format.")
            {
                Handler = CommandHandler.Create(async(string wpexportFilePath, string universalFilePath) =>
                {
                    if (!File.Exists(wpexportFilePath))
                    {
                        Console.WriteLine($"File not found {wpexportFilePath}");

                        return;
                    }

                    BlogSite blogSite;

                    Console.WriteLine($"Reading {wpexportFilePath}");

                    using (var reader = File.OpenText(wpexportFilePath))
                    {
                        var document = await XDocument.LoadAsync(reader, LoadOptions.None, CancellationToken.None).ConfigureAwait(false);
                        blogSite     = new BlogSite(document);
                    }

                    Console.WriteLine($"Processing...");

                    var settings         = this.settingsManager.LoadSettings(nameof(StackerSettings));
                    var posts            = blogSite.GetAllPosts().ToList();
                    var validPosts       = posts.FilterByValid(settings).ToList();
                    var promotablePosts  = validPosts.FilterByPromotable().ToList();
                    var hashTagConverter = new WordPressTagToHashTagConverter();
                    var feed             = new List <ContentItem>();

                    Console.WriteLine($"Total Posts: {posts.Count()}");
                    Console.WriteLine($"Valid Posts: {validPosts.Count()}");
                    Console.WriteLine($"Promotable Posts: {promotablePosts.Count()}");

                    foreach (var post in promotablePosts)
                    {
                        var user = settings.Users.Find(u => string.Equals(u.Email, post.Author.Email, StringComparison.InvariantCultureIgnoreCase));

                        feed.Add(new ContentItem
                        {
                            Author = new AuthorDetails
                            {
                                DisplayName   = post.Author.DisplayName,
                                Email         = post.Author.Email,
                                TwitterHandle = user.Twitter,
                            },
                            Content = new ContentDetails
                            {
                                Body    = post.Body,
                                Excerpt = post.Excerpt,
                                Link    = post.Link,
                                Title   = post.Title,
                            },
                            PublishedOn  = post.PublishedAtUtc,
                            Promote      = post.Promote,
                            PromoteUntil = post.PromoteUntil,
                            Status       = post.Status,
                            Slug         = post.Slug,
                            Tags         = post.Tags.Where(t => t != null).Select(t => t.Name),
                        });
                    }

                    await using (var writer = File.CreateText(universalFilePath))
                    {
                        await writer.WriteAsync(JsonConvert.SerializeObject(feed, Formatting.Indented)).ConfigureAwait(false);
                    }

                    Console.WriteLine($"Content written to {universalFilePath}");
                }),
            };

            cmd.AddArgument(new Argument <string>("wp-export-file-path")
            {
                Description = "WordPress Export file path."
            });
            cmd.AddArgument(new Argument <string>("universal-file-path")
            {
                Description = "Universal file path."
            });

            return(cmd);
        }
Esempio n. 10
0
 public BlogSite CreateBlogSite(BlogSite blogSite)
 {
     context.BlogSites.Add(blogSite);
     context.SaveChanges();
     return(blogSite);
 }