Exemple #1
0
        public void TestShouldThrowEmptyExtension()
        {
            //Arrange
            string fileName = "tests\\testEmptyExtension";

            //Act

            try
            {
                FileContentProvider provider = new FileContentProvider();
                var file = (content : provider.GetContent(fileName), extension : Path.GetExtension(fileName));

                FileProcessorFactory fileProcessorFactory = new FileProcessorFactory();
                var fileProcessor = fileProcessorFactory.CreateFileProcessor(file.content, file.extension);
                fileProcessor.Process(file.content);
            }
            catch (System.ArgumentException e)
            {
                // Assert
                StringAssert.Contains(e.Message, FileProcessorFactory.EmptyExtensionMessage);
                return;
            }

            Assert.Fail("The expected exception was not thrown.");
        }
Exemple #2
0
        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
            var provider = new FileContentProvider(Path.Combine(RootPathProvider.GetRootPath(), "Content\\Posts"));

            container.Register <IContentProvider, FileContentProvider>(provider);
            container.Register <IMarkdownService, MarkdownService>().AsSingleton();
            container.Register <IPostParser, KiwiMarkdownPostParser>().AsSingleton();
            container.Register <PostProvider>().AsSingleton();
        }
Exemple #3
0
        public void Execute(string[] arguments)
        {
            Settings.Parse(arguments);
            Console.WriteLine("Port: " + Port);
            Console.WriteLine("Debug: " + Debug);

            var f = new FileContentProvider();
            var w = new WebHost(Directory.GetCurrentDirectory(), f);
            w.Start();
            Console.ReadLine();
        }
Exemple #4
0
        public void Execute(string[] arguments)
        {
            Tracing.Info("taste - testing a site locally");
            Settings.Parse(arguments);
            if (Port == 0)
            {
                Port = 8080;
            }

            var f = new FileContentProvider();
            if (string.IsNullOrWhiteSpace(Path))
            {
                Path = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Engine))
            {
                Engine = InferEngineFromDirectory(Path);
            }

            engine = templateEngines[Engine];

            if (engine == null)
                return;

            var context = new SiteContext { Folder = Path };
            engine.Initialize();
            engine.Process(context);

            var watcher = new SimpleFileSystemWatcher();
            watcher.OnChange(Path, WatcherOnChanged);

            var w = new WebHost(engine.GetOutputDirectory(Path), f);
            w.Start();

            Tracing.Info("Press 'Q' to stop the web host...");
            ConsoleKeyInfo key;
            do
            {
                key = Console.ReadKey();
            }
            while (key.Key != ConsoleKey.Q);
        }
Exemple #5
0
        public void TestTextFile()
        {
            //Arrange
            string fileName = "tests\\testText.txt";
            string expected = "text";

            //Act
            FileContentProvider provider = new FileContentProvider();
            var file = (content : provider.GetContent(fileName), extension : Path.GetExtension(fileName));

            FileProcessorFactory fileProcessorFactory = new FileProcessorFactory();
            var fileProcessor = fileProcessorFactory.CreateFileProcessor(file.content, file.extension);

            fileProcessor.Process(file.content);

            //Assert
            string actual = fileProcessor.ReturnType();

            Assert.AreEqual(expected, actual, "Wrong type (expected:" + expected);
        }
Exemple #6
0
        public void Execute(string[] arguments)
        {
            Tracing.Info("taste - testing a site locally");
            Settings.Parse(arguments);
            if (Port == 0)
            {
                Port = 8080;
            }

            Tracing.Info("Port: " + Port);
            Tracing.Info("Debug: " + Debug);

            var f = new FileContentProvider();
            var w = new WebHost(Directory.GetCurrentDirectory(), f);
            w.Start();

            Tracing.Info("Press 'Q' to stop the process");
            ConsoleKeyInfo key;
            do
            {
                key = Console.ReadKey();
            }
            while (key.Key != ConsoleKey.Q);
        }
Exemple #7
0
 public void Refresh(FileContentProvider contentProvider)
 {
     _data = contentProvider.GetArray();
 }
