public JsonResult AddLink(string suggestion)
        {
            //SetupCurrentUser();

            try
            {
                doctormembraincomContext db = new doctormembraincomContext();
                bool ok;
                suggestion = StringHelper.OnlyAlphanumeric(suggestion.ToLower().Trim(), false, false, "", new char[] { ' ' }, out ok);

                if (ok)
                {
                    Wiki w = db.Wiki.Where(x => x.Title.ToLower().Trim().Contains(suggestion)).FirstOrDefault();

                    if (w != null)
                    {
                        return(Json(new { success = true, id = w.Id, title = w.Title }));
                    }
                    else
                    {
                        return(Json(new { success = false }));
                    }
                }
                else
                {
                    return(Json(new { success = false }));
                }
            }
            catch (Exception e)
            {
                return(Json(new { success = false }));
            }
        }
Example #2
0
        protected void cmdDeleteFile_Click(object sender, EventArgs e)
        {
            string fileName = (sender as LinkButton).CommandName;

            Wiki.RemoveFile(fileName);
            BindListFiles();
        }
Example #3
0
 public void Update(Wiki wiki, string id)
 {
     wiki.AddTime = DateTime.Now;
     wiki.Id      = id;
     WikiDao.Update(wiki);
     CHCache.Remove(WIKICACHE);
 }
        public ActionResult New(ArtistWikiViewModel artistWikiRequest)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Wiki artistWiki = new Wiki
                    {
                        Description = artistWikiRequest.Description,
                        BirthYear   = artistWikiRequest.BirthYear,
                        BirthMonth  = artistWikiRequest.BirthMonth,
                        BirthDay    = artistWikiRequest.BirthDay,
                        DebutYear   = artistWikiRequest.DebutYear
                    };

                    db.Wikis.Add(artistWiki);
                    Artist artist = new Artist
                    {
                        Name    = artistWikiRequest.Name,
                        Country = artistWikiRequest.Country,
                        Wiki    = artistWiki
                    };
                    db.Artists.Add(artist);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                return(View(artistWikiRequest));
            }
            catch
            {
                return(View(artistWikiRequest));
            }
        }
Example #5
0
        protected void OnPageEmpty(object sender, EventArgs e)
        {
            var pageName = PageNameUtil.Decode(WikiPage);

            wikiViewPage.Visible     = false;
            wikiEditPage.Visible     = false;
            wikiViewFile.Visible     = false;
            wikiEditFile.Visible     = false;
            pPageIsNotExists.Visible = true;

            if (!(Action.Equals(ActionOnPage.CategoryView) || Action.Equals(ActionOnPage.CategoryEdit)))
            {
                if (IsFile)
                {
                    txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiFileIsNotExists, true, false);
                }
                else
                {
                    if (Wiki.SearchPagesByName(pageName).Count > 0)
                    {
                        txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiPageIsNotExists, false, true);
                    }
                    else
                    {
                        txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiPageIsNotExists, false, false);
                    }
                }
            }

            _isEmptyPage = true;
            InitEditsLink();
            //WikiMaster.UpdateNavigationItems();
        }
Example #6
0
 private static PagesSource <Page> CategoryMembersSource(Wiki wiki)
 {
     return((from cm in wiki.Query.categorymembers()
             where cm.title == "Category:Query languages" &&
             cm.type == categorymemberstype.subcat
             select cm).Pages);
 }
Example #7
0
        private static void Random(Wiki wiki)
        {
            var result = from rp in wiki.Query.random()
                         select rp.title;

            Write(result);
        }
        public ActionResult Edit(int id, ArtistWikiViewModel artistViewRequest)
        {
            Artist artist = db.Artists.Find(id);
            Wiki   wiki   = db.Wikis.Find(artist.Wiki.WikiId);

            try
            {
                if (ModelState.IsValid)
                {
                    if (TryUpdateModel(artist) && TryUpdateModel(wiki))
                    {
                        artist.Name    = artistViewRequest.Name;
                        artist.Country = artistViewRequest.Country;

                        wiki.Description = artistViewRequest.Description;
                        wiki.BirthYear   = artistViewRequest.BirthYear;
                        wiki.BirthMonth  = artistViewRequest.BirthMonth;
                        wiki.BirthDay    = artistViewRequest.BirthDay;
                        wiki.DebutYear   = artistViewRequest.DebutYear;

                        db.SaveChanges();
                    }
                    return(RedirectToAction("Index"));
                }
                return(View(artistViewRequest));
            }
            catch (Exception)
            {
                return(View(artistViewRequest));
            }
        }
Example #9
0
        private static void Watch(Wiki wiki)
        {
            var token  = wiki.tokens(new[] { tokenstype.watch }).watchtoken;
            var result = wiki.watch(token, titles: new[] { "Test" }, unwatch: false);

            Console.WriteLine(result);
        }
Example #10
0
        private static void EmailUser(Wiki wiki)
        {
            var token  = wiki.tokens(new[] { tokenstype.email }).emailtoken;
            var result = wiki.emailuser("User:Svick", "Hello", "Mail from LinqToWiki", token);

            Console.WriteLine(result);
        }
Example #11
0
        private static void QueryPage(Wiki wiki)
        {
            var result = from qp in wiki.Query.querypage(querypagepage.Uncategorizedpages)
                         select qp;

            Write(result);
        }
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(json);
     Reddit   = reddit;
     WebAgent = webAgent;
     Wiki     = new Wiki(reddit, this, webAgent);
 }
Example #13
0
        protected string RenderPageContent()
        {
            Page page;

            if (_pageName == null)
            {
                _pageName = string.Empty;
            }

            if (Version > 0)
            {
                page = Wiki.GetPage(_pageName, Version);
            }
            else
            {
                page = Wiki.GetPage(_pageName);
            }

            if (page == null)
            {
                return(RenderEmptyPage());
            }

            RiseWikiPageLoaded(page);
            RisePublishVersionInfo(page);

            return(HtmlWikiUtil.WikiToHtml(page.PageName, page.Body, Page.ResolveUrl(Request.AppRelativeCurrentExecutionFilePath),
                                           Wiki.GetPagesAndFiles(page.Body), Page.ResolveUrl(ImageHandlerUrlFormat),
                                           TenantId, CanEditPage && Version == 0 ? ConvertType.Editable : ConvertType.NotEditable));
        }
