Esempio n. 1
0
        // =============================================
        // Library Syncing Functions
        // =============================================
        public IEnumerable<CacheModel> PushToServer(ContentModel[] results)
        {
            var service = InitializeClient();

            var updates = new List<CacheModel>();

            const int batchSize = 50;
            var counter = 0;

            do
            {
                var cache = service.PushMediaInformation(_serverKey, results.Skip(counter).Take(batchSize).ToArray());

                updates.AddRange(cache);

                counter += batchSize;

            #if DEBUG
                System.Console.WriteLine("{0}%", counter / results.Length);
                foreach (var c in cache)
                {
                    System.Console.WriteLine("{0}==={1}", c.ServerMediaId, c.Hash);
                }
            #endif

            } while (counter < results.Count());

            //#if DEBUG
            //            System.Console.WriteLine("Completed Uploading");
            //#endif

            return updates;
        }
Esempio n. 2
0
 private void GoToSubmodule(ContentModel x)
 {
     var nameAndSlug = x.GitUrl.Substring(x.GitUrl.IndexOf("/repos/", System.StringComparison.Ordinal) + 7);
     var repoId = new RepositoryIdentifier(nameAndSlug.Substring(0, nameAndSlug.IndexOf("/git", System.StringComparison.Ordinal)));
     var sha = x.GitUrl.Substring(x.GitUrl.LastIndexOf("/", System.StringComparison.Ordinal) + 1);
     ShowViewModel<SourceTreeViewModel>(new NavObject {Username = repoId.Owner, Repository = repoId.Name, Branch = sha});
 }
Esempio n. 3
0
 public ActionResult Upload(ContentModel model)
 {
     AddRecordContentCommand command = new AddRecordContentCommand
     {
         //RecordId = (Guid) Session["RecordId"],
         DataType = (DataTypes)model.SelectedList[0],
         DescriptionFile = null,
         //ContentFile = new byte[model.ContentFile.ContentLength]
     };
     model.ContentFile.InputStream.Read(command.ContentFile, 0, model.ContentFile.ContentLength);
     Bus.Send(command);
     return View();
 }
Esempio n. 4
0
        private Element CreateElement(ContentModel x)
        {
            if (x.Type.Equals("dir", StringComparison.OrdinalIgnoreCase))
            {
                return new StyledStringElement(x.Name, () => ViewModel.GoToSourceTreeCommand.Execute(x), Images.Folder);
            }
            if (x.Type.Equals("file", StringComparison.OrdinalIgnoreCase))
            {
                //If there's a size, it's a file
                if (x.Size != null)
                {
                    return new StyledStringElement(x.Name, () => ViewModel.GoToSourceCommand.Execute(x), Images.File);
                }

                //If there is no size, it's most likey a submodule
                return new StyledStringElement(x.Name, () => ViewModel.GoToSubmoduleCommand.Execute(x), Images.Repo);
            }

            return new StyledStringElement(x.Name) { Image = Images.File };
        }
Esempio n. 5
0
        public ActionResult Upload()
        {
            ContentModel model = new ContentModel
            {
                DataType = new ListViewModel[2],
                SelectedList = new int[0],
            };

            model.DataType[0] = new ListViewModel
            {
                Id = (int) DataTypes.Doc,
                Title = "DOC"
            };

            model.DataType[1] = new ListViewModel
            {
                Id = (int) DataTypes.Pdf,
                Title = "PDF"
            };

            return View(model);
        }
 public override ActionResult Index(ContentModel model)
 {
     return(base.Index(model));
 }
Esempio n. 7
0
 public override ActionResult Index(ContentModel model)
 {
     return(View(uFPC.IO.uFPCio.FindView(Current.Services.FileService.GetTemplate(model.Content.GetTemplateAlias())).Replace(System.AppDomain.CurrentDomain.BaseDirectory, "~\\")));
 }
        /// <summary>
        /// This method is used to update category content
        /// </summary>
        /// <param name="content"></param>
        public void UpdateCategoryContent(ContentModel content)
        {
            IContentOperationBL catBL = new CategoryContentOperationsBL();

            catBL.UpdateCategoryContent(content);
        }
Esempio n. 9
0
        internal XmlSchemaElement CreateXsdElement()
        {
            XmlSchemaElement el = new XmlSchemaElement();

            SetLineInfo(el);
            el.Name = Name;

            XmlSchemaComplexType ct = new XmlSchemaComplexType();

            el.SchemaType = ct;
            if (Attributes != null)
            {
                SetLineInfo(ct);
                foreach (DTDAttributeDefinition a in
                         Attributes.Definitions)
                {
                    ct.Attributes.Add(a.CreateXsdAttribute());
                }
            }
            if (IsEmpty)
            {
                ;                 // nothing to do
            }
            else if (IsAny)
            {
                XmlSchemaAny any = new XmlSchemaAny();
                any.MinOccurs       = 0;
                any.MaxOccursString = "unbounded";
                ct.Particle         = any;
            }
            else
            {
                if (IsMixedContent)
                {
                    ct.IsMixed = true;
                }
                ct.Particle = ContentModel.CreateXsdParticle();
            }

            /*
             * if (IsEmpty) {
             *      el.SchemaType = new XmlSchemaComplexType ();
             *      SetLineInfo (el.SchemaType);
             * }
             * else if (IsAny)
             *      el.SchemaTypeName = new XmlQualifiedName (
             *              "anyType", XmlSchema.Namespace);
             * else {
             *      XmlSchemaComplexType ct = new XmlSchemaComplexType ();
             *      SetLineInfo (ct);
             *      if (Attributes != null)
             *              foreach (DTDAttributeDefinition a in
             *                      Attributes.Definitions)
             *                      ct.Attributes.Add (a.CreateXsdAttribute ());
             *      if (IsMixedContent)
             *              ct.IsMixed = true;
             *      ct.Particle = ContentModel.CreateXsdParticle ();
             *      el.SchemaType = ct;
             * }
             */
            return(el);
        }