Exemple #8
0
 private void RaiseCommited(String filePath, FileContentProvider fileStream)
 {
     Commited?.Invoke(filePath, fileStream);
 }
        public CommandResult Execute(NewPostCommand command)
        {
            //TODO:应该验证TitleSlug是否唯一
            var contentProvider = new FileContentProvider(null, Encoding.UTF8);
            var parser          = new MarkdownService(contentProvider);
            var content         = parser.ToHtml(command.MarkDown);

            var post = new BlogPost
            {
                Id                = ObjectId.NewObjectId(),
                AuthorEmail       = command.Author.Email,
                AuthorDisplayName = command.Author.DisplayName,
                MarkDown          = command.MarkDown,
                Content           = content,
                PubDate           = command.PubDate.CloneToUtc(),
                Status            = command.Published ? PublishStatus.Published : PublishStatus.Draft,
                Title             = command.Title,
                TitleSlug         = command.TitleSlug.IsNullOrWhitespace() ? command.Title.Trim().ToSlug() : command.TitleSlug.Trim().ToSlug(),
                DateUTC           = DateTime.UtcNow
            };

            using (var db = new LiteDatabase(_dbConfig.DbPath))
            {
                if (!command.Tags.IsNullOrWhitespace())
                {
                    var tags = command.Tags.AsTags();
                    post.Tags = tags.Keys.ToArray();

                    var tagCol = db.GetCollection <Tag>(DBTableNames.Tags);
                    foreach (var kv in tags)
                    {
                        var slug = kv.Key;
                        var tag  = kv.Value;

                        if (string.IsNullOrWhiteSpace(tag))
                        {
                            continue;
                        }

                        var entry = tagCol.FindOne(t => t.Slug.Equals(slug));
                        if (entry != null)
                        {
                            entry.PostCount++;
                            tagCol.Update(entry);
                        }
                        else
                        {
                            entry = new Tag
                            {
                                Id        = ObjectId.NewObjectId(),
                                Slug      = slug,
                                Name      = tag,
                                PostCount = 1
                            };
                            tagCol.Insert(entry);
                        }
                    }

                    tagCol.EnsureIndex(t => t.PostCount);
                }
                else
                {
                    post.Tags = new string[] { };
                }

                var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts);
                blogPostCol.Insert(post);

                return(CommandResult.SuccessResult);
            }
        }