Example #14
0
        private void BindRepeater()
        {
            var resultToShow = Wiki.GetFiles();

            UpdateHasFilesToDelete(resultToShow);

            HasFiles = resultToShow.Count > 0;

            if (HasFiles)
            {
                rptFilesList.DataSource = resultToShow;
                rptFilesList.DataBind();
            }
            else
            {
                var emptyScreenControl = new EmptyScreenControl
                {
                    ImgSrc   = WebImageSupplier.GetAbsoluteWebPath("wikilogo150.png", WikiManager.ModuleId),
                    Header   = WikiResource.EmptyScreenWikiFilesCaption,
                    Describe = WikiResource.EmptyScreenWikiFilesText,
                };

                if (CanUpload)
                {
                    emptyScreenControl.ButtonHTML = String.Format("<a class='link underline blue plus' href='javascript:ShowUploadFileBox();'>{0}</a>", WikiResource.menu_AddNewFile);
                }

                EmptyContent.Controls.Add(emptyScreenControl);
            }
        }
Example #15
0
        public bool IsWikipediaTitle(Wiki wiki)
        {
            const string methodKey   = "Wiki";
            bool?        cachedValue = caching.Get <bool?>(methodKey, NounPhrase.PhraseString);

            if (cachedValue != null)
            {
                return((bool)cachedValue);
            }

            bool retValue = false;
            var  result   = from s in wiki.Query.search("intitle:\"" + NounPhrase.PhraseString + "\"") select new { s.title };

            try
            {
                var list = result.ToList();
                retValue = list.Count > 0;
            }
            catch (XmlException)
            {
            }

            caching.Add(methodKey, NounPhrase.PhraseString, retValue);

            return(retValue);
        }
Example #16
0
        private static void Search(Wiki wiki)
        {
            var result = from s in wiki.Query.search("LINQ")
                         select new { s.title, snippet = s.snippet.Substring(0, 30) };

            Write(result);
        }
Example #17
0
        private static void TestRepositoriesEndPoint(SharpBucketV1 sharpBucket)
        {
            var    repositoriesEndPoint = sharpBucket.RepositoriesEndPoint(accountName, repository);
            var    tags       = repositoriesEndPoint.ListTags();
            var    branches   = repositoriesEndPoint.ListBranches();
            var    mainBranch = repositoriesEndPoint.GetMainBranch();
            var    sources    = repositoriesEndPoint.ListSources(mainBranch.name, null);
            var    content    = repositoriesEndPoint.GetSrcFile(mainBranch.name, sources.files[0].path);
            string WIKI_PAGE  = "";
            var    wiki       = repositoriesEndPoint.GetWiki(WIKI_PAGE);
            var    newPage    = new Wiki {
                data = "Hello to my new page"
            };
            var newWiki    = repositoriesEndPoint.PostWiki(newPage, "NewPage");
            var changeSet  = repositoriesEndPoint.ListChangeset();
            var change     = changeSet.changesets[4];
            var getChange  = repositoriesEndPoint.GetChangeset(change.node);
            var diffStats  = repositoriesEndPoint.GetChangesetDiffstat(change.node);
            var repoEvents = repositoriesEndPoint.ListEvents();
            var links      = repositoriesEndPoint.ListLinks();
            var newLink    = new Link {
                id = 100
            };
            var newLinkResponse = repositoriesEndPoint.PostLink(newLink);
            var link            = repositoriesEndPoint.GetLink(newLinkResponse.id);

            newLinkResponse.handler.name = "sfsdf";
            var updatedLink = repositoriesEndPoint.PutLink(newLinkResponse);

            repositoriesEndPoint.DeleteLink(updatedLink);
        }
Example #18
0
        private static void WatchlistRaw(Wiki wiki)
        {
            var result = from wr in wiki.Query.watchlistraw()
                         select null;

            Write(result);
        }
Example #19
0
        private static void EmptyCategoriesSlower(Wiki wiki)
        {
            var result = wiki.Query
                         .allpages()
                         .Where(p => p.ns == Namespace.Category)
                         .Pages
                         .Select(
                p =>
                new
            {
                p.info.title,
                p.categoryinfo,
                softRedirectCategory =
                    p.categories()
                    .Where(c => c.categories == "Category:Wikipedia soft redirected categories")
                    .Select(c => c.title)
                    .ToEnumerable()
            })
                         .ToEnumerable()
                         .Where(c => (c.categoryinfo == null || c.categoryinfo.size == 0) && !c.softRedirectCategory.Any())
                         .Select(c => c.title)
                         .Take(10);

            Write(result);
        }
Example #20
0
        public async Task PatchPage400TestAsync(string wikiURL, string pageURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var repo            = new PageRepositoryStoring(context, factory);
            var page_controller = new PageController(repo, p_logger);

            Wiki wiki = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            Page page;

            if (wiki != null)
            {
                page = await context.Page.Where(p => (p.WikiId == wiki.Id && p.Url == pageURL)).SingleOrDefaultAsync();
            }
            else
            {
                page = null;
            }
            //ACT
            var status = await page_controller.PatchAsync(wikiURL, pageURL, new ViewzApi.Models.Page());

            //ASSERT - status 400 (Bad Request)
            Assert.IsType <BadRequestObjectResult>(status);
        }