Esempio n. 10
0
        public ContentModel ResolveContent(IPublishedElement content, Dictionary <string, object>?options = null)
        {
            try
            {
                if (content == null)
                {
                    throw new ArgumentNullException(nameof(content));
                }

                var contentModel = new ContentModel
                {
                    System = new SystemModel
                    {
                        Id          = content.Key,
                        ContentType = content.ContentType.Alias,
                        Type        = content.ContentType.ItemType.ToString()
                    }
                };

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


                if (content is IPublishedContent publishedContent)
                {
                    contentModel.System.CreatedAt  = publishedContent.CreateDate;
                    contentModel.System.EditedAt   = publishedContent.UpdateDate;
                    contentModel.System.Locale     = _variationContextAccessor.VariationContext.Culture;
                    contentModel.System.Name       = publishedContent.Name;
                    contentModel.System.UrlSegment = publishedContent.UrlSegment;

                    if (options != null &&
                        options.ContainsKey("addUrl") &&
                        bool.TryParse(options["addUrl"].ToString(), out var addUrl) &&
                        addUrl)
                    {
                        contentModel.System.Url = publishedContent.Url(mode: UrlMode.Absolute);
                    }
                }

                foreach (var property in content.Properties)
                {
                    var converter =
                        _converters.FirstOrDefault(x => x.EditorAlias.Equals(property.PropertyType.EditorAlias));
                    if (converter != null)
                    {
                        var prop = property.Value(_publishedValueFallback);

                        if (prop == null)
                        {
                            continue;
                        }


                        prop = converter.Convert(prop, options?.ToDictionary(x => x.Key, x => x.Value));

                        if (prop != null)
                        {
                            dict.Add(property.Alias, prop);
                        }
                    }
                    else
                    {
                        dict.Add(
                            property.Alias,
                            $"No converter implemented for editor: {property.PropertyType.EditorAlias}");
                    }
                }

                contentModel.Fields = dict;
                return(contentModel);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An exceptional exception happened, see the inner exception for details");
                throw;
            }
        }
 public ActionResult Index(ContentModel model)
 {
     return(View("/views/frontpage.cshtml", model.Content));
 }
Esempio n. 12
0
        /// <summary>
        /// Scans all the individual episodes from a tv show in plex library
        /// </summary>
        /// <param name="id"></param>
        /// <param name="showTitle"></param>
        /// <param name="showSortTitle"></param>
        /// <param name="showRemoteSourceId"></param>
        /// <returns></returns>
        public IEnumerable<ContentModel> ScanEpisodes(int id, string showTitle, string showSortTitle, string showRemoteSourceId, string libraryName)
        {
            var results = new List<ContentModel>();

            var xml = XDocument.Load(string.Format("http://{0}/library/metadata/{1}/allLeaves", _plexServerAddress, id));

            foreach (var node in xml.Descendants("Video"))
            {
                var content = new ContentModel()
                {
                    VideoType = VideoType.TvShowEpisode,
                    Title = ReadAttribute(node, "title"),
                    Season = Convert.ToInt32(ReadNumberAttribute(node, "parentIndex")),
                    Episode = Convert.ToInt32(ReadNumberAttribute(node, "index")),
                    ParentId = id,
                    ParentRemoteSourceId = showRemoteSourceId,
                    ParentTitle = showTitle,
                    ParentSortTitle = showSortTitle,
                    LibraryName = libraryName
                };

                var media = new List<MediaModel>();

                // add a record for each file
                foreach (var mediaNode in node.Descendants("Media"))
                {
                    var mediaModel = new MediaModel()
                    {
                        VideoId = Convert.ToInt32(ReadNumberAttribute(node, "ratingKey")),
                        MediaId = Convert.ToInt32(ReadNumberAttribute(mediaNode, "id")),
                        AspectRatio = (decimal)ReadNumberAttribute(mediaNode, "aspectRatio"),
                        Resolution = ReadAttribute(mediaNode, "videoResolution"),
                        DateAdded = ReadDateAttribute(node, "addedAt")
                    };

                    var part = mediaNode.Descendants("Part").FirstOrDefault();
                    if (part != null)
                    {
                        mediaModel.Size = ReadNumberAttribute(part, "size");
                        mediaModel.FilePath = ReadAttribute(part, "file");
                    }

                    media.Add(mediaModel);
                }

                content.MediaModels = media.ToArray();
                content.ModelHash = CalculateComparisonHash(content);

                results.Add(content);
            }

            return results;
        }
Esempio n. 13
0
 internal void SetModel(ContentModel model)
 {
     base.Model = model;
 }
Esempio n. 14
0
 public new async Task <ActionResult> Index(ContentModel model)
 {
     return(await Task.FromResult(base.Index(model)));
 }
Esempio n. 15
0
 public ActionResult Index(ContentModel model, int page)
 {
     return(base.Index(model));
 }
        public async override Task <ActionResult> Index(ContentModel contentModel)
        {
            if (contentModel is null)
            {
                throw new ArgumentNullException(nameof(contentModel));
            }

            var model = new EditKnockoutMatchViewModel(contentModel.Content, Services?.UserService)
            {
                Match = new Match
                {
                    MatchType     = MatchType.KnockoutMatch,
                    MatchLocation = new MatchLocation()
                }
            };

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Team == null)
                {
                    return(new HttpNotFoundResult());
                }

                var possibleSeasons = _createMatchSeasonSelector.SelectPossibleSeasons(model.Team.Seasons, model.Match.MatchType);

                if (possibleSeasons.Count == 0)
                {
                    return(new HttpNotFoundResult());
                }

                if (possibleSeasons.Count == 1)
                {
                    model.Match.Season = possibleSeasons.First();
                }

                model.PossibleSeasons = _editMatchHelper.PossibleSeasonsAsListItems(possibleSeasons);

                await _editMatchHelper.ConfigureModelPossibleTeams(model, possibleSeasons).ConfigureAwait(false);

                model.HomeTeamId        = model.Team.TeamId;
                model.MatchLocationId   = model.Team.MatchLocations.FirstOrDefault()?.MatchLocationId;
                model.MatchLocationName = model.Team.MatchLocations.FirstOrDefault()?.NameAndLocalityOrTownIfDifferent();

                if (model.PossibleHomeTeams.Count > 1)
                {
                    model.AwayTeamId = new Guid(model.PossibleHomeTeams[1].Value);
                }
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Match.Season = model.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, true).ConfigureAwait(false);

                if (model.Season == null || !model.Season.MatchTypes.Contains(MatchType.KnockoutMatch))
                {
                    return(new HttpNotFoundResult());
                }
                model.PossibleSeasons   = _editMatchHelper.PossibleSeasonsAsListItems(new[] { model.Match.Season });
                model.PossibleHomeTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
                model.PossibleAwayTeams = _editMatchHelper.PossibleTeamsAsListItems(model.Season.Teams);
            }

            model.IsAuthorized[AuthorizedAction.CreateMatch] = User.Identity.IsAuthenticated;

            _editMatchHelper.ConfigureAddMatchModelMetadata(model);

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
            });

            return(CurrentTemplate(model));
        }