Exemple #10
0
        //When deployed on server
        //private const string jsonFile = @"Data.json";
        //private const string jsonDirr = @"~/Json/";
        //private const string MDDB = jsonDirr + jsonFile;
        //private const string MD2 = @"~/MD2/";
        //private const string MD = @"~/MD/";


        public IndexModule()
        {
            //async syntax
            //Get["/aa", true] = async (parameters, ct) => "Hello World!";

            Models.Errors errorMsg = new Models.Errors();

            //var ses = Request.Session;
            Get["/"] = _ =>
            {
                Request.Session["filter"]         = "";
                Request.Session["LoggedInStatus"] = false;


                return(View["default"]);
            };
            Get["/ms_iot_Community_Samples"] = _ =>
            {
                bool getList = false;
                if (Models.BlogPost.BlogPostz == null)
                {
                    getList = true;
                }
                else if (Models.BlogPost.BlogPostz.Count() == 0)
                {
                    getList = true;
                }
                if (getList)
                {
                    string[] files1 = Directory.GetFiles(jsonDirr, jsonFile);
                    if (files1.Length != 1)
                    {
                        return(View["IndexList"]);
                    }
                    string document = "";
                    document = File.ReadAllText(MDDB);

                    JsonSerializerSettings set = new JsonSerializerSettings();
                    set.MissingMemberHandling = MissingMemberHandling.Ignore;
                    Models.BlogPost[] md = JsonConvert.DeserializeObject <Models.BlogPost[]>(document, set);

                    var mdd = from n in md select n;
                    //Objects.BlogPost.BlogPostz = md.Select(data => data)).ToList()
                    Models.BlogPost.BlogPostz = md.ToList <Models.BlogPost>();
                    Request.Session["filter"] = "";
                }

                return(View["/ms_iot_Community_Samples/ms_iot_Community_Samples", errorMsg]);
                //Models.BlogPost.ViewBlogPostz((string) Request.Session["filter"])];
            };

            /*******************
             * Get["/ms_iot_Community_Samples/load"] = _ =>
             * {
             *  string[] files1 = Directory.GetFiles( jsonDirr, jsonFile);
             *  if (files1.Length != 1)
             *      return View["IndexList"];
             *  string document = "";
             *  document= File.ReadAllText(MDDB);
             *
             *  JsonSerializerSettings set = new JsonSerializerSettings();
             *  set.MissingMemberHandling = MissingMemberHandling.Ignore;
             *  Models.BlogPost[] md = JsonConvert.DeserializeObject<Models.BlogPost[]>(document, set);
             *
             *  var mdd = from n in md select n;
             *  Models.BlogPost.BlogPostz = md.ToList<Models.BlogPost>();
             *  Models.BlogPost.ResetBlogPostz();
             *  Request.Session["filter"] = "";
             *  return View["/ms_iot_Community_Samples/IndexList"];
             * };
             **/
            Get["/ms_iot_Community_Samples/default"] = _ => {
                Request.Session["filter"]         = "";
                Request.Session["LoggedInStatus"] = false;
                return(View["default"]);
            };
            Get["/ms_iot_Community_Samples/login/{referer}"] = parameters => {
                string referer = parameters.referer;
                if (referer == "0")
                {
                    referer = "ms_iot_Community_Samples";
                }
                else
                {
                    referer = "IndexList";
                }
                return(View["/ms_iot_Community_Samples/login", referer]);
            };
            Get["/ms_iot_Community_Samples/logout/{referer}"] = parameters => {
                string referer = parameters.referer;
                if (referer == "0")
                {
                    referer = "ms_iot_Community_Samples";
                }
                else
                {
                    referer = "IndexList";
                }
                //Models.Errors.LoggedInStatus = false;
                Request.Session["filter"]         = "";
                Request.Session["LoggedInStatus"] = false;
                errorMsg.Message        = "Logged out.";
                errorMsg.Source         = "/Logout";
                errorMsg.LoggedInStatus = false;
                if (referer == "ms_iot_Community_Samples")
                {
                    return(View["/ms_iot_Community_Samples/" + referer, errorMsg]);
                }
                else
                {
                    return(View["/ms_iot_Community_Samples/" + referer, Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
                }
            };
            Get["/ms_iot_Community_Samples/onlogin/{referer}/{user}/{pwd}"] = parameters => {
                string user    = parameters.user;
                string pwd     = parameters.pwd;
                string referer = parameters.referer;
                Request.Session["filter"]         = "";
                Request.Session["LoggedInStatus"] = false;
#if ISDEPLOYED
                //http://www.dotnetprofessional.com/blog/post/2008/03/03/Encrypt-sections-of-WebConfig-or-AppConfig.aspx
                NameValueCollection secureAppSettings =
                    (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
                string admin    = (string)secureAppSettings["Admin.UserName"];
                string adminPwd = (string)secureAppSettings["Admin.Pwd"];
#else
                string admin    = (string)ConfigurationManager.AppSettings["Admin.UserName"];
                string adminPwd = (string)ConfigurationManager.AppSettings["Admin.Pwd"];
#endif
                user = user.Trim();
                pwd  = pwd.Trim();
                if ((user == admin) && (pwd == adminPwd))
                {
                    Request.Session["LoggedInStatus"] = true;
                    errorMsg.Message        = "Logged in.";
                    errorMsg.Source         = "/OnLogin";
                    errorMsg.LoggedInStatus = true;
                }
                else
                {
                    Request.Session["LoggedInStatus"] = false;
                    errorMsg.Message        = "Login failed!";
                    errorMsg.Source         = "/OnLogin";
                    errorMsg.LoggedInStatus = false;
                    return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]);
                }
                if (referer == "ms_iot_Community_Samples")
                {
                    return(View["/ms_iot_Community_Samples/ms_iot_Community_Samples", errorMsg]);
                }
                else
                {
                    return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
                }
            };


            Get["/ms_iot_Community_Samples/convert"] = _ =>
            {
                if (!(bool)Request.Session["LoggedInStatus"])
                {
                    errorMsg.Message = "Not logged in!";
                    errorMsg.Source  = "/Convert";
                    return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]);
                }
                string[] files0 = Directory.GetFiles(jsonDirr, "*.*");

                foreach (string file in files0)
                {
                    File.Delete(file);
                }

                string[] files1 = Directory.GetFiles(MD2, "*.*");

                foreach (string file in files1)
                {
                    File.Delete(file);
                }

                char[]   lineSep = new char[] { '\r', '\n' };
                string[] files   = Directory.GetFiles(MD, "*.MD");
                //File.AppendAllText(MDDB, "[\r\n");

                int  count     = files.Length;
                bool abortFile = false;
                Models.BlogPost.ClearBlogPostz();
                foreach (string file in files)
                {
                    abortFile = false;
                    try {
                        string filename = Path.GetFileNameWithoutExtension(file);
                        count--;
                        string fileTxt = File.ReadAllText(file);

                        //Get database between 1st and second lines of ---
                        int startIndex = fileTxt.IndexOf(DBSep, 0);
                        if (startIndex < 0)
                        {
                            continue;
                        }

                        int endIndex = fileTxt.IndexOf(DBSep, startIndex + DBSep.Length);
                        if (endIndex < 0)
                        {
                            continue;
                        }

                        string DB2 = fileTxt.Substring(startIndex, endIndex - startIndex + DBSep.Length) + "\r\n";
                        string DB  = fileTxt.Substring(startIndex + DBSep.Length, endIndex - startIndex - DBSep.Length).Trim();
                        fileTxt = fileTxt.Substring(endIndex + DBSep.Length);
                        string[]        lines    = DB.Split(lineSep);
                        Models.BlogPost blogpost = new Models.BlogPost();
                        blogpost.filename = filename;
                        foreach (string line in lines)
                        {
                            string newLine = line.Trim();
                            if (newLine != "")
                            {
                                string[] parts  = newLine.Split(new char[] { ':' });
                                string   vname  = parts[0].Trim();
                                string   vvalue = parts[1].Trim();
                                try
                                {
                                    var fields = typeof(Models.BlogPost).GetFields(
                                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                                    var field = from n in fields where n.Name.Substring(1).Replace(">k__BackingField", "") == vname select n;
                                    if (field.Count() == 1)
                                    {
                                        field.First().SetValue(blogpost, vvalue);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //Abort lines loop
                                    abortFile = true;
                                    break;
                                }
                            }
                        }
                        if (abortFile)
                        {
                            //Abort this db record
                            break;
                        }
                        string name = Path.GetFileName(file);
                        File.WriteAllText(MD2 + name, fileTxt);
                    }
                    catch (Exception ex)
                    {
                        //Skip this file and continue with next
                        continue;
                    }
                }
                Request.Session["filter"] = "";
                string json = JsonConvert.SerializeObject(Models.BlogPost.BlogPostz);

                File.AppendAllText(MDDB, json);
                Request.Session["filter"] = "";
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };

            Get["/ms_iot_Community_Samples/display/{name}"] = parameters =>
            {
                var contentProvider = new FileContentProvider(MD2, null);
                var converter       = new MarkdownService(contentProvider);
                var document        = converter.GetDocument(parameters.name);
                return(document.Content);
            };


            Get["/ms_iot_Community_Samples/GitHub", true] = async(parameters, ct) =>
            {
                if (!(bool)Request.Session["LoggedInStatus"])
                {
                    errorMsg.Message = "Not logged in!";
                    errorMsg.Source  = "/GitHub";
                    return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]);
                }
#if ISDEPLOYED
                NameValueCollection secureAppSettings =
                    (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
                string githuUrl   = (string)secureAppSettings["GitHub.Url"];
                string githubRepo = (string)secureAppSettings["GitHub.Repository"];
                string githubUsr  = (string)secureAppSettings["GitHub.UserName"];
                string githubPwd  = (string)secureAppSettings["GitHub.Pwd"];
#else
                string githuUrl   = (string)ConfigurationManager.AppSettings["GitHub.Url"];
                string githubRepo = (string)ConfigurationManager.AppSettings["GitHub.MDsRepository"];
                string githubUsr  = (string)ConfigurationManager.AppSettings["GitHub.UserName"];
                string githubPwd  = (string)ConfigurationManager.AppSettings["GitHub.Pwd"];
#endif
                //http://haacked.com/archive/2014/04/24/octokit-oauth/
                string clientId     = "2c0baac7c20dd4fb52b5";
                string clientSecret = "f14d3e9055a292128abe472ab0b000a2a8c87166"; //f14d3e9055a292128abe472ab0b000a2a8c87166
                                                                                  //readonly
                GitHubClient client3 =
                    new GitHubClient(new ProductHeaderValue(githubRepo), new Uri(githuUrl));
                //https://github.com/octokit/octokit.net
                var github = new GitHubClient(new ProductHeaderValue(githubRepo));
                var user   = await github.User.Get(githubUsr);

                var client    = new GitHubClient(new ProductHeaderValue(githubRepo));
                var basicAuth = new Credentials(githubUsr, githubPwd); // NOTE: not real credentials
                client3.Credentials = basicAuth;

                //var client = new GitHubClient(new ProductHeaderValue("dotnet-test-functional"));
                //client.Credentials = GithubHelper.Credentials;
                //http://stackoverflow.com/questions/24830617/reading-code-from-repository
                var repos = await client3.Repository.GetAllForCurrent();

                var repo = from n in repos where n.Name == githubRepo select n;
                if (repo.Count() == 1)
                {
                    var AllContent = await client.Repository.Content.GetAllContents(repo.First().Id);//.GetAllContent(repos[0].Owner.Login, repos[0].Name);

                    var textOfFirstFile     = AllContent[0].Content;
                    var textOfFirstFileName = AllContent[0].Name;
                    var AllContent2         = await client.Repository.Content.GetAllContents(repo.First().Id, textOfFirstFileName);

                    var textOfFirstFile2     = AllContent[1].Content;
                    var textOfFirstFile2Name = AllContent[1].Name;
                    var AllContent3          = await client.Repository.Content.GetAllContents(repo.First().Id, textOfFirstFile2Name);
                }

                //var pull = await client3.PullRequest.GetAllForRepository("djaus2", "ms-iot-community-samples");

                //var client2 = new GitHubClient(new ProductHeaderValue("ms-iot-community-samples"));
                //var tokenAuth = new Credentials("token"); // NOTE: not real token
                //client2.Credentials = tokenAuth;

                Request.Session["LoggedInStatus"] = false;
                Request.Session["filter"]         = "";
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };


            Get["/ms_iot_Community_Samples/Sort/{field}"] = parameters =>
            {
                string sortString = parameters.field;
                Models.FilterAndSortInfo fi;
                if ((string)Request.Session["filter"] == null)
                {
                    fi = new Models.FilterAndSortInfo();
                }
                else if ((string)Request.Session["filter"] == "")
                {
                    fi = new Models.FilterAndSortInfo();
                }
                else
                {
                    JsonSerializerSettings set = new JsonSerializerSettings();
                    set.MissingMemberHandling = MissingMemberHandling.Ignore;
                    fi = JsonConvert.DeserializeObject <Models.FilterAndSortInfo>((string)Request.Session["filter"], set);
                }
                //For filter remove any pre-existing sorting (but for sort don't remove pre-existing sorting).
                fi.SortString = sortString;
                string json = JsonConvert.SerializeObject(fi);
                Request.Session["filter"] = json;
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };

            Get["/ms_iot_Community_Samples/ClearSort"] = _ =>
            {
                if ((string)Request.Session["filter"] != null)
                {
                    if ((string)Request.Session["filter"] == "")
                    {
                        ((Models.FilterAndSortInfo)Request.Session["filter"]).SortString = "";
                    }
                }
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };


            Get["/ms_iot_Community_Samples/Show/{id}"] = parameters =>
            {
                string          id       = parameters.id;
                Models.BlogPost blogPost = Models.BlogPost.Get(id);
                if (blogPost != null)
                {
                    return(View["/ms_iot_Community_Samples/Index", blogPost]);
                }
                else
                {
                    return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
                }
            };
            Get["/ms_iot_Community_Samples/reset"] = _ =>
            {
                Request.Session["filter"] = "";
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };
            Get["/ms_iot_Community_Samples/clear"] = _ =>
            {
                Request.Session["filter"] = "";
                Models.BlogPost.ClearBlogPostz();
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };
            Get["/ms_iot_Community_Samples/list"] = _ =>
            {
                string filter = (string)Request.Session["filter"];
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };

            Get["/ms_iot_Community_Samples/ClearFilter"] = _ =>
            {
                //Same as reset
                Request.Session["filter"] = "";
                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };
            Get["/ms_iot_Community_Samples/Filter/{idfilter}/{titlefilter}/{summaryfilter}/{codefilter}/{tagsfilter}/{tagsfilter2}"] = parameters =>
            {
                char[]   sep = new char[] { '~' };
                string[] tupl;
                var      filters = new List <Tuple <string, string> >();

                string filter = parameters.idfilter;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("z", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                filter = parameters.titlefilter;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("z", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                filter = parameters.summaryfilter;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("z", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                filter = parameters.codefilter;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("Y", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                filter = parameters.tagsfilter;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("Y", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                filter = parameters.tagsfilter2;
                filter = filter.Replace("Z", "+");
                filter = filter.Replace("z", "/");
                filter = filter.Trim();
                if (filter != "")
                {
                    tupl = filter.Split(sep);
                    if (tupl.Length == 2)
                    {
                        if (tupl[0] != "")
                        {
                            if (Models.BlogPost.Fields.Contains(tupl[0]))
                            {
                                if (tupl[1] != "")
                                {
                                    filters.Add(new Tuple <string, string>(tupl[0], tupl[1]));
                                }
                            }
                        }
                    }
                }
                Models.FilterAndSortInfo fi;
                if ((string)Request.Session["filter"] == null)
                {
                    fi = new Models.FilterAndSortInfo();
                }
                else if ((string)Request.Session["filter"] == "")
                {
                    fi = new Models.FilterAndSortInfo();
                }
                else
                {
                    JsonSerializerSettings set = new JsonSerializerSettings();
                    set.MissingMemberHandling = MissingMemberHandling.Ignore;
                    fi = JsonConvert.DeserializeObject <Models.FilterAndSortInfo>((string)Request.Session["filter"], set);
                }
                //For filter remove any pre-existing sorting (but for sort don't remove pre-existing sorting)
                fi.Filters    = filters;
                fi.SortString = "";
                string json = JsonConvert.SerializeObject(fi);
                Request.Session["filter"] = json;


                return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]);
            };
        }
Exemple #11
0
        public CommandResult Execute(EditPostCommand command)
        {
            using (var db = new LiteDatabase(_dbConfig.DbPath))
            {
                var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts);
                var post        = blogPostCol.FindById(command.PostId);

                if (post == null)
                {
                    throw new ApplicationException("Post with id: {0} was not found".FormatWith(command.PostId));
                }

                if (post.Tags != null)
                {
                    var tagCol = db.GetCollection <Tag>(DBTableNames.Tags);
                    foreach (var tag in post.Tags)
                    {
                        var slug     = tag.ToSlug();
                        var tagEntry = tagCol.FindOne(x => x.Slug.Equals(slug));
                        if (tagEntry != null)
                        {
                            tagEntry.PostCount--;
                            tagCol.Update(tagEntry);
                        }
                    }
                }

                var contentProvider = new FileContentProvider(null, Encoding.UTF8);
                var parser          = new MarkdownService(contentProvider);
                var content         = parser.ToHtml(command.MarkDown);
                //TODO:应该验证TitleSlug是否是除了本文外唯一的

                post.MarkDown  = command.MarkDown;
                post.Content   = content;
                post.PubDate   = command.PubDate.CloneToUtc();
                post.Status    = command.Published ? PublishStatus.Published : PublishStatus.Draft;
                post.Title     = command.Title;
                post.TitleSlug = command.TitleSlug.Trim().ToSlug();

                if (!command.Tags.IsNullOrWhitespace())
                {
                    var tags = command.Tags.AsTags();
                    post.Tags = tags.Keys.ToArray();

                    var tagCol = db.GetCollection <Tag>(DBTableNames.Tags);
                    foreach (var kv in tags)
                    {
                        var slug = kv.Key;
                        var tag  = kv.Value;

                        var entry = tagCol.FindOne(x => x.Slug.Equals(slug));
                        if (entry != null)
                        {
                            entry.PostCount++;
                            tagCol.Update(entry);
                        }
                        else
                        {
                            entry = new Tag
                            {
                                Id        = ObjectId.NewObjectId(),
                                Slug      = slug,
                                Name      = tag,
                                PostCount = 1
                            };
                            tagCol.Insert(entry);
                        }
                    }
                }
                else
                {
                    post.Tags = new string[] { };
                }

                db.GetCollection <BlogPost>(DBTableNames.BlogPosts).Update(post);
                return(CommandResult.SuccessResult);
            }
        }
Exemple #12
0
        static async Task Main(string[] args)
        {
            var version = new VersionInformationService();

            // original and best
            Console.WriteLine(await version.EntryAssemblyAsync());

            // assembly using the default type handler
            Console.WriteLine(await version.FromSourceAsync(Assembly.GetEntryAssembly()));

            // a custom string
            Console.WriteLine(await version.FromSourceAsync("Hello"));

            // a custom object
            dynamic obj = new
            {
                Major     = 1,
                Minor     = 2,
                Codename  = "Alhambra",
                TimeStamp = DateTime.UtcNow
            };

            Console.WriteLine(JsonConvert.SerializeObject(
                                  await version.FromSourceAsync(obj)));

            // a custom provider
            Console.WriteLine(await version.FromSourceAsync(new MyProvider()));

            // With a Keyed Handler
            const string key = "MyKey";

            version.KeyHandlers[key] = new MyProvider();
            // with no source needed
            Console.WriteLine(await version.ByKeyAsync(key));
            // or with a "source"
            Console.WriteLine(await version.FromSourceAsync(null, key));

            // With a Typed Handler
            version.TypeHandlers[typeof(bool)] = new MyProvider();
            Console.WriteLine(await version.FromSourceAsync(true));

            // Aggregating multiple sources
            Console.WriteLine(JsonConvert.SerializeObject(
                                  await version.FromSourceAsync(new
            {
                Source1 = await version.ByKeyAsync(key),
                Source2 = new { Key1 = 1, Key2 = "2" },
                Source3 = await version.EntryAssemblyAsync()
            })));

            // all the text content from a file
            var fileProvider = new FileContentProvider("filecontent.txt");

            Console.WriteLine(await version.FromSourceAsync(fileProvider));
            version.KeyHandlers.Add("file", fileProvider);
            fileProvider.FilePath = "";
            Console.WriteLine(await version.ByKeyAsync("file", "filecontent.txt"));

            // key value string pairs from a file
            Console.WriteLine(JsonConvert.SerializeObject(
                                  await version.FromSourceAsync(
                                      new KeyValueFileProvider("keyvalue.txt"))));

            // no file (returns null)
            Console.WriteLine(JsonConvert.SerializeObject(
                                  await version.FromSourceAsync(
                                      new KeyValueFileProvider {
                FileOptional = true
            })));

            // hiding null properties
            Console.WriteLine(JsonConvert.SerializeObject(
                                  new
            {
                Prop1 = "Prop2 should be hidden because it's null",
                Prop2 = await version.FromSourceAsync(
                    new KeyValueFileProvider {
                    FileOptional = true
                })
            },
                                  new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            }));

            // some synchronous tests
            Console.WriteLine(version.EntryAssembly());
            Console.WriteLine(version.FromSource("hello there"));
            Console.WriteLine(JsonConvert.SerializeObject(version.ByKey("file")));

            Console.Read();
        }