Example #21
0
        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(WikiPage) || IsFile)
                {
                    return;
                }
                var pageName = PageNameUtil.Decode(WikiPage);

                var page = Wiki.GetPage(pageName);
                CommunitySecurity.DemandPermissions(new WikiObjectsSecurityObject(page), Common.Constants.Action_RemovePage);

                foreach (var cat in Wiki.GetCategoriesRemovedWithPage(pageName))
                {
                    WikiNotifySource.Instance.GetSubscriptionProvider().UnSubscribe(Common.Constants.AddPageToCat, cat.CategoryName);
                }

                Wiki.RemoveCategories(pageName);

                WikiNotifySource.Instance.GetSubscriptionProvider().UnSubscribe(Common.Constants.EditPage, pageName);

                foreach (var comment in Wiki.GetComments(pageName))
                {
                    CommonControlsConfigurer.FCKUploadsRemoveForItem("wiki_comments", comment.Id.ToString());
                }
                Wiki.RemovePage(pageName);

                Response.RedirectLC("Default.aspx", this);
            }
            catch (Exception err)
            {
                WikiMaster.PrintInfoMessage(err.Message, InfoType.Alert);
            }
        }
        public async Task <IActionResult> PutWiki([FromRoute] int id, [FromBody] Wiki wiki)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != wiki.ID)
            {
                return(BadRequest());
            }

            _context.Entry(wiki).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WikiExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public IActionResult CreateWiki(int?wiki_id = null)
        {
            try
            {
                doctormembraincomContext db = new doctormembraincomContext();
                Wiki        w     = new Wiki();
                List <Wiki> wikis = db.Wiki.ToList();
                ViewBag.Wikis = wikis;
                if (wiki_id == null)
                {
                    w.Chapter = new List <Chapter>();
                }
                else
                {
                    w = db.Wiki
                        .Include(x => x.Chapter)
                        .Where(x => x.Id == wiki_id)
                        .FirstOrDefault();
                    w.Chapter = w.Chapter.OrderBy(x => x.Priority).ToList();
                }

                return(View("CreateWiki", w));
            }
            catch (Exception e)
            {
                return(NotFound(HttpStatusCode.NotFound));
            }
        }