Esempio n. 17
0
        private void DoTest(string input, IList expectedOutput, ContentModel contentModel, string lastStartTag)
        {
            HtmlTokenizer tokenizer = new HtmlTextTokenizer(new StringReader(input));
            tokenizer.ParseError += new EventHandler<ParseErrorEventArgs>(reader_ParseError);

            tokenizer.ContentModel = contentModel;
            if (!String.IsNullOrEmpty(lastStartTag)) {
                HtmlTextTokenizer__lastEmittedStartTagName.SetValue(tokenizer, lastStartTag);
            }

            Trace.Write("Input: ");
            Trace.WriteLine(input);
            try {
                while (tokenizer.Read()) {
                    switch (tokenizer.TokenType) {
                    case XmlNodeType.DocumentType:
                        actualOutput.Add(new object[] { "DOCTYPE", tokenizer.Name, tokenizer.GetAttribute("PUBLIC"), tokenizer.GetAttribute("SYSTEM"), !tokenizer.ForceQuirks });
                        break;
                    case XmlNodeType.Element:
                        Dictionary<string, string> attrs = new Dictionary<string, string>(
                            tokenizer.HasAttributes ? tokenizer.AttributeCount : 0,
                            StringComparer.InvariantCulture);
                        if (tokenizer.HasAttributes) {
                            for (int i = 0; i < tokenizer.AttributeCount; i++) {
                                attrs.Add(
                                    tokenizer.GetAttributeName(i),
                                    tokenizer.GetAttribute(i));
                            }
                        }
                        actualOutput.Add(new object[] { "StartTag", tokenizer.Name, attrs });
                        break;
                    case XmlNodeType.EndElement:
                        actualOutput.Add(new string[] { "EndTag", tokenizer.Name });
                        break;
                    case XmlNodeType.Comment:
                        actualOutput.Add(new string[] { "Comment", tokenizer.Value });
                        break;
                    case XmlNodeType.Text:
                    case XmlNodeType.Whitespace:
                        actualOutput.Add(new string[] { "Character", tokenizer.Value });
                        break;
                    default:
                        Assert.Fail("Unexpected token type: {0}", tokenizer.TokenType);
                        break;
                    }
                }

                Trace.Write("Expected output: ");
                TraceOutput(expectedOutput);
                Trace.WriteLine("");
                Trace.Write("Actual output: ");
                TraceOutput(actualOutput);
                Trace.WriteLine("");

                Assert.AreEqual(expectedOutput.Count, actualOutput.Count, "Not the same number of tokens");

                for (int i = 0; i < expectedOutput.Count; i++) {
                    object expected = expectedOutput[i];
                    object actual = actualOutput[i];

                    if (expected.GetType() == typeof(string)) {
                        // ParseError
            #if !NUNIT
                        Assert.IsInstanceOfType(actual, typeof(ParseErrorEventArgs));
            #else
                    Assert.IsInstanceOfType(typeof(ParseErrorEventArgs), actual);
            #endif
                    } else {
                        Assert.AreEqual(expected.GetType(), actual.GetType());

                        object[] expectedToken = (object[])expected;
                        object[] actualToken = (object[])actual;

                        Assert.AreEqual(expectedToken.Length, actualToken.Length);

                        for (int j = 0; j < expectedToken.Length; j++) {
                            if (expectedToken[j] is ICollection<KeyValuePair<string, string>>) {
            #if !NUNIT
                                Assert.IsInstanceOfType(actualToken[j], typeof(IDictionary<string, string>));
            #else
                            Assert.IsInstanceOfType(typeof(IDictionary<string, string>), actualToken[j]);
            #endif

                                ICollection<KeyValuePair<string, string>> expectedDict = (ICollection<KeyValuePair<string, string>>)expectedToken[j];
                                IDictionary<string, string> actualDict = (IDictionary<string, string>)actualToken[j];

                                Assert.AreEqual(expectedDict.Count, actualDict.Count);

                                foreach (KeyValuePair<string, string> attr in expectedDict) {
                                    Assert.AreEqual(attr.Value, actualDict[attr.Key]);
                                }
                            } else {
                                Assert.AreEqual(expectedToken[j], actualToken[j]);
                            }
                        }
                    }
                }
            } catch (NotImplementedException nie) {
                // Amnesty for those that confess
                Trace.WriteLine("");
                Trace.WriteLine(nie);
            #if NUNIT
                Assert.Ignore("Not Implemented");
            #else
                Assert.Inconclusive("Not Implemented");
            #endif
            }
        }
Esempio n. 18
0
 private SourceItemViewModel CreateSourceItemViewModel(ContentModel content)
 {
     return new SourceItemViewModel(content.Name, GetSourceItemType(content), x =>
     {
         switch (x.Type)
         {
             case SourceItemType.File:
             {
                 var vm = this.CreateViewModel<SourceViewModel>();
                 vm.Branch = Branch;
                 vm.RepositoryOwner = RepositoryOwner;
                 vm.RepositoryName = RepositoryName;
                 vm.TrueBranch = TrueBranch;
                 vm.Name = content.Name;
                 vm.HtmlUrl = content.HtmlUrl;
                 vm.Path = content.Path;
                 vm.PushAccess = PushAccess;
                 NavigateTo(vm);
                 break;
             }
             case SourceItemType.Directory:
             {
                 var vm = this.CreateViewModel<SourceTreeViewModel>();
                 vm.RepositoryOwner = RepositoryOwner;
                 vm.Branch = Branch;
                 vm.RepositoryName = RepositoryName;
                 vm.TrueBranch = TrueBranch;
                 vm.Path = content.Path;
                 vm.PushAccess = PushAccess;
                 NavigateTo(vm);
                 break;
             }
             case SourceItemType.Submodule:
             {
                 var nameAndSlug = content.GitUrl.Substring(content.GitUrl.IndexOf("/repos/", StringComparison.OrdinalIgnoreCase) + 7);
                 var repoId = new RepositoryIdentifier(nameAndSlug.Substring(0, nameAndSlug.IndexOf("/git", StringComparison.OrdinalIgnoreCase)));
                 var vm = this.CreateViewModel<SourceTreeViewModel>();
                 vm.RepositoryOwner = repoId.Owner;
                 vm.RepositoryName = repoId.Name;
                 vm.Branch = content.Sha;
                 NavigateTo(vm);
                 break;
             }
         }
     });
 }
Esempio n. 19
0
        public ActionResult Create(ContentModel model, string command, FormCollection fm)
        {
            try
            {
                using (var objContext = new db_KISDEntities())
                {
                    var file = Request.Files.Count > 0 ? Request.Files[0] : null;
                    if (string.IsNullOrEmpty(command))
                    {
                        var InnerImagesTitle = Models.Common.GetInnerImages();
                        ViewBag.InnerImagesTitle = InnerImagesTitle;//get all the inner image titles

                        var RightSectionTitle = (from db in objContext.RightSections
                                                 where db.StatusInd == true
                                                 select new { db.TitleTxt, db.RightSectionID }).ToList().OrderBy(x => x.TitleTxt);

                        ViewBag.RightSectionTitle = RightSectionTitle;

                        var ContentType = model.ContentTypeID;
                        ViewBag.ContentTypeID = ContentType;
                        var IsSave           = false;
                        var contenttypetitle = objContext.ContentTypes.Find(ContentType).ContentTypeNameTxt;
                        ViewBag.Title       = contenttypetitle;
                        ViewBag.PageTitle   = model.PageTitleTxt ?? "";
                        ViewBag.IsActiveInd = GetStatusData(model.StatusInd == true ? "1" : "0");
                        var objContent = objContext.Contents.Where(x => x.ContentTypeID == ContentType).FirstOrDefault();
                        if (objContent == null)
                        {
                            IsSave     = true;
                            objContent = new Content();
                        }

                        #region System Change Log
                        DataTable dtOld;
                        var       oldResult = (from a in objContext.Contents
                                               where a.ContentID == model.ContentID
                                               select a).ToList();
                        dtOld = Models.Common.LINQResultToDataTable(oldResult);
                        #endregion

                        ViewBag.Submit = IsSave ? "Save" : "Update";

                        if (model != null && !string.IsNullOrEmpty(model.PageURLTxt))
                        {
                            var count = 0;
                            count  = objContext.Contents.Where(x => x.PageURLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.ContentID != model.ContentID && x.IsDeletedInd == false).Count();
                            count += objContext.BoardOfMembers.Where(x => x.URLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.IsDeletedInd == false).Count();
                            count += objContext.Departments.Where(x => x.URLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.IsDeletedInd == false).Count();
                            count += objContext.ExceptionOpportunities.Where(x => x.URLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.IsDeletedInd == false).Count();
                            count += objContext.GalleryListings.Where(x => x.URLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.IsDeletedInd == false).Count();
                            count += objContext.NewsEvents.Where(x => x.PageURLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && x.IsDeletedInd == false).Count();
                            count += objContext.RightSections.Where(x => x.ExternalLinkURLTxt.ToLower().Trim() == model.PageURLTxt.ToLower().Trim() && (x.IsDeletedInd == false || x.IsDeletedInd == null)).Count();
                            if (model.PageURLTxt.Trim().ToLower() == "error404")// Check for duplicate url and error404 url
                            {
                                count = count + 1;
                            }

                            if (count > 0)
                            {
                                #region Route value directory
                                var rvd = new RouteValueDictionary();
                                rvd.Add("ContentType", ContentType);
                                #endregion

                                ViewBag.FocusPageUrl = true;                         // Set focus on Pageurl Field if same url exist
                                ViewBag.InnerImages  = new SelectList(objContext.Images.Where(x => x.ImageTypeID == 2 && x.StatusInd == true).ToList(), "ImageID", "TitleTxt");
                                if (model.PageURLTxt.ToLower().Trim() == "error404") //if user types url 'error404' below validation msg should display
                                {
                                    ModelState.AddModelError("PageURLTxt", model.PageURLTxt + " URL is not allowed.");
                                }
                                else
                                {
                                    ModelState.AddModelError("PageURLTxt", model.PageURLTxt + " URL already exists.");
                                }

                                return(View(model));
                            }
                        }


                        objContent.ContentTypeID          = ContentType;
                        objContent.ParentID               = (int?)null;
                        objContent.IsExternalLinkInd      = model.IsExternalLinkInd;
                        objContent.ExternalLinkTxt        = string.IsNullOrEmpty(model.ExternalLinkTxt) ? string.Empty : model.ExternalLinkTxt;
                        objContent.ExternalLinkTargetInd  = model.IsExternalLinkInd ? model.ExternalLinkTargetInd : false;
                        objContent.PageTitleTxt           = model.IsExternalLinkInd ? string.Empty :(string.IsNullOrEmpty(model.PageTitleTxt) ? string.Empty : model.PageTitleTxt);
                        objContent.MenuTitleTxt           = string.IsNullOrEmpty(model.MenuTitleTxt) ? (ContentType == 1 ? "home" : string.Empty) : model.MenuTitleTxt.Replace("<", "");
                        objContent.PageURLTxt             = model.IsExternalLinkInd ? string.Empty : (string.IsNullOrEmpty(model.PageURLTxt) ? (ContentType == 1 ? "home" : string.Empty) : (ContentType == 1 ? "home" : model.PageURLTxt));
                        objContent.BannerImageID          = model.IsExternalLinkInd ? 0 : model.BannerImageID;
                        objContent.AbstractTxt            = string.IsNullOrEmpty(model.AbstractTxt) ? string.Empty : model.AbstractTxt;
                        objContent.BannerImageAbstractTxt = model.IsExternalLinkInd ? string.Empty :(string.IsNullOrEmpty(model.BannerImageAbstractTxt) ? string.Empty : model.BannerImageAbstractTxt);
                        objContent.DescriptionTxt         = model.IsExternalLinkInd ? string.Empty :(string.IsNullOrEmpty(model.DescriptionTxt) ? string.Empty : model.DescriptionTxt);
                        objContent.StatusInd              = (ContentType == Convert.ToInt32(ContentTypeAlias.Footer) ||
                                                             ContentType == Convert.ToInt32(ContentTypeAlias.Header) ||
                                                             ContentType == Convert.ToInt32(ContentTypeAlias.Search) ||
                                                             ContentType == Convert.ToInt32(ContentTypeAlias.Home)
                                                             ) ? true : (fm["IsActiveInd"] == "1" ? true : false);
                        objContent.ContentCreateDate = model.ContentCreateDate;

                        objContent.PageMetaTitleTxt        = model.IsExternalLinkInd ? string.Empty :(string.IsNullOrEmpty(model.PageMetaTitleTxt) ? string.Empty : model.PageMetaTitleTxt);
                        objContent.PageMetaDescriptionTxt  = model.IsExternalLinkInd ? string.Empty :(string.IsNullOrEmpty(model.PageMetaDescriptionTxt) ? string.Empty : model.PageMetaDescriptionTxt);
                        objContent.AltBannerImageTxt       = model.IsExternalLinkInd ? string.Empty : model.AltBannerImageTxt;
                        objContent.RightSectionAbstractTxt = model.IsExternalLinkInd ? string.Empty : model.RightSectionAbstractTxt;
                        objContent.RightSectionTitleTxt    = model.IsExternalLinkInd ? string.Empty : model.RightSectionTitleTxt;
                        objContent.IsFacebookSharingInd    = model.IsExternalLinkInd ? false : model.IsFacebookSharingInd;
                        objContent.IsGooglePlusSharingInd  = model.IsExternalLinkInd ? false: model.IsGooglePlusSharingInd;
                        objContent.IsTwitterSharingInd     = model.IsExternalLinkInd ? false : model.IsTwitterSharingInd;
                        objContent.IsDeletedInd            = false;
                        objContent.CreateDate     = model.ContentID > 0 ? objContent.CreateDate : DateTime.Now;;
                        objContent.CreateByID     = model.ContentID > 0 ? objContent.CreateByID : Convert.ToInt64(Membership.GetUser().ProviderUserKey);
                        objContent.LastModifyByID = Convert.ToInt64(Membership.GetUser().ProviderUserKey);
                        objContent.LastModifyDate = DateTime.Now;

                        //Save image path
                        if (file != null && file.ContentLength > 0)
                        {
                            #region Upload Image
                            Models.Common.CreateFolder();
                            var NewImgName = UploadImage();
                            //var croppedfile = new FileInfo(Server.MapPath(NewImgName.Data.ToString()));//err
                            var fileName = NewImgName.Data;
                            TempData["CroppedImage"] = null;
                            objContent.AbstractTxt   = "~/WebData/images/" + fileName;
                            #endregion

                            if (!string.IsNullOrEmpty(model.AbstractTxt) && (
                                    (objContent.ContentTypeID == Convert.ToInt32(ContentTypeAlias.Header))
                                    ))
                            {
                                try
                                {
                                    Models.Common.DeleteImage(Server.MapPath(model.AbstractTxt));
                                }
                                catch
                                {
                                }
                            }
                        }
                        if (IsSave)
                        {
                            objContext.Contents.Add(objContent);
                        }
                        objContext.SaveChanges();

                        var AlertText = IsContent(objContent.ContentTypeID) ? " Content" : " Page Content";
                        TempData["Alert"] = contenttypetitle + (IsSave ? AlertText + " saved successfully." : AlertText + " updated successfully.");

                        #region System Change Log
                        SystemChangeLog objSCL  = new SystemChangeLog();
                        long            userid  = Convert.ToInt64(Membership.GetUser().ProviderUserKey);
                        User            objuser = objContext.Users.Where(x => x.UserID == userid).FirstOrDefault();
                        objSCL.NameTxt     = objuser.FirstNameTxt + " " + objuser.LastNameTxt;
                        objSCL.UsernameTxt = objuser.UserNameTxt;
                        objSCL.UserRoleID  = (short)objContext.UserRoles.Where(x => x.UserID == objuser.UserID).First().RoleID;
                        objSCL.ModuleTxt   = "Content";
                        objSCL.LogTypeTxt  = model.ContentID > 0 ? "Update" : "Add";
                        objSCL.NotesTxt    = (GetContentType(model.ContentTypeID)) + " Details" + (model.ContentID > 0 ? " updated for " : "  added for ") + model.PageTitleTxt;
                        objSCL.LogDateTime = DateTime.Now;
                        objContext.SystemChangeLogs.Add(objSCL);
                        objContext.SaveChanges();
                        objSCL = objContext.SystemChangeLogs.OrderByDescending(x => x.ChangeLogID).FirstOrDefault();
                        var newResult = (from x in objContext.Contents
                                         where x.ContentID == objContent.ContentID
                                         select x);
                        DataTable dtNew = Models.Common.LINQResultToDataTable(newResult);
                        foreach (DataColumn col in dtNew.Columns)
                        {
                            if (model.ContentID > 0)
                            {
                                if (dtOld.Rows[0][col.ColumnName].ToString() != dtNew.Rows[0][col.ColumnName].ToString())
                                {
                                    SystemChangeLogDetail objSCLD = new SystemChangeLogDetail();
                                    objSCLD.ChangeLogID  = objSCL.ChangeLogID;
                                    objSCLD.FieldNameTxt = col.ColumnName.ToString();
                                    objSCLD.OldValueTxt  = dtOld.Rows[0][col.ColumnName].ToString();
                                    objSCLD.NewValueTxt  = dtNew.Rows[0][col.ColumnName].ToString();
                                    objContext.SystemChangeLogDetails.Add(objSCLD);
                                    objContext.SaveChanges();
                                }
                            }
                            else
                            {
                                SystemChangeLogDetail objSCLD = new SystemChangeLogDetail();
                                objSCLD.ChangeLogID  = objSCL.ChangeLogID;
                                objSCLD.FieldNameTxt = col.ColumnName.ToString();
                                objSCLD.OldValueTxt  = "";
                                objSCLD.NewValueTxt  = dtNew.Rows[0][col.ColumnName].ToString();
                                objContext.SystemChangeLogDetails.Add(objSCLD);
                                objContext.SaveChanges();
                            }
                        }
                        #endregion

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }
            catch (Exception ex)
            {
                TempData["Alert"] = " Some error occured. Please try again later.";
                return(RedirectToAction("Index", "Home"));
            }
        }
 public ActionResult Index(ContentModel model)
 {
     return(RenderView(false));
 }
Esempio n. 21
0
        //private void GetMetaData(int id, ContentModel syncModel)
        //{
        //    var xml = XDocument.Load(string.Format("http://{0}/library/metadata/{1}", _plexServerAddress, id));
        //    // read the genres
        //    var genres = xml.Descendants("Genre").Select(node => ReadAttribute(node, "tag")).ToList();
        //    syncModel.Genres = string.Join(",", genres);
        //    // read the collections
        //    var collections = xml.Descendants("Collection").Select(node => ReadAttribute(node, "tag")).ToList();
        //    syncModel.Collections = string.Join(",", collections);
        //}
        private string CalculateComparisonHash(ContentModel contentModel)
        {
            var contents = new StringBuilder();

            contents.Append(contentModel.Title);
            contents.Append(contentModel.SortName);
            contents.Append(contentModel.Season);
            contents.Append(contentModel.Episode);
            contents.Append(contentModel.Collections);
            contents.Append(contentModel.LibraryName);
            contents.Append(string.Join(",",contentModel.MediaModels.Select(a => string.Format("{0}{1}{2}{3}", a.VideoId, a.MediaId, a.FilePath, a.Size))));

            var md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(contents.ToString());
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
Esempio n. 22
0
        public object Run(object t, ParallelTask task)
        {
            var model = t as CrawlTaskModel;

            var results  = new List <object>();
            var reporter = task.Progress as IProgress <string>;

            reporter.Report("正在读取Feed记录");
            var feed = FeedLiteDb.GetFeed(model.FeedId);

            reporter.Report("正在下载 Feed");

            var compile = new UrlCompile();
            var addrs   = compile.GetResult(feed.Address);

            foreach (var addr in addrs)
            {
                feed.Address = addr.ToString();

                var job  = new FeedJob();
                var snap = job.DoTask(feed, false);
                reporter.Report("Feed 下载完成");

                var block = RuiJiBlockParser.ParserBlock(feed.RuiJiExpression);

                var feedResult = RuiJiExtractor.Extract(snap.Content, block);
                results.Add(feedResult);

                reporter.Report("正在提取Feed地址");
                var j    = new FeedExtractJob();
                var urls = j.ExtractAddress(snap);
                reporter.Report("Feed地址提取完成");

                if (!string.IsNullOrEmpty(snap.RuiJiExpression))
                {
                    foreach (var url in urls)
                    {
                        reporter.Report("正在提取地址 " + url);
                        var result = Cooperater.GetResult(url);

                        if (result != null)
                        {
                            var cm = new ContentModel();
                            cm.Id    = model.FeedId;
                            cm.Url   = url;
                            cm.Metas = result.Metas;
                            cm.CDate = DateTime.Now;

                            results.Add(cm);
                        }
                    }
                }

                reporter.Report("计算完成");

                if (!model.IncludeContent)
                {
                    results.ForEach((m) =>
                    {
                        ClearContent(m);
                    });
                }
            }

            return(results);
        }
Esempio n. 23
0
 public virtual async Task <IActionResult> Index(ContentModel model) => await List(model, "Index");
Esempio n. 24
0
        public override ActionResult Index(ContentModel m)
        {
            PurchaseOrderViewModel model = MapOrder();

            return(View("/Views/Preview.cshtml", model));
        }
Esempio n. 25
0
 // GET: Confirmation
 public override ActionResult Index(ContentModel model)
 {
     return(View("/Views/Confirmation.cshtml"));
 }
Esempio n. 26
0
        public ActionResult Create(string ct)
        {
            TempData["CroppedImage"] = null;
            using (var objContext = new db_KISDEntities())
            {
                //decrypt content type id(ct)
                ct = !string.IsNullOrEmpty(Convert.ToString(ct)) ? EncryptDecrypt.Decrypt(ct) : "0";
                int ContentTypeID = !string.IsNullOrEmpty(ct) ? Convert.ToInt32(ct) : 0;

                #region Check Tab is Accessible or Not
                int TabType = 0;
                if (ContentTypeID == 1 || ContentTypeID == 2 || ContentTypeID == 3)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.Home);
                }
                if (ContentTypeID == 4)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.AboutKISD);
                }
                if (ContentTypeID == 5)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.School);
                }
                if (ContentTypeID == 6)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.NewToKISD);
                }
                if (ContentTypeID == 7 || ContentTypeID == 35)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.ParentStudents);
                }
                if (ContentTypeID == 8)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.Departments);
                }
                if (ContentTypeID == 9 || ContentTypeID == 34)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.SchoolBoard);
                }
                if (ContentTypeID == 10)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.Employment);
                }
                if (ContentTypeID == 11)
                {
                    TabType = Convert.ToInt32(ModuleTypeAlias.GoogleAnalytic);
                }

                var userId       = objContext.Users.Where(x => x.UserNameTxt == User.Identity.Name).Select(x => x.UserID).FirstOrDefault();
                var RoleID       = objContext.UserRoles.Where(x => x.UserID == userId).Select(x => x.RoleID).FirstOrDefault();
                var HasTabAccess = GetAccessibleTabAccess(TabType, Convert.ToInt32(userId));
                if (!(HasTabAccess || RoleID == Convert.ToInt32(UserType.SuperAdmin) ||
                      RoleID == Convert.ToInt32(UserType.Admin))) //if tab not accessible then redirect to home
                {
                    if (TabType == Convert.ToInt32(ModuleTypeAlias.Departments) && RoleID == Convert.ToInt32(UserType.DepartmentUser))
                    {
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                #endregion

                ViewBag.ContentTypeID = ContentTypeID;
                ViewBag.Date          = DateTime.Now.ToShortDateString();
                var chkcontenttype = objContext.ContentTypes.Any(x => x.ContentTypeID == ContentTypeID && ContentTypeID <= 43);
                if (!chkcontenttype)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                var objContentModel = new ContentModel();
                objContentModel.ContentTypeID = ContentTypeID;
                var objContent       = objContext.Contents.Where(x => x.ContentTypeID == ContentTypeID).FirstOrDefault();
                var contenttypetitle = objContext.ContentTypes.Find(ContentTypeID).ContentTypeNameTxt;

                objContentModel.RightSections = GetAllRightSections();

                if (objContent != null)
                {
                    objContentModel.ContentID = objContent.ContentID;

                    objContentModel.AbstractTxt            = objContent.AbstractTxt;
                    objContentModel.ContentTypeID          = objContent.ContentTypeID;
                    objContentModel.IsExternalLinkInd      = objContent.IsExternalLinkInd;
                    objContentModel.ExternalLinkTxt        = objContent.ExternalLinkTxt;
                    objContentModel.ExternalLinkTargetInd  = objContent.ExternalLinkTargetInd;
                    objContentModel.PageTitleTxt           = objContent.PageTitleTxt;
                    objContentModel.MenuTitleTxt           = objContent.MenuTitleTxt;
                    objContentModel.PageURLTxt             = objContent.PageURLTxt;
                    objContentModel.BannerImageID          = objContent.BannerImageID;
                    objContentModel.AltBannerImageTxt      = objContent.AltBannerImageTxt;
                    objContentModel.BannerImageAbstractTxt = objContent.BannerImageAbstractTxt;
                    objContentModel.DescriptionTxt         = objContent.DescriptionTxt;
                    objContentModel.ContentCreateDate      = objContent.ContentCreateDate;
                    objContentModel.CreateDate             = objContent.CreateDate;
                    objContentModel.StatusInd               = objContent.StatusInd;
                    objContentModel.PageMetaTitleTxt        = objContent.PageMetaTitleTxt;
                    objContentModel.RightSectionTitleTxt    = objContent.RightSectionTitleTxt;
                    objContentModel.RightSectionAbstractTxt = objContent.RightSectionAbstractTxt;
                    objContentModel.PageMetaDescriptionTxt  = objContent.PageMetaDescriptionTxt;
                    objContentModel.IsGooglePlusSharingInd  = objContent.IsGooglePlusSharingInd.HasValue ? objContent.IsGooglePlusSharingInd.Value : false;
                    objContentModel.IsFacebookSharingInd    = objContent.IsFacebookSharingInd.HasValue ? objContent.IsFacebookSharingInd.Value : false;
                    objContentModel.IsTwitterSharingInd     = objContent.IsTwitterSharingInd.HasValue ? objContent.IsTwitterSharingInd.Value : false;
                    objContentModel.strCreateDate           = objContent.CreateDate.HasValue ? objContent.CreateDate.Value.ToShortDateString() : DateTime.Now.ToShortDateString();
                    ViewBag.IsActiveInd = GetStatusData(objContentModel.StatusInd == true ? "1" : "0");
                    ViewBag.Date        = objContent.ContentCreateDate != null?objContent.ContentCreateDate.Value.ToShortDateString() : DateTime.Now.ToShortDateString();

                    objContentModel.ContentTypeTitle = "Edit " + contenttypetitle + (IsContent(ContentTypeID) ? " Content" : " Page Content");
                    ViewBag.Submit = "Update";
                }
                else
                {
                    ViewBag.Submit = "Save";
                    string[] ToEmailarr = new string[] { "0" };
                    objContentModel.ContentTypeID = ContentTypeID;
                    ViewBag.Date = DateTime.Now.ToShortDateString();
                    objContentModel.IsGooglePlusSharingInd = false;
                    objContentModel.IsFacebookSharingInd   = false;
                    objContentModel.IsTwitterSharingInd    = false;
                    objContentModel.ContentTypeTitle       = "Add " + contenttypetitle + (IsContent(ContentTypeID) ? " Content" : " Page Content");
                    ViewBag.IsActiveInd = GetStatusData(string.Empty);
                }

                var InnerImagesTitle = Models.Common.GetInnerImages();
                ViewBag.InnerImagesTitle = InnerImagesTitle;//get all the inner image titles

                ViewBag.Title = (ContentModel.GetContentTypeName(Convert.ToInt32(ContentTypeID))) + (ContentTypeID == Convert.ToInt32(ContentTypeAlias.Fly) ? " Page" : "");
                return(View(objContentModel));
            }
        }