Example #24
0
        public SaveResult Save(Guid userId, out string fileName)
        {
            fileName = string.Empty;
            if (!fuFile.HasFile)
            {
                return(SaveResult.FileEmpty);
            }

            var file = CurrentFile ?? new File {
                FileName = fuFile.FileName, UploadFileName = fuFile.FileName
            };

            file.FileSize = fuFile.FileBytes.Length;

            file = Wiki.CreateOrUpdateFile(file);

            try
            {
                FileContentSave(file.FileLocation, fuFile.FileBytes, WikiSection.Section, TenantId);
            }
            catch (TenantQuotaException)
            {
                Wiki.RemoveFile(file.FileName);
                return(SaveResult.FileSizeExceeded);
            }

            _fileInfo = file;

            RisePublishVersionInfo(file);
            fileName = file.FileName;

            return(SaveResult.Ok);
        }
        public ActionResult CreateWikiPost(Wiki model)
        {
            try
            {
                doctormembraincomContext db = new doctormembraincomContext();
                Wiki w = db.Wiki.Where(x => x.Id == model.Id).FirstOrDefault();
                if (w != null)
                {
                    bool ok;
                    w.Title = StringHelper.OnlyAlphanumeric(model.Title, false, true, "", new char[] { ' ', ',', '-', '\'', '"', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                    w.Intro = StringHelper.OnlyAlphanumeric(model.Intro, true, true, "br", new char[] { ' ', '.', ',', '-', '\'', '"', '*', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                }
                else
                {
                    w = new Wiki();
                    bool ok;
                    w.Title = StringHelper.OnlyAlphanumeric(model.Title, false, true, "", new char[] { ' ', ',', '-', '\'', '"', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                    w.Intro = StringHelper.OnlyAlphanumeric(model.Intro, true, true, "br", new char[] { ' ', '.', ',', '-', '\'', '"', '*', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                    db.Wiki.Add(w);
                }
                db.SaveChanges();

                return(RedirectToRoute("create_wiki", new { wiki_id = w.Id }));
            }
            catch (Exception e)
            {
                return(NotFound(HttpStatusCode.NotFound));
            }
        }
Example #26
0
        protected void cmdRevert_Click(object sender, EventArgs e)
        {
            if (CommunitySecurity.IsOutsider())
            {
                throw new SecurityException();
            }

            int ver;

            if (int.TryParse((sender as LinkButton).CommandName, out ver))
            {
                var page = Wiki.GetPage(PageNameUtil.Decode(WikiPage), ver);
                if (page != null)
                {
                    page.Date    = TenantUtil.DateTimeNow();
                    page.UserID  = SecurityContext.CurrentAccount.ID;
                    page.Version = Wiki.GetPageMaxVersion(page.PageName) + 1;

                    Wiki.SavePage(page);
                    Wiki.UpdateCategoriesByPageContent(page);

                    BindHistoryList();
                }
            }
        }
        public ActionResult RemoveChapterPost(int chapter_id)
        {
            try
            {
                doctormembraincomContext db = new doctormembraincomContext();
                Chapter c = db.Chapter.Where(x => x.Id == chapter_id).FirstOrDefault();
                if (c != null)
                {
                    Wiki w = db.Wiki
                             .Include(x => x.Chapter)
                             .Where(x => x.Id == c.WikiId)
                             .FirstOrDefault();
                    w.Chapter = w.Chapter.OrderBy(x => x.Priority).ToList();
                    foreach (Chapter ch in w.Chapter)
                    {
                        if (ch.Priority > c.Priority)
                        {
                            ch.Priority--;
                        }
                    }
                    db.Chapter.Remove(c);
                    db.SaveChanges();
                }

                return(RedirectToRoute("create_wiki", new { wiki_id = c.WikiId }));
            }
            catch (Exception e)
            {
                return(NotFound(HttpStatusCode.NotFound));
            }
        }
Example #28
0
        private static void Unblock(Wiki wiki)
        {
            var token  = wiki.tokens(new[] { tokenstype.unblock }).unblocktoken;
            var result = wiki.unblock(user: "******", token: token, reason: "I don't hate you anymore.");

            Console.WriteLine(result);
        }
        public ActionResult AddChapterPost(int wiki_id, string c_title, string c_text)
        {
            try
            {
                doctormembraincomContext db = new doctormembraincomContext();
                Wiki w = db.Wiki
                         .Include(x => x.Chapter)
                         .Where(x => x.Id == wiki_id)
                         .FirstOrDefault();
                if (w != null)
                {
                    bool    ok;
                    Chapter c = new Chapter();
                    c.Priority = w.Chapter.Count() + 1;
                    c.Title    = StringHelper.OnlyAlphanumeric(c_title, false, true, "", new char[] { ' ', ',', '-', '\'', '"', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                    c.Text     = StringHelper.OnlyAlphanumeric(c_text, true, true, "br", new char[] { ' ', '.', ',', '-', '\'', '"', '*', '&', '#', '(', ')', '\\', '?', '/', '<', '>' }, out ok);
                    w.Chapter.Add(c);
                    db.SaveChanges();
                }

                return(RedirectToRoute("create_wiki", new { wiki_id = w.Id }));
            }
            catch (Exception e)
            {
                return(NotFound(HttpStatusCode.NotFound));
            }
        }
Example #30
0
        private static void Run(string[] args)
        {
            Arguments arguments;
            try
            {
                arguments = Arguments.Parse(args);
            }
            catch (Exception e)
            {
                throw new ArgumentException(string.Format("Error parsing arguments: {0}", e.Message), e);
            }

            string urlString = arguments.Url;

            if (urlString == null)
                throw new ArgumentException("Url to API has to be specified.");

            if (!urlString.StartsWith("http"))
                urlString = "http://" + urlString;

            var url = new Uri(urlString, UriKind.Absolute);
            string baseUrl = url.GetLeftPart(UriPartial.Authority);
            string apiPath = url.AbsolutePath;

            if (apiPath == "/")
                apiPath = "/w/api.php";

            var wiki = new Wiki(baseUrl, apiPath, arguments.Namespace, arguments.PropsFile);
            wiki.AddAllModules();
            wiki.AddAllQueryModules();
            var result = wiki.Compile(arguments.OutputName, arguments.Directory);

            foreach (CompilerError error in result.Errors)
                Console.WriteLine(error);
        }
Example #31
0
        public async Task GetPageNoContentTestAsync(string wikiURL, string pageURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var repo            = new PageRepositoryStoring(context, factory);
            var page_controller = new PageController(repo, p_logger);

            Wiki wiki = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            Page page;

            if (wiki != null)
            {
                page = await context.Page.Where(p => (p.WikiId == wiki.Id && p.Url == pageURL)).SingleOrDefaultAsync();
            }
            else
            {
                page = null;
            }

            var status = await page_controller.GetAsync(wikiURL, pageURL, ViewzApi.Controllers.PageContent.NoContent);

            if (page != null)
            {
                Assert.IsType <OkObjectResult>(status);
            }
            else
            {
                Assert.IsType <NotFoundObjectResult>(status);
            }
        }
Example #32
0
        public void RestoreTo(WikiName name, WikiVersion version)
        {
            Wiki o = dbManager.GetWikiByVerslion(name, version);
            Wiki n = new Wiki();
            n.Name = o.Name;
            n.Content = o.Content;

            dbManager.WriteWiki(n);
        }
        public ActionResult Index()
        {
            //Creates a new Wiki object to query Wikipedia
            var wikipedia = new Wiki("Example");

            //This query pulls all images that begin with "Microsoft"
            var query = wikipedia.Query.allimages()
                        .Where(i => i.prefix == "Microsoft")
                        .Select(s => new WikiImage(s.url, s.height, s.width)).ToList();
            return View(query);
        }
Example #34
0
    protected void ContentButton_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Request.QueryString["id"]))
            return;

        wiki = Wiki.Load(new Guid(Request.QueryString["id"]));

        if (wiki == null)
            return;

        Response.Redirect(wiki.RelativeLink);
    }
Example #35
0
        static void Main(string[] args)
        {
            try
            {
                var wiki = new Wiki("Wiki.ASOIAF.DictSync", "zh.asoiaf.wikia.com", "/api.php");
                var allPagesources =
                    wiki.Query.allpages().Where(p => p.filterredir == allpagesfilterredir.nonredirects).Pages;
                var results =
                    allPagesources.Select(
                        p => PageResult.Create(p.info, p.langlinks().Where(l => l.lang == "en").ToEnumerable()))
                        .ToEnumerable();
                var dict = results.Select(result => new { Lang = result.Data.FirstOrDefault(), Result = result })
                    .Where(
                        item =>
                            {
                                if (item.Lang == null || string.IsNullOrEmpty(item.Lang.value))
                                {
                                    Log.Warn(string.Format("Noen {0}", item.Result.Info.title));
                                    return false;
                                }

                                return true;
                            })
                    .GroupBy(item => item.Lang.value)
                    .Select(
                        group =>
                            {
                                if (group.Count() > 1)
                                {
                                    Log.Warn(
                                        string.Format(
                                            "Duplicated item, en:{0}, ch:{1}",
                                            group.Key,
                                            string.Join(",", group.Select(item => item.Result.Info.title))));
                                }

                                return group.First();
                            })
                    .ToDictionary(item => item.Lang.value, item => item.Result.Info.title);
                var json = JsonConvert.SerializeObject(dict);
                using (var sw = new StreamWriter(@"..\..\..\..\dict\entry.json"))
                {
                    sw.Write(json);
                }
            }
            catch (Exception ex)
            {
                Log.Fatal("Error occurred", ex);
            }
        }
Example #36
0
    protected void CancelButton_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
            wiki = Wiki.Load(new Guid(Request.QueryString["id"]));

            if (wiki != null)
            {
                Session.Remove(wiki.ID.ToString());
                Response.Redirect(wiki.RelativeLink);
            }
        }

        Response.Redirect("~/Default.aspx");
    }
Example #37
0
        public void AddWikiTest()
        {
            Guid wiki_name = Guid.NewGuid();
            WikiName name = new WikiName(wiki_name.ToString());
            WikiContent content = new WikiContent("this is wiki content...");
            Wiki wiki = new Wiki();

            wiki.Name = name;
            wiki.Content = content;

            WikiManager wm = new WikiManager();
            wm.WriteWiki(wiki);
            Wiki dbWiki = wm.GetWiki(name, new WikiVersion(1));

            Assert.IsTrue(wm.GetWikiList(name).Count == 1);
            Assert.IsTrue(wiki.Version.Value == 1);
        }
Example #38
0
        public void GetLastVersionTest()
        {
            Int32 total = 100;
            String wikiName = Guid.NewGuid().ToString();
            WikiManager wm = new WikiManager();
            for (int i = 0; i < total; i++)
            {
                Wiki w = new Wiki();
                w.Name = new WikiName(wikiName);
                w.Content = new WikiContent(String.Format("{0}|{1}", wikiName, DateTime.Now.Ticks.ToString()));
                wm.WriteWiki(w);
            }

            WikiVersion latestWikiVersion = wm.GetLatestWikiVersion(new WikiName(wikiName));

            Assert.AreEqual(latestWikiVersion.Value, total);
        }
Example #39
0
        public void CreateWiki(Wiki wk,string username)
        {
            try
            {
                ApplicationUser usr = null;

                if ( wk!=null && CommonTools.isEmpty(username)==false)
                {

                    usr = CommonTools.usrmng.GetUser(username);
                    if (usr != null)
                    {
                        wk.Administrator = usr.Id;//.Clone();
                        //wk.AdministratorId = wk.Administrator.Id;

                     //  wk.Moderators = new List<WikiMods>();
                      //  WikiMods wm = new WikiMods();
                       // wm.Wiki = wk;
                       // wm.Moderator = usr.Id;
                        //wk.Moderators.Add(wm);
                        this.wrepo.CreateWiki(wk);

                        string wkrotfold = this.setmngr.WikiRootFolderName();
                        string wkpath;

                        //if (CommonTools.isEmpty(wkrotfold ))
                        //{
                        //    wkrotfold = "wikifiles";
                        //}
                        // wkpath = "~/" + AppDataDir + "/" + wkrotfold + "/" + wk.Name;
                        wkpath = FileSystemManager.GetWikiRootDataFolderRelativePath(wk.Name);
                        if (FileSystemManager.DirectoryExists(wkpath) == false)
                        {
                            FileSystemManager.CreateDirectory(wkpath);

                        }
                    }
                }
            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                //return null;
            }
        }
        public static string ToInfoMessage(Wiki tag)
        {
            try
            {
                StringBuilder builder = new StringBuilder();

                if (!string.IsNullOrWhiteSpace(tag.Name)) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Tag_Name, tag.Name));
                if (tag.Id != null) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Tag_Id, NetworkConverter.ToBase64UrlString(tag.Id)));

                if (builder.Length != 0) return builder.ToString().Remove(builder.Length - 2);
                else return null;
            }
            catch (Exception e)
            {
                throw new ArgumentException("ArgumentException", e);
            }
        }
Example #41
0
    private void BindWikiContent()
    {
        if (string.IsNullOrEmpty(Request.QueryString["id"]))
            return;

        wiki = string.IsNullOrEmpty(Request.QueryString["ischanged"]) || !Convert.ToBoolean(Request.QueryString["ischanged"]) ?
            Wiki.Load(new Guid(Request.QueryString["id"])) : (Wiki)Session[Request.QueryString["id"]];

        if (wiki == null)
            return;

        Page.Title = string.Format("Wiki - {0}", wiki.Title);
        TitleLabel.Text = wiki.Title;
        EditorLabel.Text = string.Format("Autor: {0}{1}", !string.IsNullOrEmpty(wiki.Editor) ? wiki.Editor : "ND",
            !string.IsNullOrEmpty(wiki.DepartmentArea) ? string.Format(" - {0}", wiki.DepartmentArea) : string.Empty);
        ContentLabel.Text = wiki.Content;
        EditButton.Visible = wiki.Editable || User.IsInRole("Administrator");
    }
        public void AddAModToNewWiki(Wiki wk ,string mod)
        {
            try
            {
                if ( wk !=null && CommonTools.isEmpty(mod)==false )
                {

                    if (wk.Moderators != null)
                    {
                        WikiMods wm = new WikiMods();
                        wm.Moderator = mod;
                        wm.Wiki = wk;
                        if ( wk.Moderators.FirstOrDefault(x=>x.Moderator==mod && x.Wiki.Name==wk.Name)==null)
                        {
                            wk.Moderators.Add(wm);
                        }

                    }
                    else
                    {
                        wk.Moderators = new List<WikiMods>();
                        WikiMods wm = new WikiMods();
                        wm.Moderator = mod;
                        wm.Wiki = wk;
                        if (wk.Moderators.FirstOrDefault(x => x.Moderator == mod && x.Wiki.Name == wk.Name) == null)
                        {
                            wk.Moderators.Add(wm);
                        }

                    }

                }

            }
            catch (ValidationException ex) { CommonTools.ValidationErrorReporting(ex); }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                //return null;
            }
        }