Esempio n. 27
0
 /// <summary>
 /// over ride the default index action
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public override ActionResult Index(ContentModel model)
 {
     //return the view with the custom model combined with the umbraco content model
     return(View(MapModel(model.Content)));
 }
Esempio n. 28
0
        // GET: Home
        public override ActionResult Index(ContentModel model)
        {
            var home = new Home(model.Content);

            return(CurrentTemplate(home));
        }
Esempio n. 29
0
 public ActionResult Counter(string categoryAlias = "", string alias = "")
 {
     ContentModel.AddHit(AppUsers.GetTenant(), categoryAlias, alias);
     return(this.Ok());
 }
Esempio n. 30
0
 private CurrentTokenizerTokenState FollowGenericCdataOrRcdataParsingAlgorithm(ContentModel cdataOrRcdata)
 {
     Debug.Assert(cdataOrRcdata == ContentModel.Cdata || cdataOrRcdata == ContentModel.Rcdata);
     _inCdataOrRcdata = true;
     _tokenizer.ContentModel = cdataOrRcdata;
     // XXX: we're adding the element to the stack of open elements as a way to keep track of its name
     return InsertHtmlElement();
 }
Esempio n. 31
0
        public virtual ActionResult About()
        {
            ContentModel model = db.GetContent("About");

            return(View(model));
        }
        /// <summary>
        /// This method is used to delete Purchase and Sales Categories content
        /// </summary>
        /// <param name="content"></param>
        public void DeletePSCategoryContent(ContentModel content)
        {
            IContentOperationBL catBL = new CategoryContentOperationsBL();

            catBL.DeletePSCategoryContent(content);
        }
Esempio n. 33
0
        public virtual ActionResult ForDesigners()
        {
            ContentModel model = db.GetContent("ForDesigners");

            return(View(model));
        }
Esempio n. 34
0
 public virtual ActionResult Index(ContentModel model)
 {
     return(CurrentTemplate(model));
 }
 public ActionResult HomePage(ContentModel model)
 {
     return(View());
 }
Esempio n. 36
0
        void SaveContent(object param)
        {
            //creating an object of repository
            ICategoryRepository catRepository = new CategoryRepository();

            if (SelectedPSCategory != null)
            {
                if (string.IsNullOrEmpty(SelectedPSContent))
                {
                    Error = "Please enter content to save";
                    return;
                }
                else
                {
                    Error = string.Empty;
                    MessageBoxResult result = System.Windows.MessageBox.Show("Do you want to save changes?", "Save Content", MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.Yes)
                    {
                        var cat = SelectedPSCategory as ContentModel;
                        if (cat != null)
                        {
                            var content = new ContentModel();
                            content.CategoryID   = cat.CategoryID;
                            content.CategoryCode = cat.CategoryCode;
                            content.ContentName  = SelectedPSContent;
                            catRepository.SavePSCategoryContent(content);

                            // PSError = string.Empty;
                        }
                    }
                }
            }
            else
            {
                if (SelectedCategory == null)
                {
                    Error = "Please select Category";
                }
                else
                {
                    // UpdateBindingGroup.CommitEdit();
                    var content = SelectedCategoryContent as ContentModel;
                    if (content == null || content.ContentName == string.Empty || content.ContentName == null)
                    {
                        Error = "Please enter content to save";
                    }
                    else
                    {
                        //Commented as client's mail on 31 march 2017
                        //if (content.Predefined == true)
                        //{
                        //    if (content.ContentName != "0")
                        //    {
                        //        Error = "Cannot edit Predefined Contents";
                        //        return;
                        //     }
                        // }

                        string msg = catRepository.ValidateCategoryContent(content);
                        if (msg != string.Empty)
                        {
                            Error = msg;
                        }
                        else
                        {
                            Error = string.Empty;
                            MessageBoxResult result = System.Windows.MessageBox.Show("Do you want to save changes?", "Save Content", MessageBoxButton.YesNo);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (!catRepository.IsContentExists(content))
                                {
                                    Error = string.Empty;

                                    var catContent = SelectContent as ContentModel;
                                    //if (catContent != null)
                                    //{
                                    //    SelectedCategoryContent.IsSelected = catContent.IsSelected;
                                    //}

                                    if (SelectedIndex == -1)
                                    {
                                        catRepository.SaveCategoryContent(content);
                                    }
                                    else
                                    {
                                        catRepository.UpdateCategoryContent(content);
                                    }
                                    OnPropertyChanged("SelectContent"); // Update the list from the data source

                                    // MessageBox.Show("Record Saved Successfully");
                                    // System.Windows.MessageBox.Show("Record Saved successfully", "Save Content", MessageBoxButton.OK);
                                }
                                else
                                {
                                    Error = "Content should be unique";
                                    return;
                                }
                            }
                            SelectContent           = null;
                            SelectedCategoryContent = null;
                            SelectedContent         =
                                new ObservableCollection <ContentModel>(catRepository.GetCategoryContent(content.CategoryID));
                        }
                    }
                }
            }
        }