Example #43
0
    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(Request.QueryString["id"]))
                return;

            wiki = Wiki.Load(new Guid(Request.QueryString["id"]));

            if (wiki == null)
                return;

            wiki.Delete();
            wiki.Save();

        }
        finally
        {
            Response.Redirect(Utils.RelativeWebRoot);
        }
    }
Example #44
0
        public void GetWikisTest()
        {
            Int32 count = 10;
            WikiManager wm = new WikiManager();
            Guid wiki_name = Guid.NewGuid();
            WikiName name = new WikiName(wiki_name.ToString());

            for (int i = 0; i < count; i++)
            {
                WikiContent content = new WikiContent(string.Format("this is wiki content...{0}", i));

                Wiki wiki = new Wiki();
                wiki.Name = name;
                wiki.Content = content;

                wm.WriteWiki(wiki);
            }

            List<Wiki> list = wm.GetWikiList(name);
            Assert.IsTrue(count == list.Count);
        }
Example #45
0
        public MWFS(string serverUrl, string serverUser, string serverPassword)
        {
            wiki = new Wiki("http://"+serverUrl);
            if (!String.IsNullOrEmpty(serverUser))
            {
                wiki.Login(serverUser, serverPassword);
            }
            //Init directories
            TopDirectory = new Dictionary<string, string>();
            TopDirectory["Categories"] = "Categories";
            TopDirectory["Main namespace"] = "Main namespace";
            TopDirectory["Templates"] = "Templates";
            TopDirectory["Forms"] = "Forms";
            TopDirectory["Properties"] = "Properties";

            DirCache = new Dictionary<string, Dictionary<string, int>>();
            DirCache["Categories"] = new Dictionary<string, int>();
            DirCache["Main namespace"] = new Dictionary<string, int>();
            DirCache["Templates"] = new Dictionary<string, int>();
            DirCache["Forms"] = new Dictionary<string, int>();
            DirCache["Properties"] = new Dictionary<string, int>();
        }
        public Boolean UserHasAccessToWiki(ApplicationUser user, Wiki wk, Boolean isDelete)
        {
            try
            {
                Boolean ap = false;
                if (user != null && UserExists(user.UserName.ToString()) == true)
                {
                    if (isDelete == true)
                    {
                        IdentityRole role = this.GetRole(AdminRoles);
                        if (role != null)
                        {
                            if (role.Users.First(x => x.UserId == user.Id) != null && wk.Administrator== user.Id)
                            {
                                ap = true;
                            }

                        }
                    }
                    else
                    {
                        if (wk.Administrator == user.Id)
                        {
                            ap = true;
                        }
                    }
                }

                return ap;

            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                return false;
            }
        }
        public static void LogIn(Wiki wiki, string userName, string password, Action onSuccess,
            Action<string> onError)
        {
            StringDictionary query = new StringDictionary
            {
                { "action", "login" },
                { "lgname", userName },
                { "lgpassword", password },
            };
            PostApi(wiki, query, delegate(XmlDocument doc)
            {
                XmlNode login = doc.GetElementsByTagName("login")[0];
                if (login.Attributes["result"].Value != "NeedToken")
                {
                    onError(Localization.GetString("MorebitsDotNet_LoginFailure", login.Attributes["result"].Value));
                    return;
                }
                LoginSessions[wiki].SessionID = login.Attributes["sessionid"].Value;
                LoginSessions[wiki].CookiePrefix = login.Attributes["cookieprefix"].Value;

                StringDictionary loginQuery = new StringDictionary
                {
                    { "action", "login" },
                    { "lgname", userName },
                    { "lgpassword", password },
                    { "lgtoken", login.Attributes["token"].Value }
                };
                PostApi(wiki, loginQuery, delegate(XmlDocument innerDoc)
                {
                    XmlNode innerLogin = innerDoc.GetElementsByTagName("login")[0];
                    LoginSessions[wiki].UserName = innerLogin.Attributes["lgusername"].Value;
                    LoginSessions[wiki].UserID = innerLogin.Attributes["lguserid"].Value;
                    LoginSessions[wiki].LoggedIn = true;
                    onSuccess();
                }, onError, true, false);
            }, onError);
        }
        public void Test_OutoposConverter_Wiki()
        {
            Wiki tag1 = new Wiki("oooo", new byte[32]);
            Wiki tag2;

            var stringTagAndOption = OutoposConverter.ToWikiString(tag1);
            tag2 = OutoposConverter.FromWikiString(stringTagAndOption);

            Assert.AreEqual(tag1, tag2, "OutoposConverter #2");
        }
        public static string ToWikiString(Wiki tag)
        {
            if (tag.Name == null || tag.Id == null) return null;

            try
            {
                return tag.Name + " - " + NetworkConverter.ToBase64UrlString(tag.Id);
            }
            catch (Exception e)
            {
                throw new ArgumentException("ArgumentException", e);
            }
        }
        public void EditWikiBasicInfo(Wiki wk,string wikiname)
        {
            try
            {
                if (wk != null && CommonTools.isEmpty(wikiname)==false)
                {
                    //if (wk.Name == wikiname)
                    {

                        Wiki wk2 = this.GetWiki(wikiname);
                        wk.Administrator = wk2.Administrator;

                        // db.Entry(wk).State = EntityState.Modified;
                        this.MarkWikiAsUpdated(wk);
                        db.Entry(this.GetWiki(wikiname)).CurrentValues.SetValues(wk);
                        db.SaveChanges();

                    }
                }
            }
            catch (ValidationException ex) { CommonTools.ValidationErrorReporting(ex); }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                //return null;
            }
        }
        public void CreateWiki(Wiki wk)
        {
            try
            {
                if ( wk!=null && this.WikiExists(wk.Name)==false)
                {
                    wk.UpdatedAt = DateTime.Now;
                     if (  CommonTools.isEmpty(wk.WikiTitle))
                    {
                        wk.WikiTitle = wk.Name;
                    }
                   // this.AddAModToNewWikiWithoutSave(wk, wk.Administrator);
                    this.db.Wikis.Add(wk);
                   //this.db.Configuration.ValidateOnSaveEnabled = false;
                    this.db.SaveChanges();

                }
            }
            catch (ValidationException ex){  CommonTools.ValidationErrorReporting(ex);        }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                //return null;
            }
        }
Example #52
0
 private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
 {
     base.Init(json);
     Reddit = reddit;
     WebAgent = webAgent;
     Wiki = new Wiki(reddit, this, webAgent);
 }
Example #53
0
        public Wiki ExportToModel()
        {
            try
            {
                Wiki ap = new Wiki();
                    //ApplicationUser user = CommonTools.usrmng.GetUserbyID(md.Administrator);

                      //  ap.id = this.id;

                        ap.Files = this.Files;
                        ap.Categories = Categories;
                        ap.Content = Content;
                        ap.Description = Description;
                        ap.Name = Name;
                        ap.Titles = Titles;
                        ap.UpdatedAt = UpdatedAt;
                        ap.WikiTitle = WikiTitle;
                if (Administrator != null)
                {
                    ap.Administrator = Administrator.Id;
                }
                if ( Files==null)
                {
                    ap.Files = new List<WikiFile>();
                }
                 if ( Categories== null)
                {
                    ap.Categories = new List<WikiCategory>();
                }
                        if (Moderators != null)
                        {
                            //List<string> mods = new List<string>();
                    ap.Moderators = new List<WikiMods>();

                            foreach (var m in this.Moderators)
                            {

                        //mods.Add(m.Id);
                        WikiMods wm = new WikiMods();
                        wm.Wiki = ap;
                        wm.Moderator = m.Id;
                        ap.Moderators.Add(wm);

                            }

                        }

                return ap;

            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                return null;

            }
        }
 public SinglePropModuleGenerator(Wiki wiki)
     : base(wiki)
 {
 }
        public void Test_ConnectionManager()
        {
            for (int i = 0; i < 4; i++)
            {
                TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 60000));
                listener.Start();
                var listenerAcceptSocket = listener.BeginAcceptSocket(null, null);

                TcpClient client = new TcpClient();
                client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 60000));

                var server = listener.EndAcceptSocket(listenerAcceptSocket);
                listener.Stop();

                var tcpClient = new BaseConnection(new SocketCap(client.Client), null, Test_Library_Net_Outopos.MaxReceiveCount, _bufferManager);
                var tcpServer = new BaseConnection(new SocketCap(server), null, Test_Library_Net_Outopos.MaxReceiveCount, _bufferManager);

                List<ConnectionManager> connectionManagers = new List<ConnectionManager>();

                {
                    ConnectionManager serverConnectionManager;
                    ConnectionManager clientConnectionManager;

                    Node serverNode = null;
                    Node clientNode = null;

                    byte[] serverSessionId = null;
                    byte[] clientSessionId = null;

                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var uris = new string[] { "net.tcp://localhost:9000", "net.tcp://localhost:9001", "net.tcp://localhost:9002" };

                        serverNode = new Node(id, uris);
                    }

                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var uris = new string[] { "net.tcp://localhost:9000", "net.tcp://localhost:9001", "net.tcp://localhost:9002" };

                        clientNode = new Node(id, uris);
                    }

                    {
                        serverSessionId = new byte[32];
                        _random.NextBytes(serverSessionId);
                    }

                    {
                        clientSessionId = new byte[32];
                        _random.NextBytes(clientSessionId);
                    }

                    serverConnectionManager = new ConnectionManager(tcpServer, serverSessionId, serverNode, ConnectDirection.In, _bufferManager);
                    clientConnectionManager = new ConnectionManager(tcpClient, clientSessionId, clientNode, ConnectDirection.Out, _bufferManager);

                    Thread serverThread = new Thread(new ThreadStart(() =>
                    {
                        serverConnectionManager.Connect();
                    }));

                    Thread clientThread = new Thread(new ThreadStart(() =>
                    {
                        clientConnectionManager.Connect();
                    }));

                    serverThread.Start();
                    clientThread.Start();

                    serverThread.Join();
                    clientThread.Join();

                    Assert.IsTrue(CollectionUtilities.Equals(serverConnectionManager.SesstionId, clientSessionId), "ConnectionManager SessionId #1");
                    Assert.IsTrue(CollectionUtilities.Equals(clientConnectionManager.SesstionId, serverSessionId), "ConnectionManager SessionId #2");

                    Assert.AreEqual(serverConnectionManager.Node, clientNode, "ConnectionManager Node #1");
                    Assert.AreEqual(clientConnectionManager.Node, serverNode, "ConnectionManager Node #2");

                    connectionManagers.Add(serverConnectionManager);
                    connectionManagers.Add(clientConnectionManager);
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullNodesEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullNodesEvent += (object sender, PullNodesEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    List<Node> nodes = new List<Node>();

                    for (int j = 0; j < 32; j++)
                    {
                        Node node = null;

                        {
                            var id = new byte[32];
                            _random.NextBytes(id);
                            var uris = new string[] { "net.tcp://localhost:9000", "net.tcp://localhost:9001", "net.tcp://localhost:9002" };

                            node = new Node(id, uris);
                        }

                        nodes.Add(node);
                    }

                    senderConnection.PushNodes(nodes);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(nodes, item.Nodes), "ConnectionManager #1");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullBlocksLinkEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullBlocksLinkEvent += (object sender, PullBlocksLinkEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var keys = new List<Key>();

                    for (int j = 0; j < 32; j++)
                    {
                        Key key = null;

                        {
                            var id = new byte[32];
                            _random.NextBytes(id);

                            key = new Key(id, HashAlgorithm.Sha256);
                        }

                        keys.Add(key);
                    }

                    senderConnection.PushBlocksLink(keys);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(keys, item.Keys), "ConnectionManager #2");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullBlocksRequestEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullBlocksRequestEvent += (object sender, PullBlocksRequestEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var keys = new List<Key>();

                    for (int j = 0; j < 32; j++)
                    {
                        Key key = null;

                        {
                            var id = new byte[32];
                            _random.NextBytes(id);

                            key = new Key(id, HashAlgorithm.Sha256);
                        }

                        keys.Add(key);
                    }

                    senderConnection.PushBlocksRequest(keys);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(keys, item.Keys), "ConnectionManager #3");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullBlockEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullBlockEvent += (object sender, PullBlockEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var buffer = _bufferManager.TakeBuffer(1024 * 1024 * 8);
                    var key = new Key(Sha256.ComputeHash(buffer), HashAlgorithm.Sha256);

                    senderConnection.PushBlock(key, new ArraySegment<byte>(buffer, 0, 1024 * 1024 * 4));

                    var item = queue.Dequeue();
                    Assert.AreEqual(key, item.Key, "ConnectionManager #4.1");
                    Assert.IsTrue(CollectionUtilities.Equals(buffer, 0, item.Value.Array, item.Value.Offset, 1024 * 1024 * 4), "ConnectionManager #4.2");

                    _bufferManager.ReturnBuffer(buffer);
                    _bufferManager.ReturnBuffer(item.Value.Array);
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullBroadcastMetadatasRequestEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullBroadcastMetadatasRequestEvent += (object sender, PullBroadcastMetadatasRequestEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.EcDsaP521_Sha256);

                    var signatures = new SignatureCollection();

                    for (int j = 0; j < 32; j++)
                    {
                        signatures.Add(digitalSignature.ToString());
                    }

                    senderConnection.PushBroadcastMetadatasRequest(signatures);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(signatures, item.Signatures), "ConnectionManager #5.1");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullBroadcastMetadatasEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullBroadcastMetadatasEvent += (object sender, PullBroadcastMetadatasEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.EcDsaP521_Sha256);

                    var metadatas1 = new List<ProfileMetadata>();

                    for (int j = 0; j < 4; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);
                        var metadata = new ProfileMetadata(DateTime.UtcNow, key, digitalSignature);

                        metadatas1.Add(metadata);
                    }

                    senderConnection.PushBroadcastMetadatas(metadatas1);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(metadatas1, item.ProfileMetadatas), "ConnectionManager #6.1");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullUnicastMetadatasRequestEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullUnicastMetadatasRequestEvent += (object sender, PullUnicastMetadatasRequestEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.EcDsaP521_Sha256);

                    var signatures = new SignatureCollection();

                    for (int j = 0; j < 32; j++)
                    {
                        signatures.Add(digitalSignature.ToString());
                    }

                    senderConnection.PushUnicastMetadatasRequest(signatures);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(signatures, item.Signatures), "ConnectionManager #7.1");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullUnicastMetadatasEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullUnicastMetadatasEvent += (object sender, PullUnicastMetadatasEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.EcDsaP521_Sha256);

                    var metadatas1 = new List<SignatureMessageMetadata>();

                    for (int j = 0; j < 4; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);
                        var miner = new Miner(CashAlgorithm.Version1, -1, TimeSpan.Zero);
                        var metadata = new SignatureMessageMetadata(digitalSignature.ToString(), DateTime.UtcNow, key, miner, digitalSignature);

                        metadatas1.Add(metadata);
                    }

                    senderConnection.PushUnicastMetadatas(metadatas1);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(metadatas1, item.SignatureMessageMetadatas), "ConnectionManager #8.1");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullMulticastMetadatasRequestEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullMulticastMetadatasRequestEvent += (object sender, PullMulticastMetadatasRequestEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var wikis = new WikiCollection();
                    var chats = new ChatCollection();

                    for (int j = 0; j < 32; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);

                        wikis.Add(new Wiki(RandomString.GetValue(256), id));
                    }

                    for (int j = 0; j < 32; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);

                        chats.Add(new Chat(RandomString.GetValue(256), id));
                    }

                    senderConnection.PushMulticastMetadatasRequest(wikis, chats);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(wikis, item.Wikis), "ConnectionManager #9.1");
                    Assert.IsTrue(CollectionUtilities.Equals(chats, item.Chats), "ConnectionManager #9.2");
                }

                connectionManagers.Randomize();

                {
                    var queue = new WaitQueue<PullMulticastMetadatasEventArgs>();

                    var receiverConnection = connectionManagers[0];
                    var senderConnection = connectionManagers[1];

                    receiverConnection.PullMulticastMetadatasEvent += (object sender, PullMulticastMetadatasEventArgs e) =>
                    {
                        queue.Enqueue(e);
                    };

                    var digitalSignature = new DigitalSignature("123", DigitalSignatureAlgorithm.EcDsaP521_Sha256);

                    var metadatas1 = new List<WikiDocumentMetadata>();
                    var metadatas2 = new List<ChatTopicMetadata>();
                    var metadatas3 = new List<ChatMessageMetadata>();

                    for (int j = 0; j < 4; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);
                        var tag = new Wiki("oooo", new byte[32]);
                        var miner = new Miner(CashAlgorithm.Version1, -1, TimeSpan.Zero);
                        var metadata = new WikiDocumentMetadata(tag, DateTime.UtcNow, key, miner, digitalSignature);

                        metadatas1.Add(metadata);
                    }

                    for (int j = 0; j < 4; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);
                        var tag = new Chat("oooo", new byte[32]);
                        var miner = new Miner(CashAlgorithm.Version1, -1, TimeSpan.Zero);
                        var metadata = new ChatTopicMetadata(tag, DateTime.UtcNow, key, miner, digitalSignature);

                        metadatas2.Add(metadata);
                    }

                    for (int j = 0; j < 4; j++)
                    {
                        var id = new byte[32];
                        _random.NextBytes(id);
                        var key = new Key(id, HashAlgorithm.Sha256);
                        var tag = new Chat("oooo", new byte[32]);
                        var miner = new Miner(CashAlgorithm.Version1, -1, TimeSpan.Zero);
                        var metadata = new ChatMessageMetadata(tag, DateTime.UtcNow, key, miner, digitalSignature);

                        metadatas3.Add(metadata);
                    }

                    senderConnection.PushMulticastMetadatas(metadatas1, metadatas2, metadatas3);

                    var item = queue.Dequeue();
                    Assert.IsTrue(CollectionUtilities.Equals(metadatas1, item.WikiDocumentMetadatas), "ConnectionManager #10.1");
                    Assert.IsTrue(CollectionUtilities.Equals(metadatas2, item.ChatTopicMetadatas), "ConnectionManager #10.2");
                    Assert.IsTrue(CollectionUtilities.Equals(metadatas3, item.ChatMessageMetadatas), "ConnectionManager #10.3");
                }

                foreach (var connectionManager in connectionManagers)
                {
                    connectionManager.Dispose();
                }

                client.Close();
                server.Close();
            }
        }
 public SingleQueryModuleGenerator(Wiki wiki)
     : base(wiki)
 {
 }