Esempio n. 37
0
 public ActionResult Product(ContentModel model, string id)
 {
     return(this.View("Product", model));
 }
Esempio n. 38
0
        public async Task <ActionResult> CounterAsync(string categoryAlias = "", string alias = "")
        {
            await ContentModel.AddHitAsync(this.Tenant, categoryAlias, alias).ConfigureAwait(false);

            return(this.Ok());
        }
Esempio n. 39
0
        public override SearchPage CreateModel(SearchPage viewModel, ContentModel contentModel)
        {
            viewModel = base.CreateModel(viewModel, contentModel);

            return(viewModel);
        }
Esempio n. 40
0
        private static SourceItemType GetSourceItemType(ContentModel content)
        {
            if (content.Type.Equals("dir", StringComparison.OrdinalIgnoreCase))
                return SourceItemType.Directory;
            if (content.Type.Equals("file", StringComparison.OrdinalIgnoreCase))
            {
                var isTree = content.GitUrl.EndsWith("trees/" + content.Sha, StringComparison.OrdinalIgnoreCase);
                if (content.Size == null || isTree)
                    return SourceItemType.Submodule;
            }

            return SourceItemType.File;
        }
        public async Task <IWikiArticle> GetArticleAsync(IArticleIdentifier articleIdentifier, ContentModel contentModel)
        {
            try
            {
                // Resolve license on a background task, retrieve after content has been parsed.
                var licenseTask = _articleLicenseProvider.GetArticleLicenseAsync(articleIdentifier);

                var parseQuery    = MediaWikiUtils.GetParseQuery(articleIdentifier.Title, articleIdentifier.Language, contentModel);
                var parseQueryUri = new Uri(parseQuery);

                var mwResponse = await _networkingProvider.DownloadContentAsync(parseQueryUri);

                var mwResponseObject = JsonConvert.DeserializeObject <ParserResponse.ParserRootObject>(mwResponse);

                string?content = contentModel switch
                {
                    ContentModel.Html => mwResponseObject?.parse?.text?["*"],
                    ContentModel.WikiText => mwResponseObject?.parse?.wikitext?["*"],
                    _ => throw new NotImplementedException()
                };

                if (content == null)
                {
                    var logSb = new StringBuilder().Append("Failed to deserialize MediaWiki parser output.").Append(Environment.NewLine)
                                .Append("Media Wiki response content: ").Append(mwResponse);

                    throw new ApplicationException(logSb.ToString());
                }

                // retrieve license from background task
                var license = await licenseTask;

                return(_wikiMediaFactory.CreateWikiArticle(articleIdentifier, license, content, contentModel));
            }

            catch (Exception e)
            {
                _logger.LogError(e, "Failed to retrieve article.");
                throw;
            }
        }
 public IList<string> FindComponents(ContentModel.Querying.IQuery queryParameters)
 {
     throw new NotImplementedException();
 }
Esempio n. 43
0
        public override bool Read()
        {
            if (_tokenState == TokenState.Complete) {
                if (_textToken.Length > 0) {
                    _textToken.Length = 0;
                    _textTokenIsWhitespace = true;
                    return true;
                }
                _tokenState = TokenState.Uninitialized;
            }

            _textToken.Length = 0;
            _textTokenIsWhitespace = true;

            do {
                switch (_currentParsingFunction) {
                case ParsingFunction.Initial:
                    // http://www.whatwg.org/specs/web-apps/current-work/multipage/section-tokenisation.htmlmultipage/section-tokenisation.html#tokenization:
                    // The state machine must start in the data state.
                    _currentParsingFunction = ParsingFunction.Data;
                    break;
                case ParsingFunction.Eof:
                    if (_textToken.Length == 0) {
                        return false;
                    }
                    _tokenState = TokenState.Initialized; // HACK: to exit the while loop
                    break;
                case ParsingFunction.ReaderClosed:
                    return false;
                case ParsingFunction.Data:
                    ParseData();
                    break;
                case ParsingFunction.EntityData:
                    ParseEntityData();
                    break;
                case ParsingFunction.TagOpen:
                    ParseTagOpen();
                    break;
                case ParsingFunction.CloseTagOpen:
                    ParseCloseTagOpen();
                    break;
                case ParsingFunction.TagName:
                    ParseTagName();
                    break;
                case ParsingFunction.BeforeAttributeName:
                    ParseBeforeAttributeName();
                    break;
                case ParsingFunction.AttributeName:
                    ParseAttributeName();
                    break;
                case ParsingFunction.AfterAttributeName:
                    ParseAfterAttributeName();
                    break;
                case ParsingFunction.BeforeAttributeValue:
                    ParseBeforeAttributeValue();
                    break;
                case ParsingFunction.AttributeValueDoubleQuoted:
                    ParseAttributeValueDoubleQuoted();
                    break;
                case ParsingFunction.AttributeValueSingleQuoted:
                    ParseAttributeValueSingleQuoted();
                    break;
                case ParsingFunction.AttributeValueUnquoted:
                    ParseAttributeValueUnquoted();
                    break;
                // case ParsingFunction.EntityInAttributeValue: handled "inline" in the ParseAttributeXXX methods
                case ParsingFunction.AfterAttributeValueQuoted:
                    ParseAfterAttributeValueQuoted();
                    break;
                case ParsingFunction.BogusComment:
                    ParseBogusComment();
                    break;
                case ParsingFunction.MarkupDeclarationOpen:
                    ParseMarkupDeclarationOpen();
                    break;
                case ParsingFunction.CommentStart:
                    ParseCommentStart();
                    break;
                case ParsingFunction.CommentStartDash:
                    ParseCommentStartDash();
                    break;
                case ParsingFunction.Comment:
                    ParseComment();
                    break;
                case ParsingFunction.CommentEndDash:
                    ParseCommentEndDash();
                    break;
                case ParsingFunction.CommentEnd:
                    ParseCommentEnd();
                    break;
                case ParsingFunction.Doctype:
                    ParseDoctype();
                    break;
                case ParsingFunction.BeforeDoctypeName:
                    ParseBeforeDoctypeName();
                    break;
                case ParsingFunction.DoctypeName:
                    ParseDoctypeName();
                    break;
                case ParsingFunction.AfterDoctypeName:
                    ParseAfterDoctypeName();
                    break;
                case ParsingFunction.BeforeDoctypePublicId:
                    ParseBeforeDoctypePublicId();
                    break;
                case ParsingFunction.DoctypePublicIdDoubleQuoted:
                    ParseDoctypePublicIdDoubleQuoted();
                    break;
                case ParsingFunction.DoctypePublicIdSingleQuoted:
                    ParseDoctypePublicIdSingleQuoted();
                    break;
                case ParsingFunction.AfterDoctypePublicId:
                    ParseAfterDoctypePublicId();
                    break;
                case ParsingFunction.BeforeDoctypeSystemId:
                    ParseBeforeDoctypeSystemId();
                    break;
                case ParsingFunction.DoctypeSystemIdDoubleQuoted:
                    ParseDoctypeSystemIdDoubleQuoted();
                    break;
                case ParsingFunction.DoctypeSystemIdSingleQuoted:
                    ParseDoctypeSystemIdSingleQuoted();
                    break;
                case ParsingFunction.AfterDoctypeSystemId:
                    ParseAfterDoctypeSystemId();
                    break;
                case ParsingFunction.BogusDoctype:
                    ParseBogusDoctype();
                    break;
                default:
                    throw new InvalidOperationException();
                }
            } while (_tokenState == TokenState.Uninitialized
                || (_tokenState == TokenState.Initialized && _textToken.Length == 0));

            if (_tokenState == TokenState.Complete){
                switch (_tokenType) {
                case XmlNodeType.Element:
                case XmlNodeType.EndElement:
                    // Check duplicate attributes
                    _attributes.RemoveAll(
                        delegate(Attribute attr)
                        {
                            if (attr.isDuplicate) {
                                OnParseError(new ParseErrorEventArgs(String.Concat("Duplicate attribute: ", attr.name), attr));
                                return true;
                            }
                            return false;
                        }
                    );
                    if (_tokenType == XmlNodeType.EndElement) {
                        _contentModel = ContentModel.Pcdata;
                        if (_attributes.Count > 0) {
                            OnParseError("End tag with attributes");
                        }
                    }
                    break;
                }
            }
            return true;
        }