Example #57
0
        public void ImportFromModel(Wiki md)
        {
            try
            {
                if ( md !=null && CommonTools.isEmpty(md.Administrator)==false)
                {
                    ApplicationUser user = CommonTools.usrmng.GetUserbyID(md.Administrator);
                    if (user != null)
                    {
                       // this.id = md.id;
                        this.Files = md.Files;
                        this.Categories = md.Categories;
                        this.Content = md.Content;
                        this.Description = md.Description;
                        this.Name = md.Name;
                        this.Titles = md.Titles;
                        this.UpdatedAt = md.UpdatedAt;
                        this.WikiTitle = md.WikiTitle;
                        this.Administrator = user;
                        if (md.Moderators != null)
                        {
                            List<ApplicationUser> mods = new List<ApplicationUser>();

                            foreach(var m in md.Moderators)
                            {
                                ApplicationUser ms = CommonTools.usrmng.GetUserbyID(m.Moderator);
                                 if ( ms !=null)
                                {
                                    mods.Add(ms);

                                }
                            }
                            this.Moderators = mods;

                        }

                    }
                }
            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);

            }
        }
 void HandleOnLink(object sender, Wiki.LinkEventArgs e)
 {
     if (e.Href.Contains("://"))
     {
         e.Target = Wiki.LinkEventArgs.TargetEnum.External;
     }
     else
     {
         e.Target = Wiki.LinkEventArgs.TargetEnum.Internal;
         e.Href = "wiki://" + e.Href;
     }
 }
 public ModuleGenerator(Wiki wiki)
     : base(wiki)
 {
 }
        //public void MarkWikiAsUpdated(string wikiname)
        //{
        //    try
        //    {
        //        if ( this.WikiExists(wikiname)==true)
        //        {
        //            Wiki wk = this.GetWiki(wikiname);
        //            wk.UpdatedAt = DateTime.Now;
        //         db.Entry(this.GetWiki(wikiname)).CurrentValues.SetValues(wk);
        //            db.Entry(wk).State = EntityState.Modified;
        //            this.db.SaveChanges();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        CommonTools.ErrorReporting(ex);
        //    }
        //}
        public void MarkWikiAsUpdated(Wiki wk)
        {
            try
            {

                if (wk != null)
                {
                    wk.UpdatedAt = DateTime.Now;
                    db.Entry(this.GetWiki(wk.Name)).CurrentValues.SetValues(wk);
                   // db.Entry(wk).State = EntityState.Modified;
                 //  this.db.SaveChanges();
                }

            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
            }
        }