/// <summary> /// Gets an instance of the configuration for a given publication /// </summary> /// <param name="publication"></param> /// <returns></returns> public static TridionConfigurationManager GetInstance(Publication publication) { log.Debug(">>GetInstance called for " + publication.Id); // locking to make threadsafe // this prevents errors like 'given key was not present in the dictionary' lock (lock1) { if (!Instances.ContainsKey(publication.Id)) { log.Debug("no instance found, creating new one"); AddInstance(publication); } else { log.Debug(string.Format("found instance, publication revision date {0}, config file modification date {1}, cache date {2}", publication.RevisionDate, ConfigurationModificationDate, InstanceCacheDates[publication.Id])); if (InstanceCacheDates[publication.Id].CompareTo(publication.RevisionDate) < 0 || InstanceCacheDatesFS[publication.Id].CompareTo(ConfigurationModificationDate) < 0) { log.Debug("creating new instance"); RemoveInstance(publication); AddInstance(publication); } } } return Instances[publication.Id]; }
private List<SiteLocalizationData> DetermineSiteLocalizations(Publication contextPublication) { string siteId = GetSiteIdFromPublication(contextPublication); Publication master = GetMasterPublication(contextPublication); Logger.Debug(String.Format("Master publication is : {0}, siteId is {1}", master.Title, siteId)); List<SiteLocalizationData> siteLocalizations = new List<SiteLocalizationData>(); bool masterAdded = false; if (GetSiteIdFromPublication(master) == siteId) { masterAdded = IsMasterWebPublication(master); siteLocalizations.Add(GetPublicationDetails(master, masterAdded)); } if (siteId!=null) { siteLocalizations.AddRange(GetChildPublicationDetails(master, siteId, masterAdded)); } //It is possible that no publication has been set explicitly as the master //in which case we set the context publication as the master if (!siteLocalizations.Any(p => p.IsMaster)) { string currentPubId = Publication.Id.ItemId.ToString(CultureInfo.InvariantCulture); foreach (SiteLocalizationData pub in siteLocalizations) { if (pub.Id==currentPubId) { pub.IsMaster = true; } } } return siteLocalizations; }
public static void Main() { Contact[] contacts = new Contact[6]; contacts[0] = new Contact( "Dick", "Traci", "123 Main St., Spokane, WA 99037", "123-123-1234"); // ... // Classes are implicitly converted to // their supported interfaces contacts.List(Contact.Headers); Console.WriteLine(); Publication[] publications = new Publication[3] { new Publication("Celebration of Discipline", "Richard Foster", 1978), new Publication("Orthodoxy", "G.K. Chesterton", 1908), new Publication( "The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979) }; publications.List(Publication.Headers); }
public void Run_Where_We_Batch_Publish_Messages_Waiting_For_Batch_Completion_Each_Time() { this.InstantiateAndStartPublisher(); do { var _tasks = new List<Task>(); var _messageDelivery = new MessageDelivery(Configuration.ExchangeName1, "H", MessageDeliveryMode.Persistent, m => "Ted"); for (var _index = 1; _index <= 100; _index++) { var _myEvent = new MyEvent(Guid.NewGuid(), "", "R1", _index, "09:00", "DDD...."); var _taskCompletionSource = new TaskCompletionSource<PublicationResult>(); var _publication = new Publication(_messageDelivery, _myEvent, _taskCompletionSource); this.c_publicationQueue.Add(_publication); _tasks.Add(_publication.ResultTask); } Task.WaitAll(_tasks.ToArray()); Console.WriteLine("Hit enter to publish more messages, x to exit"); } while (Console.ReadLine() != "x"); Console.WriteLine("Hit enter to cancel"); Console.ReadLine(); this.c_cancellationTokenSource.Cancel(); Console.WriteLine("Hit enter to close connection (Channel should already be closed - check the dashboard)"); Console.ReadLine(); this.c_connection.Close(); Console.WriteLine("Hit enter to exit"); Console.ReadLine(); }
public PublicationResult BuildFrom(Publication publication, IJsonSerializer jsonSerializer, string trafficTag, string trafficTagName) { var publicationResult = new PublicationResult(jsonSerializer); publicationResult.PublishableItemData = publicationResult.GetPublishableItemData(publication); publicationResult.PublicationData = publicationResult.GetPublicationData(publication, trafficTag,trafficTagName); publicationResult.UserData = publicationResult.GetUserData(publication); return publicationResult; }
public void AverageRanking_Should_be_Return_2_5() { Publication publication = new Publication(); publication.ConfortRanking = 2; publication.DesignRanking = 2; publication.PriceRanking = 0; publication.SecurityRanking = 5; Assert.AreEqual(publication.AverageRanking,2.5); }
public void Details_Action_Should_Return_Correct_View_Model() { var agencyIndexServiceMock = new DynamicMock(typeof(IndexServiceAgencySolrImpl)); var publicationIndexServiceMock = new DynamicMock(typeof(IndexServicePublicationSolrImpl)); var agency = new Agency { Address = "Direccion", Name = "agencia prueba", UserId = 1 }; var agencysPublication1 = new Publication { VehicleMakeText = "Ford", UserUid = agency.UserId }; var agencysPublication2 = new Publication { VehicleMakeText = "Peugeot", UserUid = agency.UserId }; var listPublications = new List<Publication> { agencysPublication1, agencysPublication2 }; var listAgency = new List<Agency> { agency }; agencyIndexServiceMock.SetReturnValue("Query", listAgency); publicationIndexServiceMock.SetReturnValue("Query",listPublications); var agencyController = new AgencyController { AgencyIndexService = (IndexServiceAgencySolrImpl)agencyIndexServiceMock.MockInstance, PublicationIndexService = (IndexServicePublicationSolrImpl)publicationIndexServiceMock.MockInstance, }; var viewResult = agencyController.Details("abrahamautomotores"); Assert.IsNotNull(viewResult); Assert.NotNull(viewResult.ViewData["Title"]); Assert.True(viewResult.ViewData["Title"].ToString() == "Concesionaria abrahamautomotores"); Assert.NotNull(viewResult.ViewData["Publications"]); Assert.True(((List<Publication>)viewResult.ViewData["Publications"]).Count == listPublications.Count); Assert.True(((List<Publication>)viewResult.ViewData["Publications"])[0].VehicleMakeText == listPublications[0].VehicleMakeText); }
private StructureGroup GetSG(string sgWebDav, string Start_SG_Images, Publication pub, Engine engine) { String rootSGwebdav = pub.RootStructureGroup.WebDavUrl + "/" + Start_SG_Images + "/" + sgWebDav; StructureGroup result = engine.GetObject(rootSGwebdav) as StructureGroup; if (result == null) // SG not found, creating it { FindOrCreateSG(engine, rootSGwebdav); result = engine.GetObject(rootSGwebdav) as StructureGroup; } else { log.Debug(string.Format("SG '{0}' exists", rootSGwebdav)); } return result; }
public void AddPublisher(string[] topics, object o, EventInfo evt) { if (o == null) { throw new ArgumentNullException ("o"); } if (evt == null) { throw new ArgumentNullException ("evt"); } var pub = new Publication {Topics = topics, Broker = this}; var dg = Delegate.CreateDelegate (typeof(Action), pub, _pubmethod); evt.AddEventHandler (o, dg); }
public static void PingHandler(Publication pongPublication, IDirectBuffer buffer, int offset, int length) { if (pongPublication.Offer(buffer, offset, length) > 0L) { return; } PingHandlerIdleStrategy.Reset(); while (pongPublication.Offer(buffer, offset, length) < 0L) { PingHandlerIdleStrategy.Idle(); } }
protected override void OnInit(EventArgs e) { this._publication = Publication.Load(this.Key); if (this._publication == null) { this._publication = new Publication(new LinqPublication(this.Key)); this._publication.Title = this.Title; this._publication.Author = HttpContext.Current.User.Identity.Name; this._publication.Category = null; this._publication.Description = this.Description; this._publication.IsVisible = true; this._publication.RelativeLink = HttpContext.Current.Request.Url.ToString(); } }
public GeoLocation GetLocation(Publication publication, GeoLocation list) { list.Province = new Location(); list.Province.Id = publication.VehicleLocProv; list.Province.Name = publication.VehicleLocProvText; list.Partido = new Location(); list.Partido.Id = publication.VehicleLocPart; list.Partido.Name = publication.VehicleLocPartText; list.Localidad = new Location(); list.Localidad.Id = publication.VehicleLocLoc; list.Localidad.Name = publication.VehicleLocLocText; return list; }
/// <summary> /// Create and initialize a new InfoGrid /// </summary> /// <param name="pub">The publication to show</param> public InfoGrid(Publication pub) { publication = pub; Opacity = 0; Background = new SolidColorBrush(Color.FromArgb(200, 0, 0, 0)); SetupGrid(); AddCoverImage(); AddInfoPanel(); SetupInputPanel(); Loaded += AnimateIn; StylusSystemGesture += BackgroundGesture; }
public string GetMultimediaComponentUrl(Component component, string ROOT_WEBDAV_URL, string Start_SG_Images, Publication pub, Engine engine) { string sgLocation = ""; if (component.ComponentType.Equals(ComponentType.Multimedia)) { sgLocation = getStructureGroupLocation(component.WebDavUrl, ROOT_WEBDAV_URL); StructureGroup publishSG = GetSG(sgLocation, Start_SG_Images, pub, engine); if (publishSG != null) { if (!sgLocation.StartsWith("/")) { sgLocation = "/images/" + sgLocation; } else { sgLocation = "/images" + sgLocation; } sgLocation = sgLocation.Replace(" ", ""); sgLocation = sgLocation + "/" + component.BinaryContent.Filename; // Add Filename of SG } } return sgLocation; }
private static void RoundTripMessages(IMutableDirectBuffer buffer, FragmentHandler fragmentHandler, Publication publication, Subscription subscription, int count) { for (var i = 0; i < count; i++) { do { buffer.PutLong(0, Stopwatch.GetTimestamp()); } while (publication.Offer(buffer, 0, MessageLength) < 0L); PollingIdleStrategy.Reset(); while (subscription.Poll(fragmentHandler, FragmentCountLimit) <= 0) { PollingIdleStrategy.Idle(); } } }
protected void btnAltaAdv_Click(object sender, EventArgs e) { if (Page.IsValid && Page.IsPostBack) { String title = txtAdvTitulo.Text; String salary = txtAdvRemuneracion.Text; String description = txtAdvDescripcion.Text; if (!"".Equals(title) && !"".Equals(salary) && !"".Equals(description)) { Publication pub = new Publication(title, description, salary, DateTime.Now); pubDao.saveOrUpdate(pub); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "ShowModalPopup();", true); cleanFields(); } } }
internal static string GetSearchQueryUrl(Publication publication, string environmentPurpose) { string publicationId = publication.Id.ToString(); MappingData mapping = TopologyManagerClient.Mappings.Expand("CdEnvironment") .Where(m => m.PublicationId == publicationId && m.EnvironmentPurpose == environmentPurpose).FirstOrDefault(); if (mapping == null || mapping.CdEnvironment == null) { return null; } string dxaSearchQueryUrl = mapping.CdEnvironment.ExtensionProperties .Where(ep => ep.Name == "DXA.Search.QueryURL") .Select(ep => ep.Value) .FirstOrDefault(); return dxaSearchQueryUrl; }
/// <summary> /// Sends follow-up email to Library patron /// </summary> /// <param name="username">Bucknell username of patron</param> /// <param name="pub">Pulication instance to follow up</param> public static async void emailSend(string username, Publication pub) { var fromAddress = new MailAddress(Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailName); MailAddress toAddress; try { toAddress = new MailAddress(username + "@bucknell.edu", await getFullName(username)); } catch (Exception) { Console.WriteLine("Invalid username. Email not sent."); return; } string fromPassword = Properties.Settings.Default.MailPassword; string subject = "Here is your eBook!: " + pub.Title; MemoryStream str = new MemoryStream(); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(pub.CoverImage)); encoder.Save(str); str.Position = 0; var coverInline = new LinkedResource(str, "image/png"); string body = getMessageBody(await getFirstName(username), pub, coverInline); var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, IsBodyHtml = true }) { try { var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); view.LinkedResources.Add(coverInline); message.AlternateViews.Add(view); await smtp.SendMailAsync(message); Console.WriteLine("Sent to " + toAddress); } catch (Exception e) { Console.WriteLine("Error: " + e); } } }
public string BuildFor(Publication publication) { var seoSection = string.Format("{0}-{1}-{2}-{3}-{4}", publication.VehicleMakeText, publication.VehicleModelText, publication.VehicleLocPartText, publication.VehicleSegmentText, publication.VehicleFuelTypeText); seoSection = seoSection.Replace("/","-").Replace(" ","-"); string url; if(publication.VehicleType==2) url = BaseUrl + UrlPartForVehicleType(publication.VehicleType) + seoSection + "/" + publication.PublicationId; else url = BaseUrl + UrlPartForVehicleType(publication.VehicleType) + seoSection + "/" + publication.VehicleYear + "_" + publication.PublicationId; return url.Replace(" ", "-").Replace("--", "-"); }
public void BuildSearchUrlFor_Should_Return_SearchUrlFormatText() { var publication = new Publication { VehicleMakeText = "Volkswagen", VehicleModelText = "Gol", VehicleMake = 395, VehicleModel = 1950, PublicationVisitorsQty = 998, VehicleType = 1 }; var detailUrlBuilder = new DetailUrlBuilder { UrlOfuscator = new OfuscatorStub() }; Assert.AreEqual("autos-usados-volkswagen/VTYY1WWMAYY395WWMOYY1950",detailUrlBuilder.BuildSearchUrlFor(publication)); }
/// <summary> /// Create and initialize a new PublicationCanvas /// </summary> /// <param name="pubs">The publications to display on the screen</param> /// <param name="height">The height of the canvas</param> public PublicationCanvas(Publication[] pubs, double height) { // map Image objects to Publications publications = pubs.ToDictionary( p => new Image() { Source = p.CoverImage, Height = height, RenderTransform = new TranslateTransform(), }, p => p ); images = publications.Keys.ToArray(); positions = new double[images.Length]; // shift entire display 500px left RenderTransform = new TranslateTransform() { X = RENDER_TRANSFORM }; // initially layout images tileWidth = 0; for (int i = 0; i < images.Length; i++) { var image = images[i]; positions[i] = tileWidth; Children.Add(image); image.StylusSystemGesture += ImageTapped; tileWidth += (int)((image.Height / image.Source.Height) * image.Source.Width); } // allow multitouch manipulation IsManipulationEnabled = true; ManipulationStarting += BeginManipulation; ManipulationDelta += HandleManipulation; ManipulationInertiaStarting += BeginInertia; ManipulationCompleted += EndManipulation; // register UI scroll at 60fps timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1.0 / 60.0) }; timer.Tick += delegate { ScrollImagesBy(RESTING_VELOCITY); }; Loaded += delegate { timer.Start(); }; }
private Dictionary<string, ItemData> GetPublicationData(Publication publication, string trafficTag, string trafficTagName) { return new Dictionary<string, ItemData> { {"PUBLICATION_DATA_ID",new ItemData(publication.PublicationId.ToString(),typeof(int).Name) }, {"PUBLICATION_DATA_PUBLICATION_URL",new ItemData(publication.UrlDetails + (string.IsNullOrEmpty(trafficTag)?string.Empty:"#" + trafficTagName + "=" + trafficTag),typeof(string).Name) }, {"PUBLICATION_DATA_HIGHLIGHT",new ItemData(publication.PublicationHighLight,typeof(string).Name) }, {"PUBLICATION_DATA_SORT_WEIGHT",new ItemData(publication.IndexWeight.ToString(),typeof(string).Name) }, {"PUBLICATION_DATA_STATE",new ItemData(publication.PublicationDeleted?"Finalizada":"Active",typeof(string).Name) }, {"PUBLICATION_DATA_START_DATE",new ItemData(publication.PublicationStartDate.ToShortDateString(),typeof(DateTime).Name) }, {"PUBLICATION_DATA_END_DATE",new ItemData(publication.PublicationEndDate.ToShortDateString(),typeof(DateTime).Name) }, {"PUBLICATION_DATA_EXPIRATION_DATE",new ItemData(publication.PublicationEndDate.ToShortDateString(),typeof(DateTime).Name) },//expiration date {"PUBLICATION_DATA_VISITS_QUANTITY",new ItemData(publication.PublicationVisitorsQty.ToString(),typeof(int).Name) }, {"PUBLICATION_DATA_SHOW_CONTACTS_COUNTER_IN_SEARCH_RESULTS",new ItemData(true.ToString(),typeof(bool).Name) }, {"PUBLICATION_DATA_SHOW_VISITS_COUNTER_IN_SEARCH_RESULTS",new ItemData(true.ToString(),typeof(bool).Name) }, {"PUBLICATION_DATA_SHOW_CLICK_TO_CALL_LOGO_IN_SEARCH_RESULTS",new ItemData(false.ToString(),typeof(bool).Name) }, {"PUBLICATION_DATA_TITLE",new ItemData(publication.PublicationSubtitle==null?String.Empty:publication.PublicationSubtitle,typeof(string).Name) }, //{"PUBLICATION_DATA_SUBTITLE",new ItemData(publication.PublicationSubtitle,typeof(string).Name) } }; }
public void SetUp() { _sendBuffer = new byte[SendBufferCapacity]; _atomicSendBuffer = new UnsafeBuffer(_sendBuffer); _logMetaDataBuffer = new UnsafeBuffer(new byte[LogBufferDescriptor.LOG_META_DATA_LENGTH]); _termBuffers = new UnsafeBuffer[LogBufferDescriptor.PARTITION_COUNT]; _termMetaDataBuffers = new UnsafeBuffer[LogBufferDescriptor.PARTITION_COUNT]; _buffers = new UnsafeBuffer[LogBufferDescriptor.PARTITION_COUNT*2 + 1]; _conductor = A.Fake<ClientConductor>(); _logBuffers = A.Fake<LogBuffers>(); _publicationLimit = A.Fake<IReadablePosition>(); A.CallTo(() => _publicationLimit.Volatile).Returns(2*SendBufferCapacity); A.CallTo(() => _logBuffers.AtomicBuffers()).Returns(_buffers); A.CallTo(() => _logBuffers.TermLength()).Returns(LogBufferDescriptor.TERM_MIN_LENGTH); LogBufferDescriptor.InitialTermId(_logMetaDataBuffer, TermID1); LogBufferDescriptor.TimeOfLastStatusMessage(_logMetaDataBuffer, 0); for (var i = 0; i < LogBufferDescriptor.PARTITION_COUNT; i++) { _termBuffers[i] = new UnsafeBuffer(new byte[LogBufferDescriptor.TERM_MIN_LENGTH]); _termMetaDataBuffers[i] = new UnsafeBuffer(new byte[LogBufferDescriptor.TERM_META_DATA_LENGTH]); _buffers[i] = _termBuffers[i]; _buffers[i + LogBufferDescriptor.PARTITION_COUNT] = _termMetaDataBuffers[i]; } _buffers[LogBufferDescriptor.LOG_META_DATA_SECTION_INDEX] = _logMetaDataBuffer; _publication = new Publication(_conductor, Channel, StreamID1, SessionID1, _publicationLimit, _logBuffers, CorrelationID); _publication.IncRef(); LogBufferDescriptor.InitialiseTailWithTermId(_termMetaDataBuffers[0], TermID1); }
public override void Setup() { base.Setup(); publication = CreatePublication(); }
public void AddUserReleaseRole() { PolicyCheckBuilder() .ExpectCheck(SecurityPolicies.CanManageUsersOnSystem) .AssertSuccess(async userService => { var contentDbContextId = Guid.NewGuid().ToString(); var publication = new Publication { Id = Guid.NewGuid(), Title = "Test Publication" }; var release = new Release { Id = Guid.NewGuid(), TimePeriodCoverage = TimeIdentifier.CalendarYear, ReleaseName = "2000", PublicationId = publication.Id, Publication = publication }; var user = new User { Id = Guid.NewGuid(), FirstName = "TestFirstName", LastName = "TestLastName", Email = "*****@*****.**" }; var userReleaseRoleRequest = new UserReleaseRoleRequest { ReleaseId = release.Id, ReleaseRole = ReleaseRole.Approver }; await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(publication); await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(user); await contentDbContext.SaveChangesAsync(); } var userAndRolesContextId = Guid.NewGuid().ToString(); var appUser = new ApplicationUser { Id = user.Id.ToString(), FirstName = user.FirstName, LastName = user.LastName, Email = user.Email }; await using (var userAndRolesDbContext = InMemoryUserAndRolesDbContext(userAndRolesContextId)) { await userAndRolesDbContext.AddAsync(appUser); await userAndRolesDbContext.SaveChangesAsync(); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) await using (var usersAndRolesDbContext = InMemoryUserAndRolesDbContext(userAndRolesContextId)) { var persistenceHelper = MockPersistenceHelper <ContentDbContext>(); SetupCall(persistenceHelper, release.Id, release); var userManagementService = BuildUserManagementService( usersAndRolesDbContext, userService.Object, contentDbContext, persistenceHelper: persistenceHelper.Object ); return(await userManagementService.AddUserReleaseRole(user.Id, userReleaseRoleRequest)); } }); }
public ConsensusModuleProxy(Publication publication) { _publication = publication; }
private static async Task <AuthorSearchResult> GetProfileFromLink(string link, List <string> possibleOrganizations) { using (var client = new HttpClient()) { var htmlCode = await client.GetStringAsync(link); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(htmlCode); // Parse information about the profile. var name = WebUtility.HtmlDecode(htmlDocument.GetElementbyId("gsc_prf_in").InnerText); if (ProfilesToIgnoreWithWords.Any(w => name.ToLower().Contains(w.ToLower()))) { return(null); } var organizationInProfile = WebUtility.HtmlDecode(htmlDocument.DocumentNode.Descendants().Where(o => o.GetAttributeValue("class", "") == "gsc_prf_il").ElementAt(0).InnerText); if (possibleOrganizations.Count > 0 && !possibleOrganizations.Any(po => organizationInProfile.ToLower().Contains(po.ToLower()))) { return(null); } var hIndex = htmlDocument.DocumentNode.Descendants().Where(o => o.GetAttributeValue("class", "") == "gsc_rsb_std").ElementAt(2).InnerText; var field = string.Empty; var fieldNodes = htmlDocument.DocumentNode.Descendants().Where(o => o.GetAttributeValue("class", "") == "gsc_prf_ila"); if (fieldNodes != null) { for (var i = 0; i < fieldNodes.Count(); i++) { field += WebUtility.HtmlDecode(fieldNodes.ElementAt(i).InnerText); if (i != fieldNodes.Count() - 1) { field += ", "; } } } var publications = new List <Publication>(); var publicationsBodyNode = htmlDocument.DocumentNode.SelectSingleNode("//tbody[@id='gsc_a_b']"); if (publicationsBodyNode != null) { foreach (var publicationNode in publicationsBodyNode.ChildNodes) { var publication = new Publication(); var publicationNameNode = publicationNode.ChildNodes[0]; if (publicationNameNode != null && publicationNameNode.ChildNodes.Count >= 3) { var publicationName = WebUtility.HtmlDecode(publicationNameNode.ChildNodes[0].InnerText); var index1 = publicationName.IndexOf(" doi"); var index2 = publicationName.IndexOf(" dx.doi"); if (index1 >= 0) { publication.Name = publicationName.Substring(0, index1).Replace("=", "").Trim(); } else if (index2 >= 0) { publication.Name = publicationName.Substring(0, index2).Replace("=", "").Trim(); } else { publication.Name = publicationName.Trim(); } publication.Authors = WebUtility.HtmlDecode(publicationNameNode.ChildNodes[1].InnerText); publication.Journal = WebUtility.HtmlDecode(publicationNameNode.ChildNodes[2].InnerText); } var publicationYearNode = publicationNode.ChildNodes[2]; if (publicationYearNode != null) { Int32.TryParse(publicationYearNode.InnerText, out int year); publication.Year = year; } publications.Add(publication); } } var orderedPublications = publications.OrderByDescending(p => p.Year).ToList(); return(new AuthorSearchResult { NameSurname = name, HIndex = int.Parse(hIndex), Organization = organizationInProfile, Field = field, Link = link, Publications = orderedPublications }); } }
public async Task NotifySubscribersIfApplicable() { var release1 = new Release { Id = Guid.NewGuid(), ReleaseName = "2000", TimePeriodCoverage = TimeIdentifier.AcademicYear, Slug = "2000-01", Version = 0, Publication = new Publication { Id = Guid.NewGuid(), Title = "pub1 title", Slug = "pub1-slug", }, ReleaseStatuses = new List <ReleaseStatus> { new() { Id = Guid.NewGuid(), ApprovalStatus = ReleaseApprovalStatus.Approved, Created = DateTime.UtcNow, NotifySubscribers = true, }, new() { Id = Guid.NewGuid(), ApprovalStatus = ReleaseApprovalStatus.Draft, Created = DateTime.UtcNow.AddDays(-1), NotifySubscribers = false, }, }, }; var release2 = new Release { Id = Guid.NewGuid(), ReleaseName = "2001", TimePeriodCoverage = TimeIdentifier.AcademicYear, Slug = "2001-02", Version = 0, Publication = new Publication { Id = Guid.NewGuid(), Title = "pub2 title", Slug = "pub2-slug", }, ReleaseStatuses = new List <ReleaseStatus> { new() { Id = Guid.NewGuid(), ApprovalStatus = ReleaseApprovalStatus.Approved, Created = DateTime.UtcNow, NotifySubscribers = false, }, }, }; var amendedRelease1 = new Release { Id = Guid.NewGuid(), ReleaseName = "2002", TimePeriodCoverage = TimeIdentifier.AcademicYear, Slug = "2002-03", Version = 1, Publication = new Publication { Id = Guid.NewGuid(), Title = "pub3 title", Slug = "pub3-slug", }, ReleaseStatuses = new List <ReleaseStatus> { new() { Id = Guid.NewGuid(), ApprovalStatus = ReleaseApprovalStatus.Approved, Created = DateTime.UtcNow, NotifySubscribers = true, }, },
private static void AddSpecial2(ApiDbContext db, PublicationType[] types, Subject[] subjects) { var author1 = new Author { FirstName = "Zaphod", LastName = "Beeblebrox", DateOfBirth = DateTime.Parse("1501-04-14"), Publications = new List <Publication>() }; var author2 = new Author { FirstName = "Ford", LastName = "Prefect", DateOfBirth = DateTime.Parse("1501-06-04"), Publications = new List <Publication>() }; var book1 = new Publication { Title = "How to get elected the President of the Galaxy", Description = "A fascinating autobiography of the most (in)famous president of the Galaxy", PublicationDate = DateTime.Parse("1600-06-18"), Level = DifficultyLevel.Beginner, Type = types[0], TypeId = types[0].Id, Subject = subjects.Last(), SubjectId = subjects.Last().Id, Authors = new List <Author>() }; var book2 = new Publication { Title = "An interstellar tourist's guide to Earth: Hitchhiker's companion", Description = "Best bars, best clubs, best ways to blend in with the locals -- an indispensable help to any serious interstellar hitchhiker!", PublicationDate = DateTime.Parse("1560-01-18"), Level = DifficultyLevel.Beginner, Type = types[0], TypeId = types[0].Id, Subject = subjects.Last(), SubjectId = subjects.Last().Id, Authors = new List <Author>() }; var book3 = new Publication { Title = "Best restaurants at the end of the Universe", Description = "Account of a first-hand experience at the Milliways", PublicationDate = DateTime.Parse("1990-01-18"), Level = DifficultyLevel.Beginner, Type = types[0], TypeId = types[0].Id, Subject = subjects.Last(), SubjectId = subjects.Last().Id, Authors = new List <Author>() }; author1.Publications.Add(book1); book1.Authors.Add(author1); author2.Publications.Add(book2); book2.Authors.Add(author2); author2.Publications.Add(book3); book3.Authors.Add(author2); db.Authors.AddRange(author1, author2); db.Publications.AddRange(book1, book2, book3); }
public void ReportServiceTest_CreateViewModel() { List <Author> authors = new List <Author>(); var author = new Author { Name = "Began", Id = 1, }; authors.Add(author); var pb = new Publication() { Id = 1, Authors = authors, Topic = "Newton", Status = "closed", Type = "math", Date = new DateTime(2019, 8, 1), }; var testarray = new List <Publication>() { pb }; var dbSetMock = new Mock <DbSet <Publication> >(); dbSetMock.As <IQueryable <Publication> >().Setup(x => x.Provider).Returns(testarray.AsQueryable().Provider); dbSetMock.As <IQueryable <Publication> >().Setup(x => x.Expression).Returns(testarray.AsQueryable().Expression); dbSetMock.As <IQueryable <Publication> >().Setup(x => x.ElementType).Returns(testarray.AsQueryable().ElementType); dbSetMock.As <IQueryable <Publication> >().Setup(x => x.GetEnumerator()).Returns(testarray.AsQueryable().GetEnumerator()); var context = new Mock <DbContext>(); context.Setup(x => x.Set <Publication>()).Returns(dbSetMock.Object); // Act var repository = new Repository <Publication, int>(context.Object); var result = repository.GetAll(); //Arrange var gr = new Grant { Id = 1, Participants = authors, Name = "Newton", Description = "Algebra", }; var testList = new List <Grant>() { gr }; var dbSetMock1 = new Mock <DbSet <Grant> >(); dbSetMock1.As <IQueryable <Grant> >().Setup(x => x.Provider).Returns(testList.AsQueryable().Provider); dbSetMock1.As <IQueryable <Grant> >().Setup(x => x.Expression).Returns(testList.AsQueryable().Expression); dbSetMock1.As <IQueryable <Grant> >().Setup(x => x.ElementType).Returns(testList.AsQueryable().ElementType); dbSetMock1.As <IQueryable <Grant> >().Setup(x => x.GetEnumerator()).Returns(testList.AsQueryable().GetEnumerator()); var context1 = new Mock <DbContext>(); context1.Setup(x => x.Set <Grant>()).Returns(dbSetMock1.Object); // Act var repository1 = new Repository <Grant, int>(context1.Object); var result1 = repository1.GetAll(); var dw = new DepartmentWork { Id = 1, Authors = authors, Category = "Math", Content = "Algebra", Intro = "hello", Topic = "Equations" }; var testList1 = new List <DepartmentWork>() { dw }; var dbSetMock2 = new Mock <DbSet <DepartmentWork> >(); dbSetMock2.As <IQueryable <DepartmentWork> >().Setup(x => x.Provider).Returns(testList1.AsQueryable().Provider); dbSetMock2.As <IQueryable <DepartmentWork> >().Setup(x => x.Expression).Returns(testList1.AsQueryable().Expression); dbSetMock2.As <IQueryable <DepartmentWork> >().Setup(x => x.ElementType).Returns(testList1.AsQueryable().ElementType); dbSetMock2.As <IQueryable <DepartmentWork> >().Setup(x => x.GetEnumerator()).Returns(testList1.AsQueryable().GetEnumerator()); var context2 = new Mock <DbContext>(); context2.Setup(x => x.Set <DepartmentWork>()).Returns(dbSetMock2.Object); // Act var repository2 = new Repository <DepartmentWork, int>(context2.Object); var result2 = repository2.GetAll(); var Conf = new Conference { Date = new DateTime(2008, 3, 1, 7, 0, 0), Id = 1, Description = "sad", ImgPath = "sss", Likes = 145, Title = "Math", Watches = 300, Participants = authors, }; var testList2 = new List <Conference>() { Conf }; var dbSetMock3 = new Mock <DbSet <Conference> >(); dbSetMock3.As <IQueryable <Conference> >().Setup(x => x.Provider).Returns(testList2.AsQueryable().Provider); dbSetMock3.As <IQueryable <Conference> >().Setup(x => x.Expression).Returns(testList2.AsQueryable().Expression); dbSetMock3.As <IQueryable <Conference> >().Setup(x => x.ElementType).Returns(testList2.AsQueryable().ElementType); dbSetMock3.As <IQueryable <Conference> >().Setup(x => x.GetEnumerator()).Returns(testList2.AsQueryable().GetEnumerator()); var context3 = new Mock <DbContext>(); context3.Setup(x => x.Set <Conference>()).Returns(dbSetMock3.Object); // Act var repository3 = new Repository <Conference, int>(context3.Object); var result3 = repository3.GetAll(); var repo = new ScientificReportData.Models.Report { Id = 1, Date = new DateTime(1999, 12, 1), DepartmentWork = "AMI", Conferences = "none", Contetnt = "smth", Intro = "Begin" }; List <Report> reports = new List <Report>(); reports.Add(repo); authors.Add(author); var publication = new Publication { Status = "prove", Authors = authors, Id = 1, Date = new DateTime(2009, 12, 1), Topic = "sfs", Type = "math" }; List <Publication> publications = new List <Publication>(); publications.Add(publication); var internship = new Internship { Name = "mine", Id = 1 }; List <Internship> internships = new List <Internship>(); internships.Add(internship); var user = new ScientificReportData.Models.User { Name = "ME", Birthdate = new DateTime(1992, 1, 12), DegreeLevel = "BACHELOR", DegreeDate = new DateTime(2010, 1, 12), GraduationDate = new DateTime(2011, 1, 12), Title = "124rs", TitleDate = new DateTime(2016, 1, 12), Faculty = "AMI", Department = "AM", IsAdmin = false, IsApproved = true, Reports = reports, Publications = publications, Internships = internships, }; var Curuser = new ScientificReportData.Models.User { Name = "NOTME", Birthdate = new DateTime(1992, 1, 12), DegreeLevel = "BACHELOR", DegreeDate = new DateTime(2010, 1, 12), GraduationDate = new DateTime(2011, 1, 12), Title = "124rs", TitleDate = new DateTime(2016, 1, 12), Faculty = "AMI", Department = "AM", IsAdmin = false, IsApproved = true, Reports = reports, Publications = publications, Internships = internships, }; var publicationres = result.Where(p => p.Authors.Any(a => a.Name == user.Name))?.ToList(); var grantsres = result1.Where(p => p.Participants.Any(a => a.Name == user.Name))?.ToList(); var depWorksres = result2.Where(p => p.Authors.Any(a => a.Name == user.Name))?.ToList(); var conferencesres = result3.Where(p => p.Participants.Any(a => a.Name == user.Name))?.ToList(); var resulting = new ReportViewModel { User = user, Publications = publicationres ?? new List <Publication>(), DepartmentWorks = depWorksres ?? new List <DepartmentWork>(), Conferences = conferencesres ?? new List <Conference>(), Grants = grantsres ?? new List <Grant>() }; using (var mack = AutoMock.GetLoose()) { //Arrange mack.Mock <IReportService>() .Setup(x => x.CreateViewModel(user, DateTime.MinValue, DateTime.MaxValue)) .Returns(GetSampleViewModel(resulting)); //Act var cls = mack.Create <IReportService>(); var expected = GetSampleViewModel(resulting); var actual = cls.CreateViewModel(user, DateTime.MinValue, DateTime.MaxValue); //Assert Assert.AreEqual(actual, expected); }; }
public void ReportServiceTest_CreateReport() { //Arrange List <Author> authors1 = new List <Author>(); var author1 = new Author { Name = "Bogdan", Id = 1, }; authors1.Add(author1); var dw = new DepartmentWork { Id = 1, Authors = authors1, Category = "Math", Content = "Algebra", Intro = "hello", Topic = "Equations" }; var testList = new List <DepartmentWork>() { dw }; var dbSetMock1 = new Mock <DbSet <DepartmentWork> >(); dbSetMock1.As <IQueryable <DepartmentWork> >().Setup(x => x.Provider).Returns(testList.AsQueryable().Provider); dbSetMock1.As <IQueryable <DepartmentWork> >().Setup(x => x.Expression).Returns(testList.AsQueryable().Expression); dbSetMock1.As <IQueryable <DepartmentWork> >().Setup(x => x.ElementType).Returns(testList.AsQueryable().ElementType); dbSetMock1.As <IQueryable <DepartmentWork> >().Setup(x => x.GetEnumerator()).Returns(testList.AsQueryable().GetEnumerator()); var context1 = new Mock <DbContext>(); context1.Setup(x => x.Set <DepartmentWork>()).Returns(dbSetMock1.Object); // Act var repository1 = new Repository <DepartmentWork, int>(context1.Object); var result1 = repository1.GetAll(); List <Author> authors2 = new List <Author>(); var author2 = new Author { Name = "Bogdan", Id = 1, }; authors2.Add(author2); var gr = new Grant { Id = 1, Participants = authors2, Name = "Newton", Description = "Algebra", }; var testList2 = new List <Grant>() { gr }; var dbSetMock2 = new Mock <DbSet <Author> >(); dbSetMock2.As <IQueryable <Author> >().Setup(x => x.Provider).Returns(authors2.AsQueryable().Provider); dbSetMock2.As <IQueryable <Author> >().Setup(x => x.Expression).Returns(authors2.AsQueryable().Expression); dbSetMock2.As <IQueryable <Author> >().Setup(x => x.ElementType).Returns(authors2.AsQueryable().ElementType); dbSetMock2.As <IQueryable <Author> >().Setup(x => x.GetEnumerator()).Returns(authors2.AsQueryable().GetEnumerator()); var context2 = new Mock <DbContext>(); context2.Setup(x => x.Set <Author>()).Returns(dbSetMock2.Object); // Act var repository2 = new Repository <Author, int>(context2.Object); var result2 = repository2.GetAll(); var repo = new ScientificReportData.Models.Report { Id = 1, Date = new DateTime(1999, 12, 1), DepartmentWork = "AMI", Conferences = "none", Contetnt = "smth", Intro = "Begin" }; List <Report> reports = new List <Report>(); reports.Add(repo); List <Author> authors = new List <Author>(); var author = new Author { Name = "Bogdan", Id = 1, }; authors.Add(author); var publication = new Publication { Status = "prove", Authors = authors, Id = 1, Date = new DateTime(2009, 12, 1), Topic = "sfs", Type = "math" }; List <Publication> publications = new List <Publication>(); publications.Add(publication); var internship = new Internship { Name = "mine", Id = 1 }; List <Internship> internships = new List <Internship>(); internships.Add(internship); var user = new ScientificReportData.Models.User { Name = "ME", Birthdate = new DateTime(1992, 1, 12), DegreeLevel = "BACHELOR", DegreeDate = new DateTime(2010, 1, 12), GraduationDate = new DateTime(2011, 1, 12), Title = "124rs", TitleDate = new DateTime(2016, 1, 12), Faculty = "AMI", Department = "AM", IsAdmin = false, IsApproved = true, Reports = reports, Publications = publications, Internships = internships, }; var testarray = new List <User>() { user }; //var testarray = new List<Publication>() { pb }; var intro = new StringBuilder(); intro.Append( $"Рік народження: {user.Birthdate.Year}") .Append(Environment.NewLine) .Append($"Рік закінчення ВНЗ {user.GraduationDate}").Append(Environment.NewLine) .Append($"Науковий ступінь: {user.DegreeLevel} рік захисту {user.DegreeDate.Year}") .Append(Environment.NewLine) .Append($"Вчене звання: {user.Title} рік присвоєння {user.TitleDate.Year}" ); var userAsAuthor = repository2.GetAll().FirstOrDefault(a => a.Name == user.Name); var works = repository1.GetAll().Where(w => w.Authors.Contains(userAsAuthor)); var section = new StringBuilder(); foreach (var work in works) { section.Append($"Teмa: {work.Topic}, {work.Category}, {work.Intro}") .Append(Environment.NewLine) .Append(Environment.NewLine) .Append(work.Content) .Append(Environment.NewLine) .Append(Environment.NewLine); } var report = new Report { Date = DateTime.Today.Date, Intro = intro.ToString(), DepartmentWork = section.ToString(), }; var testarray1 = new List <Report>() { report }; var dbSetMock = new Mock <DbSet <Report> >(); dbSetMock.As <IQueryable <Report> >().Setup(x => x.Provider).Returns(testarray1.AsQueryable().Provider); dbSetMock.As <IQueryable <Report> >().Setup(x => x.Expression).Returns(testarray1.AsQueryable().Expression); dbSetMock.As <IQueryable <Report> >().Setup(x => x.ElementType).Returns(testarray1.AsQueryable().ElementType); dbSetMock.As <IQueryable <Report> >().Setup(x => x.GetEnumerator()).Returns(testarray1.AsQueryable().GetEnumerator()); var context = new Mock <DbContext>(); context.Setup(x => x.Set <Report>()).Returns(dbSetMock.Object); // Act var repository = new Repository <Report, int>(context.Object); var result = repository.GetAll(); // Assert Assert.AreEqual(report, result.ToList()[0]); }
/// <summary> /// Create a proxy with a <seealso cref="Publication"/> for sending control message requests. /// <para> /// This provides a default <seealso cref="IIdleStrategy"/> of a <seealso cref="YieldingIdleStrategy"/> when offers are back pressured /// with a defaults of <seealso cref="AeronArchive.Configuration.MESSAGE_TIMEOUT_DEFAULT_NS"/> and /// <seealso cref="DEFAULT_RETRY_ATTEMPTS"/>. /// /// </para> /// </summary> /// <param name="publication"> publication for sending control messages to an archive. </param> public ArchiveProxy(Publication publication) : this(publication, new YieldingIdleStrategy(), new SystemNanoClock(), AeronArchive.Configuration.MESSAGE_TIMEOUT_DEFAULT_NS, DEFAULT_RETRY_ATTEMPTS) { }
public async Task Query_LatestRelease() { var publication = new Publication { Id = Guid.NewGuid(), }; var release = new Release { PublicationId = publication.Id, Publication = publication, }; var releaseSubject = new ReleaseSubject { Release = release, Subject = new Subject { Id = Guid.NewGuid() } }; var indicator1Id = Guid.NewGuid(); var indicator2Id = Guid.NewGuid(); var query = new ObservationQueryContext { SubjectId = releaseSubject.Subject.Id, Indicators = new[] { indicator1Id, indicator2Id, }, Locations = new LocationQuery { Country = new[] { "england" } }, TimePeriod = new TimePeriodQuery { StartYear = 2019, StartCode = TimeIdentifier.AcademicYear, EndYear = 2020, EndCode = TimeIdentifier.AcademicYear, } }; var contextId = Guid.NewGuid().ToString(); await using (var statisticsDbContext = StatisticsDbUtils.InMemoryStatisticsDbContext(contextId)) { await statisticsDbContext.AddAsync(releaseSubject); await statisticsDbContext.SaveChangesAsync(); } await using (var statisticsDbContext = StatisticsDbUtils.InMemoryStatisticsDbContext(contextId)) { var observations = new List <Observation> { new Observation { Measures = new Dictionary <Guid, string> { { indicator1Id, "123" }, { indicator2Id, "456" }, }, FilterItems = new List <ObservationFilterItem>(), Year = 2019, TimeIdentifier = TimeIdentifier.AcademicYear, }, new Observation { Measures = new Dictionary <Guid, string> { { indicator1Id, "789" }, { Guid.NewGuid(), "1123" }, { Guid.NewGuid(), "1456" }, }, FilterItems = new List <ObservationFilterItem>(), Year = 2020, TimeIdentifier = TimeIdentifier.AcademicYear, }, }; var subjectMeta = new ResultSubjectMetaViewModel { Indicators = new List <IndicatorMetaViewModel> { new IndicatorMetaViewModel { Label = "Test indicator" } }, }; var observationService = new Mock <IObservationService>(); observationService .Setup(s => s.FindObservations(query)) .Returns(observations); var resultSubjectMetaService = new Mock <IResultSubjectMetaService>(); resultSubjectMetaService .Setup( s => s.GetSubjectMeta( release.Id, It.IsAny <SubjectMetaQueryContext>(), It.IsAny <IQueryable <Observation> >() ) ) .ReturnsAsync(subjectMeta); var subjectService = new Mock <ISubjectService>(); subjectService .Setup(s => s.GetPublicationForSubject(query.SubjectId)) .ReturnsAsync(publication); subjectService .Setup(s => s.IsSubjectForLatestPublishedRelease(query.SubjectId)) .ReturnsAsync(true); var releaseService = new Mock <IReleaseService>(); releaseService .Setup(s => s.GetLatestPublishedRelease(publication.Id)) .Returns(release); var service = BuildTableBuilderService( statisticsDbContext, observationService: observationService.Object, resultSubjectMetaService: resultSubjectMetaService.Object, subjectService: subjectService.Object, releaseService: releaseService.Object ); var result = await service.Query(query); Assert.True(result.IsRight); var observationResults = result.Right.Results.ToList(); Assert.Equal(2, observationResults.Count); Assert.Equal("2019_AY", observationResults[0].TimePeriod); Assert.Equal(2, observationResults[0].Measures.Count); Assert.Equal("123", observationResults[0].Measures[indicator1Id.ToString()]); Assert.Equal("456", observationResults[0].Measures[indicator2Id.ToString()]); Assert.Equal("2020_AY", observationResults[1].TimePeriod); Assert.Single(observationResults[1].Measures); Assert.Equal("789", observationResults[1].Measures[indicator1Id.ToString()]); Assert.Equal(subjectMeta, result.Right.SubjectMeta); MockUtils.VerifyAllMocks(observationService, resultSubjectMetaService, subjectService, releaseService); } }
protected bool Equals(Publication other) { return string.Equals(Name.ToUpperInvariant(), other.Name.ToUpperInvariant()); }
public ActionResult AddReview(ReviewViewModel model) { if (ModelState.IsValid && model.File != null && model.pubId > 0) { using (DataContext ctx = new DataContext()) { //Review review = new Review(); IUserService userService = new UserService(); string userId = User.Identity.GetUserId(); User currentUser = ctx.Users.Where(u => u.Id == userId).FirstOrDefault(); var revId = from Review rev in ctx.Reviews where rev.PublicationId == model.pubId && rev.UserId == userId select rev.ReviewId; int reviewId = revId.First(); Review review = ctx.Reviews.Find(reviewId); Publication pub = ctx.Publications.Find(model.pubId); //ReviewState state = ctx.ReviewStates.Where(s => s.Name == "Przydzielony").FirstOrDefault(); //review.CurrentState = state; //File string filePath = Server.MapPath("~/Reviews/"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string fileName = model.File.FileName; fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1); model.File.SaveAs(filePath + fileName); Data.Model.File file = new Data.Model.File() { Name = fileName, Link_source = filePath + fileName, IsCurrent = true, Review = review }; ctx.Files.Add(file); //var original = ctx.Reviews.Find(review); if (review != null) { //review.User = currentUser; //DateTime date = DateTime.Now; //review.Creation_date = date; //date = date.AddDays(14); //review.Expiration_date = date; //review.PublicationId = model.pubId; //review.Publication = pub; review.Files.Add(file); review.CurrentStateId = 2; //ctx.SaveChanges(); } //currentUser.Reviews.Add(review); //ctx.Reviews.Add(review); var fId = from Data.Model.File f in ctx.Files where f.ReviewId == reviewId select f.FileId; if (fId.FirstOrDefault() != default(int)) { int fileId = fId.First(); Data.Model.File fileCheck = ctx.Files.Find(fileId); if (fileCheck != null) { ReviewStateHistory stateHistory = new ReviewStateHistory(); stateHistory.ChangeDate = DateTime.Now; stateHistory.StateId = review.CurrentStateId; stateHistory.ReviewId = reviewId; ctx.ReviewStateHistory.Add(stateHistory); } } var fileOldId = from Data.Model.File f in ctx.Files where f.ReviewId == reviewId && f.IsCurrent == true select f.FileId; if (fileOldId.FirstOrDefault() != default(int)) { Data.Model.File fileOld = ctx.Files.Find(fileOldId.First()); fileOld.IsCurrent = false; } review.Publication = pub; pub.Reviews.Add(review); //Tu moze byc problem //ctx.Entry(pub).State = EntityState.Modified; //ctx.Entry(pub.Reviews).State = EntityState.Modified; ctx.SaveChanges(); return(RedirectToAction("Index")); } } return(View(model)); }
public void TestRelatedPublications() { Assert.Ignore(); string query = "place name is the default query"; Place place = new Place(); place.Name = query; Publication[] publications = new Publication[3]; for (int i = 0; i < publications.Length; i++) { publications[i] = new Publication(); publications[i].Title = "Publication where " + query + ": #" + i.ToString(); publications[i].CreateAndFlush(); } Assert.AreEqual(publications.Length, place.RelatedPublications.Count); }
private Dictionary<string, ItemData> GetUserData(Publication publication) { return new Dictionary<string, ItemData> { {"USER_DATA_USER_ID",new ItemData(publication.UserUid.ToString(),typeof(int).Name) }, {"USER_DATA_USER_TYPE_ID",new ItemData(publication.UserType,typeof(string).Name) }, {"USER_DATA_USER_TYPE_DESCRIPTION",new ItemData(publication.UserType=="1"?"AgencyUser":"******",typeof(string).Name) }, {"USER_DATA_BRAND_NAME",new ItemData(publication.UserDescription, typeof(string).Name)}, {"USER_DATA_CONTACT_NAME",new ItemData(publication.UserDescription, typeof(string).Name)}, {"USER_DATA_CONTACT_LASTNAME",new ItemData(publication.UserDescription, typeof(string).Name)}, {"USER_DATA_CONTACT_EMAIL",new ItemData(publication.UserEmail, typeof(string).Name)}, {"USER_DATA_PRIMARY_PHONE",new ItemData(publication.UserPhone, typeof(string).Name)}, {"USER_DATA_SECONDARY_PHONE",new ItemData(publication.UserPhone, typeof(string).Name)},//no esta en el soler. {"USER_DATA_ADDRESS",new ItemData(publication.UserAddress, typeof(string).Name)}, {"USER_DATA_HAS_MICROSITE",new ItemData((!string.IsNullOrEmpty(publication.UserMicrosite)).ToString(),typeof(bool).Name) }, {"USER_DATA_MICROSITE_URL",new ItemData(((!string.IsNullOrEmpty(publication.UserMicrosite)).ToString()).ToLower()=="false"?string.Empty:publication.UserMicrosite,typeof(string).Name) }, {"USER_DATA_HAS_LOGO",new ItemData((publication.LogoId)==0?"False":"True",typeof(bool).Name) }, {"USER_DATA_LOGO_URL",new ItemData((publication.LogoId)==0?string.Empty:"http://static1.deautos.com/images/directorio/" + publication.LogoId + "_logo.jpg",typeof(string).Name) }, {"USER_DATA_GEOLOC_COORD",new ItemData(((!string.IsNullOrEmpty(publication.UserMicrosite)).ToString()).ToLower()=="false"?string.Empty:publication.GmapCoord,typeof(string).Name) }, }; }
private static void ParseDataArnetMinerV7(string filein, string prefixfileout, ref int i) { //using (FileStream fs = File.Open(directory + filename, FileMode.Open, FileAccess.Read)) //using (BufferedStream bs = new BufferedStream(fs)) // using (StreamReader sr = new StreamReader(bs)) using (StreamReader sr = File.OpenText(filein)) { string s; string strcurTitle = "#*"; int curYear = 0; string strcurConfVenue = "#con"; int curCitationNumber = 0; int curIndex = -1; int curArnetid = -1; string strcurAbstract = "#!"; Publication curPublication = null; List<string> strcurAuthors = new List<string>(); HashSet<int> icurRefId = new HashSet<int>(); curPublication = new Publication(); while ((s = sr.ReadLine()) != null) { if ((s=s.Trim()).Equals(string.Empty)) continue; if (s.StartsWith(strTitle)) { //save current paper if (curPublication == null) { curPublication = new Publication( curIndex, 100, strcurTitle, strcurAuthors.ToArray(), curYear, strcurConfVenue, curCitationNumber, curIndex, curArnetid, strcurAbstract, icurRefId); if (!Publication.dicAllPubs.Keys.Contains(curIndex)) Publication.dicAllPubs.Add(curIndex, curPublication); else { curPublication.liAuthors.ToList().ForEach(a => { Publication.dicAllPubs[curIndex].liAuthors.Add(a); }); curPublication.liReferenceIds.ToList().ForEach(ir => { Publication.dicAllPubs[curIndex].liReferenceIds.Add(ir); }); } if ((Publication.dicAllPubs.Count) % 500000 == 0) { Console.WriteLine("dic={0}", Publication.dicAllPubs.Count * i); } if ((Publication.dicAllPubs.Count) == 500000) { i++; WriteToFile(Publication.dicAllPubs, i, prefixfileout, true); //Publication.dicAllPubs.Clear(); } } //RESET create new paper curPublication = null; icurRefId = new HashSet<int>(); strcurTitle = s.Substring(strTitle.Length); strcurAuthors.Clear(); } else if (s.StartsWith(strAuthors)) { strcurAuthors.AddRange(s.Substring(strAuthors.Length).Split(',')); } else if (s.StartsWith(strYearV7)) { curYear = Convert.ToInt32(s.Substring(strYearV7.Length)); } else if (s.StartsWith(strConfVenueV7)) { strcurConfVenue = s.Substring(strConfVenueV7.Length); } else if (s.StartsWith(strCitationNumber)) { curCitationNumber = Convert.ToInt32(s.Substring(strCitationNumber.Length)); } else if (s.StartsWith(strIndex)) { curIndex = Convert.ToInt32(s.Substring(strIndex.Length)); } else if (s.StartsWith(strArnetid)) { curArnetid = Convert.ToInt32(s.Substring(strArnetid.Length)); } else if (s.StartsWith(strRefId)) { if (!s.Substring(strRefId.Length).Trim().Equals(string.Empty)) icurRefId.Add(Convert.ToInt32(s.Substring(strRefId.Length).Trim())); } else if (s.StartsWith(strAbstract)) { strcurAbstract = s.Substring(strAbstract.Length); } else { if (s.Length != 0) Console.WriteLine("Unknown tag: string=" + s); } } WriteToFile(Publication.dicAllPubs, 1, prefixfileout, true); } }
/// <summary> /// Валидация сохранения сущности. /// </summary> /// <param name="publication">Сущность.</param> private void ValidateSave(Publication publication) { Argument.NotNull(publication, "Не указан печатный труд преподавателя."); Argument.Require(publication.PlanId > 0, "Не указан план преподавателя."); }
protected void UpdateDataView() { try { dlTemplates.Items.Clear(); if (template != null || template.Count >= 0) { foreach (string t in template) { dlTemplates.Items.Add(new ListItem(t, t)); } } CultureList culs = SessionState.User.Cultures; CollectionView vCuls = new CollectionView(culs); if (SessionState.Culture.Code != HyperCatalog.Shared.SessionState.MasterCulture.Code) { vCuls.ApplyFilter("FallbackCode", SessionState.Culture.Code, CollectionView.FilterOperand.StartsWith); dlLocalizations.Items.Add(new ListItem(SessionState.Culture.Name, SessionState.Culture.Code)); } foreach (Culture cul in vCuls) { string prefix = ""; for (int i = 0; i < (int)cul.Type; i++) { prefix += "_"; } dlLocalizations.Items.Add(new ListItem(prefix + cul.Name, cul.Code)); } if (SessionState.Culture != null) { dlLocalizations.SelectedValue = SessionState.Culture.Code; } else { dlLocalizations.SelectedValue = HyperCatalog.Shared.SessionState.MasterCulture.Code; } Publication pubWS = HyperCatalog.WebServices.WSInterface.Publication; colorParams = pubWS.GetParamSet("HP Colors"); dlColors.Items.Add(new ListItem("Default", "default")); dlColors.Items.Add(new ListItem("Auto", "auto")); foreach (ParamSet param in colorParams) { dlColors.Items.Add(new ListItem(param.Name, param.Id.ToString())); } try { //FIX FOR 70901 int paramVal = 0; //paramVal = pubWS.GetHotItemParam(item.Id.ToString(), dlTemplates.Text.ToString()); paramVal = GetHotItemParam(item.Id.ToString(), dlTemplates.Text.ToString()); //FIX FOR 70901 if (paramVal > 0) { if (paramVal < dlColors.Items.Count) { dlColors.SelectedValue = dlColors.Items[paramVal + 1].Value; } } } catch (Exception ex) { } } catch (Exception e) { Response.Write(e.Message); } }
public Task PubmedCrawlerLink(long retstart, int maxBatch, List <long> idList) { return(new Task(() => { if (idList == null || idList.Count == 0) { return; } var parameters = $"dbfrom=pubmed&linkname=pubmed_pubmed_citedin" + $"&retstart={retstart}&retmax={maxBatch}&rettype=xml&retmode=xml" + $"{ConfigurationManager.Instance.config.ParametersAPI}&id={+idList.ElementAt(0)}"; for (int i = 1; i < idList.Count; i++) { parameters += "&id=" + idList.ElementAt(i); } var url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi"; //Console.WriteLine(url); var request = (HttpWebRequest)WebRequest.Create(url); request.AutomaticDecompression = DecompressionMethods.GZip; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Timeout = (int)TimeSpan.FromMinutes(10).TotalMilliseconds; var data = Encoding.ASCII.GetBytes(parameters); request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } //Console.WriteLine("Starting request for PubMed citations this can take some time..."); XmlSerializer serializer = new XmlSerializer(typeof(ELinkResult)); ELinkResult results; using (var response = (HttpWebResponse)request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { //Console.WriteLine("Parsing request for PubMed this can take some time..."); results = serializer.Deserialize(reader) as ELinkResult; foreach (LinkSet linkset in results.LinkSet) { if (linkset.LinkSetDb != null) { Publication pub = publicationRepository.getByIDPubmed(linkset.IdList.Id); pub.timesCited = linkset.LinkSetDb.Link.Count; publicationRepository.updatePublication(pub); } } } } )); }
internal void Disconnect(ErrorHandler errorHandler) { CloseHelper.Dispose(errorHandler, _responsePublication); _responsePublication = null; }
protected void UploadButton_Click(object sender, EventArgs e) { UploadButton.Enabled = false; try { if (fileUpload.HasFile) { if (fileUpload.PostedFile.ContentType == "application/pdf") { if (fileUpload.PostedFile.FileName.Length < 80) { //Vérification que le fichier ne soit pas déjà ajouté Publication publiTest = pf.GetByFileName(fileUpload.PostedFile.FileName); if (publiTest == null) { // Televersement du fichier string path = "/ms/pdf/" + fileUpload.PostedFile.FileName; fileUpload.SaveAs(Server.MapPath(path)); // Ajout a la BD pf.Add(Convert.ToInt32(DdlCategories.SelectedValue), txtTitle.Text, path, fileUpload.PostedFile.FileName); // Notification Email aux utilisateurs abonnées // -----------Vérification le l'état du module ----------- // ModuleFactory moduleFactory = new ModuleFactory(cnnStr); Module m = moduleFactory.Get((int)Module.AllModules.Subscription); /* Module id 4 = Module des abonnements */ if (m.active != false) { //Envoyer le email UserFactory uf = new UserFactory(cnnStr); User[] users = uf.GetAllSubscribed(); string[] usersIDs = new string[users.Length]; int cpt = 0; foreach (User user in users) { EmailController ec = new EmailController(); string body = string.Empty; using (StreamReader reader = new StreamReader(Server.MapPath("~/Email/Notification.html"))) { body = reader.ReadToEnd(); } //Remplacer la date body = body.Replace("{date}", DateTime.Now.ToString("dd-MM-yyyy")); //Remplacer les liens string strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery; string strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/"); string lienPublication = strUrl + "Publications.aspx"; body = body.Replace("{lienPublications}", lienPublication); string desabonner = strUrl + "Desabonnement.aspx" + "?email=" + user.email + "&tkn=" + user.token; body = body.Replace("{desabonner}", desabonner); //Envoie du mail ec.SendMail(user.email, "Nouvelle(s) publication(s) sur JMGuay.ca", body); //ajout dans le tableau pour update les lastNotificationDates usersIDs[cpt] = user.userId.ToString(); cpt++; } if (users.Length > 0) { //Notifications des users avec la liste des IDs uf.NotifyByArray(usersIDs); } } // ------------------------------------------------------- // // Redirect txtTitle.Text = ""; Response.Redirect("AjoutPublication.aspx" + "?conf=true"); } else { //Ce fichier (ou un du même fileName) à déjà été uploadé Response.Redirect("AjoutPublication.aspx" + "?conf=false"); } } else { StatusLabel.Style.Add("color", "red"); StatusLabel.Text = "Le nom du fichier (" + fileUpload.PostedFile.FileName + ") est trop long! Ce dernier doit contenir moins de 80 caractères"; } } else { StatusLabel.Style.Add("color", "red"); StatusLabel.Text = "Seulement les documents du format PDF sont acceptés"; } } else { StatusLabel.Style.Add("color", "red"); StatusLabel.Text = "Veuillez insérer un ficher PDF"; } } catch (Exception ex) { StatusLabel.Style.Add("color", "red"); StatusLabel.Text = "Le fichier n'a pas pu être téléversé. L'erreur suivante s'est produite: " + ex.Message; } finally { UploadButton.Enabled = true; } }
public void AddPublication(Publication pub) { ctx.Publications.Add(pub); ctx.SaveChanges(); }
/// <summary> /// Add five extra articles to the database for Tobian and Bunn /// </summary> public static void CreateExtraArticlesForTobianAndBunn(Database DB, PublicationTypes PubTypes, string[] Languages) { // Create people objects for Tobian and Bunn Person Tobian = new Person("A5401532", "Louis", "", "Tobian", true, new String[] { "tobian l", "tobian l jr", "tobian lj" }, "(\"tobian l\"[au] OR \"tobian l jr\"[au] OR \"tobian lj\"[au])"); Person Bunn = new Person("A4800524", "PAUL", "A.", "BUNN", true, new String[] { "bunn p jr", "bunn pa jr", "bunn pa", "bunn p" }, "((\"bunn pa jr\"[au] or \"bunn p jr\"[au]) or ((\"bunn p\"[au] or \"bunn pa\"[au]) and (lymphoma or cancer)) and 1970:2005[dp])"); // First, add a few more publications to the colleague. Publication pub = new Publication(); string[] Authors = new String[] { "TOBIAN L", "BUNN P" }; pub.Year = 1993; pub.Journal = "Fake Journal"; pub.Authors = Authors; pub.PMID = 22222222; pub.Title = "Fake article #1"; pub.Language = "eng"; pub.PubType = "Journal Article"; Publications.WriteToDB(pub, DB, PubTypes, Languages); Publications.WritePeoplePublicationsToDB(DB, Tobian, pub); ColleagueFinder.WriteColleaguePublicationsToDB(DB, Bunn, pub, PubTypes, new string[] { "eng" }); pub = new Publication(); Authors = new String[] { "BUNN P", "TOBIAN L" }; pub.Year = 1996; pub.Journal = "Xenotransplantation"; pub.Authors = Authors; pub.PMID = 12345678; pub.Title = "Fake article #2"; pub.Language = "eng"; pub.PubType = "Journal Article"; Publications.WriteToDB(pub, DB, PubTypes, Languages); Publications.WritePeoplePublicationsToDB(DB, Tobian, pub); ColleagueFinder.WriteColleaguePublicationsToDB(DB, Bunn, pub, PubTypes, new string[] { "eng" }); pub = new Publication(); Authors = new String[] { "TOBIAN L", "BUNN P" }; pub.Year = 1996; pub.Journal = "Fake Journal"; pub.Authors = Authors; pub.PMID = 98765432; pub.Title = "Fake article #3"; pub.Language = "eng"; pub.PubType = "Journal Article"; Publications.WriteToDB(pub, DB, PubTypes, Languages); Publications.WritePeoplePublicationsToDB(DB, Tobian, pub); ColleagueFinder.WriteColleaguePublicationsToDB(DB, Bunn, pub, PubTypes, new string[] { "eng" }); pub = new Publication(); Authors = new String[] { "TOBIAN L", "BUNN P", "SCHMOE J" }; pub.Year = 2001; pub.Journal = "Nature"; pub.Authors = Authors; pub.PMID = 55555555; pub.Title = "Fake article #4"; pub.Language = "eng"; pub.PubType = "Journal Article"; Publications.WriteToDB(pub, DB, PubTypes, Languages); Publications.WritePeoplePublicationsToDB(DB, Tobian, pub); ColleagueFinder.WriteColleaguePublicationsToDB(DB, Bunn, pub, PubTypes, new string[] { "eng" }); }
public void Update(Publication item) { _context.Entry(item).State = System.Data.Entity.EntityState.Modified; }
public void DeletePublisher(Publication publisher) { throw new NotImplementedException(); }
} //declare a object for mainwindow public PublicationController(MainWindow w) { pub = new Publication(); wm = w; }
public Publisher(AtomicBoolean running, Publication publication) { Running = running; Publication = publication; }
private static void parsePublications(Ads[] ads) { for (int i = 0; i < ads.Count(); i++) { if (ads[i].adPubsXML.Count > 0 && ads[i].adPubsXML != null) { ads[i].adPubs = new Collection <Publication>(); foreach (string xml in ads[i].adPubsXML) { Publication pub = new Publication(); string fixedxml = xml.Replace("&", "&"); Debug.Write(fixedxml); pub.publicationName = "hello"; using (XmlReader reader = XmlReader.Create(new StringReader(fixedxml))) { reader.ReadToFollowing("adpub"); reader.MoveToAttribute("publicid"); pub.publicid = reader.Value; reader.MoveToAttribute("publicationId"); pub.publicationId = reader.Value; reader.MoveToAttribute("publicationName"); pub.publicationName = reader.Value; reader.MoveToAttribute("tags"); pub.tags = reader.Value; reader.MoveToAttribute("pages"); pub.pages = reader.Value; reader.MoveToAttribute("locator"); pub.locator = reader.Value; reader.MoveToAttribute("regionIds"); pub.locator = reader.Value; reader.MoveToAttribute("mediaType"); pub.locator = reader.Value; reader.MoveToAttribute("frequency"); pub.locator = reader.Value; reader.MoveToAttribute("circulation"); pub.locator = reader.Value; reader.MoveToAttribute("status"); pub.locator = reader.Value; reader.MoveToAttribute("dateModified"); pub.locator = reader.Value; } Debug.WriteLine(pub.publicationId); Debug.WriteLine(pub.publicationName); ads[i].adPubs.Add(pub); } } } }
internal TestTemplate(Publication publication) { Session = publication.Session; Publication = publication; }
static void Main(string[] args) { bool inLibrary = true; Console.Clear(); Console.WriteLine("Welcome to the Library!"); //create books Publication readyPlayerOne = new Book("Ready Player One", "Ernest Cline", 541964568, "VR People"); Book harryPotter1 = new Book("Harry Potter and the Sorcerers Stone", "JK Rowlings", 61596845, "PotterHouse"); Book haloFallOfReach = new Book("Halo: Fall of Reach", "John 117", 684961685, "Master Chief"); Book breifHistoryOfTime = new Book("A Brief History of Time", "Steven Hawking", 561968161, "The Universe"); //Create magazines Magazine time = new Magazine("Person of the Year", "Time", 523); // create library Library boiseLibrary = new Library("Boise Library"); //Add books to Library boiseLibrary.Books.Add(readyPlayerOne); boiseLibrary.Books.Add(harryPotter1); boiseLibrary.Books.Add(haloFallOfReach); boiseLibrary.Books.Add(breifHistoryOfTime); boiseLibrary.Books.Add(time); // while (inLibrary) { Console.WriteLine("Options: "); for (int i = 0; i < boiseLibrary.Books.Count; i++) { Publication currentbook = boiseLibrary.Books[i]; if (currentbook.Available) { Console.WriteLine(i + 1 + ". " + currentbook.myDescription()); } } Console.WriteLine(boiseLibrary.Books.Count + 1 + ". Return Book"); Console.WriteLine(boiseLibrary.Books.Count + 2 + ". Exit"); ///take in user input string input = Console.ReadLine(); //check if valid number int choice; bool valid = Int32.TryParse(input, out choice); if (!valid || choice > boiseLibrary.Books.Count + 2) { Console.Clear(); Console.WriteLine("INVALID SELECTION PLEASE CHOOSE FROM THE FOLLOWING OPTIONS"); } else if (choice == boiseLibrary.Books.Count + 2) { inLibrary = false; } else if (boiseLibrary.hasBook && choice != boiseLibrary.Books.Count + 1) { Console.Clear(); Publication outBook = boiseLibrary.Books.Find(b => b.Available == false); Console.WriteLine($"Sorry You Already Have A book: {outBook.Title} ... Please return it first"); } else if (choice == boiseLibrary.Books.Count + 1) { if (!boiseLibrary.hasBook) { Console.Clear(); Console.WriteLine("No book to return"); } else { boiseLibrary.ReturnBook(); Console.Clear(); Console.WriteLine(" Your book has been Returned"); } } else { boiseLibrary.Checkout(choice - 1); Console.Clear(); Console.WriteLine("ENJOY YOUR BOOK!"); } //check if is book or return } }
public void GetUser() { PolicyCheckBuilder() .ExpectCheck(SecurityPolicies.CanManageUsersOnSystem) .AssertSuccess(async userService => { var userAndRolesContextId = Guid.NewGuid().ToString(); var applicationUser = new ApplicationUser { Id = Guid.NewGuid().ToString(), FirstName = "TestFirstName", LastName = "TestLastName" }; var role = new IdentityRole { Id = Guid.NewGuid().ToString() }; var userRole = new IdentityUserRole <string> { UserId = applicationUser.Id, RoleId = role.Id }; await using (var userAndRolesDbContext = InMemoryUserAndRolesDbContext(userAndRolesContextId)) { await userAndRolesDbContext.AddAsync(applicationUser); await userAndRolesDbContext.AddAsync(role); await userAndRolesDbContext.AddAsync(userRole); await userAndRolesDbContext.SaveChangesAsync(); } var contentDbContextId = Guid.NewGuid().ToString(); var publication = new Publication { Id = Guid.NewGuid(), Title = "Test Publication" }; var release = new Release { Id = Guid.NewGuid(), TimePeriodCoverage = TimeIdentifier.CalendarYear, ReleaseName = "2000", PublicationId = publication.Id, Publication = publication }; var user = new User { Id = Guid.Parse(role.Id), FirstName = applicationUser.FirstName, LastName = applicationUser.LastName, Email = "*****@*****.**" }; var userReleaseRole = new UserReleaseRole { Id = Guid.NewGuid(), User = user, UserId = user.Id, Release = release, ReleaseId = release.Id, Role = ReleaseRole.Lead, }; await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(publication); await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(userReleaseRole); await contentDbContext.SaveChangesAsync(); } await using (var userAndRolesDbContext = InMemoryUserAndRolesDbContext(userAndRolesContextId)) await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var userManagementService = BuildUserManagementService( userAndRolesDbContext, userService.Object, contentDbContext); return(await userManagementService.GetUser(applicationUser.Id)); } } ); }
public async Task GetManageContentPageViewModel() { var publication = new Publication { Contact = new Contact { ContactName = "Name", ContactTelNo = "01234 567890", TeamEmail = "*****@*****.**", TeamName = "Team Name" }, DataSource = "Data Source", Description = "Description", LegacyReleases = new List <LegacyRelease> { new LegacyRelease { Description = "Legacy 2017/18", Order = 0, Url = "http://legacy-2017-18" }, new LegacyRelease { Description = "Legacy 2018/19", Order = 1, Url = "http://legacy-2018-19" }, }, Methodology = new Methodology { Title = "Methodology" }, Slug = "test-publication", Summary = "Summary", Title = "Publication", Topic = new Topic { Theme = new Theme { Title = "Theme" } } }; var releaseType = new ReleaseType { Title = "Release Type" }; var release = new Release { Id = Guid.NewGuid(), NextReleaseDate = new PartialDate { Day = "9", Month = "9", Year = "2040" }, PreReleaseAccessList = "Test access list", Publication = publication, PublishScheduled = DateTime.Parse("2020-09-08T23:00:00.00Z", styles: DateTimeStyles.AdjustToUniversal), Published = null, ReleaseName = "2020", RelatedInformation = new List <Link> { new Link { Description = "Related 1", Url = "http://related-1" } }, Slug = "2020-21", TimePeriodCoverage = AcademicYear, Type = releaseType, Updates = new List <Update>() }; var otherRelease = new Release { NextReleaseDate = new PartialDate { Day = "8", Month = "8", Year = "2040" }, Publication = publication, PublishScheduled = DateTime.Parse("2020-08-07T23:00:00.00Z", styles: DateTimeStyles.AdjustToUniversal), Published = null, ReleaseName = "2019", Slug = "2019-20", TimePeriodCoverage = AcademicYear, Type = releaseType }; var availableDataBlocks = new List <DataBlock> { new DataBlock() }; var ancillaryFileId = Guid.NewGuid(); var dataFileId = Guid.NewGuid(); var files = new List <FileInfo> { new FileInfo { Id = ancillaryFileId, FileName = "ancillary.pdf", Name = "Ancillary File", Path = AdminReleasePath(release.Id, Ancillary, ancillaryFileId), Size = "10 Kb", Type = Ancillary }, new FileInfo { Id = dataFileId, FileName = "data.csv", Name = "Subject File", Path = AdminReleasePath(release.Id, FileType.Data, dataFileId), Size = "20 Kb", Type = FileType.Data } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(publication); await contentDbContext.AddRangeAsync(release, otherRelease); await contentDbContext.ReleaseContentSections.AddRangeAsync( new ReleaseContentSection { Release = release, ContentSection = new ContentSection { Type = ContentSectionType.Headlines } }, new ReleaseContentSection { Release = release, ContentSection = new ContentSection { Type = ContentSectionType.KeyStatistics } }, new ReleaseContentSection { Release = release, ContentSection = new ContentSection { Type = ContentSectionType.KeyStatisticsSecondary } }, new ReleaseContentSection { Release = release, ContentSection = new ContentSection { Type = ContentSectionType.ReleaseSummary } }, new ReleaseContentSection { Release = release, ContentSection = new ContentSection { Type = ContentSectionType.Generic } }); await contentDbContext.SaveChangesAsync(); } var contentService = new Mock <IContentService>(MockBehavior.Strict); var releaseFileService = new Mock <IReleaseFileService>(MockBehavior.Strict); contentService.Setup(mock => mock.GetUnattachedContentBlocksAsync <DataBlock>(release.Id)) .ReturnsAsync(availableDataBlocks); releaseFileService.Setup(mock => mock.ListAll(release.Id, Ancillary, FileType.Data)) .ReturnsAsync(files); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupManageContentPageService(contentDbContext: contentDbContext, contentService: contentService.Object, releaseFileService: releaseFileService.Object); var result = await service.GetManageContentPageViewModel(release.Id); Assert.True(result.IsRight); contentService.Verify(mock => mock.GetUnattachedContentBlocksAsync <DataBlock>(release.Id), Times.Once); releaseFileService.Verify(mock => mock.ListAll(release.Id, Ancillary, FileType.Data), Times.Once); Assert.Equal(availableDataBlocks, result.Right.AvailableDataBlocks); var contentRelease = result.Right.Release; Assert.NotNull(contentRelease); Assert.Equal(release.Id, contentRelease.Id); Assert.Equal("Academic Year", contentRelease.CoverageTitle); Assert.NotNull(contentRelease.DataLastPublished); Assert.True(contentRelease.HasMetaGuidance); Assert.True(contentRelease.HasPreReleaseAccessList); Assert.Equal(release.HeadlinesSection.Id, contentRelease.HeadlinesSection.Id); Assert.Equal(release.KeyStatisticsSection.Id, contentRelease.KeyStatisticsSection.Id); Assert.Equal(release.KeyStatisticsSecondarySection.Id, contentRelease.KeyStatisticsSecondarySection.Id); Assert.False(contentRelease.LatestRelease); Assert.Equal("9", contentRelease.NextReleaseDate.Day); Assert.Equal("9", contentRelease.NextReleaseDate.Month); Assert.Equal("2040", contentRelease.NextReleaseDate.Year); Assert.Equal("2020", contentRelease.ReleaseName); Assert.Null(contentRelease.Published); Assert.Equal(publication.Id, contentRelease.PublicationId); Assert.Equal(DateTime.Parse("2020-09-09T00:00:00.00"), contentRelease.PublishScheduled); Assert.Equal("2020-21", contentRelease.Slug); Assert.Equal(release.SummarySection.Id, contentRelease.SummarySection.Id); Assert.Equal("Academic Year 2020/21", contentRelease.Title); Assert.Equal(release.Type, contentRelease.Type); Assert.Equal("2020/21", contentRelease.YearTitle); Assert.Empty(contentRelease.Updates); var contentDownloadFiles = contentRelease.DownloadFiles.ToList(); Assert.Equal(2, contentDownloadFiles.Count); Assert.Equal(files[0].Id, contentDownloadFiles[0].Id); Assert.Equal("pdf", contentDownloadFiles[0].Extension); Assert.Equal("ancillary.pdf", contentDownloadFiles[0].FileName); Assert.Equal("Ancillary File", contentDownloadFiles[0].Name); Assert.Equal(AdminReleasePath(release.Id, Ancillary, ancillaryFileId), contentDownloadFiles[0].Path); Assert.Equal("10 Kb", contentDownloadFiles[0].Size); Assert.Equal(Ancillary, contentDownloadFiles[0].Type); Assert.Equal(files[1].Id, contentDownloadFiles[1].Id); Assert.Equal("csv", contentDownloadFiles[1].Extension); Assert.Equal("data.csv", contentDownloadFiles[1].FileName); Assert.Equal("Subject File", contentDownloadFiles[1].Name); Assert.Equal(AdminReleasePath(release.Id, FileType.Data, dataFileId), contentDownloadFiles[1].Path); Assert.Equal("20 Kb", contentDownloadFiles[1].Size); Assert.Equal(FileType.Data, contentDownloadFiles[1].Type); var contentRelatedInformation = contentRelease.RelatedInformation; Assert.Single(contentRelatedInformation); Assert.Equal("Related 1", contentRelatedInformation[0].Description); Assert.Equal("http://related-1", contentRelatedInformation[0].Url); var contentReleaseContent = contentRelease.Content; Assert.Single(contentReleaseContent); Assert.Equal(release.GenericContent.First().Id, contentReleaseContent[0].Id); var contentPublication = contentRelease.Publication; Assert.NotNull(contentPublication); Assert.Equal(publication.Id, contentPublication.Id); Assert.Equal(publication.Contact.Id, contentPublication.Contact.Id); Assert.Equal(publication.Contact.ContactName, contentPublication.Contact.ContactName); Assert.Equal(publication.Contact.TeamEmail, contentPublication.Contact.TeamEmail); Assert.Equal(publication.Contact.ContactTelNo, contentPublication.Contact.ContactTelNo); Assert.Equal("Data Source", contentPublication.DataSource); Assert.Equal("Description", contentPublication.Description); Assert.Null(contentPublication.ExternalMethodology); Assert.Equal(publication.Methodology.Id, contentPublication.Methodology.Id); Assert.Equal("Methodology", contentPublication.Methodology.Title); Assert.Equal("test-publication", contentPublication.Slug); Assert.Equal("Summary", contentPublication.Summary); Assert.Equal("Publication", contentPublication.Title); Assert.Equal("Theme", contentPublication.Topic.Theme.Title); Assert.NotNull(contentPublication.Topic); Assert.NotNull(contentPublication.Topic.Theme); var contentPublicationLegacyReleases = contentPublication.LegacyReleases.ToList(); Assert.Equal(2, contentPublicationLegacyReleases.Count); Assert.Equal("Legacy 2018/19", contentPublicationLegacyReleases[0].Description); Assert.Equal("http://legacy-2018-19", contentPublicationLegacyReleases[0].Url); Assert.Equal("Legacy 2017/18", contentPublicationLegacyReleases[1].Description); Assert.Equal("http://legacy-2017-18", contentPublicationLegacyReleases[1].Url); var contentPublicationOtherReleases = contentPublication.OtherReleases; Assert.Single(contentPublicationOtherReleases); Assert.Equal(otherRelease.Id, contentPublicationOtherReleases[0].Id); Assert.Equal("2019-20", contentPublicationOtherReleases[0].Slug); Assert.Equal("Academic Year 2019/20", contentPublicationOtherReleases[0].Title); } }
public SnapshotTaker(Publication publication, IIdleStrategy idleStrategy, AgentInvoker aeronClientInvoker) { this.publication = publication; this.idleStrategy = idleStrategy; this.aeronClientInvoker = aeronClientInvoker; }
internal ServiceSnapshotTaker(Publication publication, IIdleStrategy idleStrategy, AgentInvoker aeronClientInvoker) : base(publication, idleStrategy, aeronClientInvoker) { }
public static async Task InitAsync(IServiceProvider services) { using (var db = services.GetRequiredService <ApiDbContext>()) { _faker = new Faker(); // Fill the database only if Authors and Literature tables are empty if (db.Authors.Any() && db.Publications.Any()) { return; } Random rnd = new Random(); var maxLevels = Enum.GetValues(typeof(DifficultyLevel)).Length; // Create Subjects and PublicationTypes var allTypes = CreatePublicationTypes(); await db.PublicationTypes.AddRangeAsync(allTypes); var maxTypeIndex = allTypes.Length; var allSubjects = CreateSubjects(); await db.Subjects.AddRangeAsync(allSubjects); var maxSubjectIndex = allSubjects.Length; // Create authors var authors = new List <Author>(); for (var i = 0; i < _maxAuthors; i++) { var author = new Author { FirstName = _faker.Name.FirstName(), LastName = _faker.Name.LastName(), DateOfBirth = _faker.Date.Past(50, DateTime.Parse("1999-12-31")).Date, Publications = new List <Publication>() }; authors.Add(author); } // Create literature var publications = new List <Publication>(); for (var i = 0; i < _maxPublications; i++) { // Retrieve random LiteratureType and random Subject var type = allTypes[rnd.Next(maxTypeIndex)]; var subject = allSubjects[rnd.Next(maxSubjectIndex)]; var publication = new Publication { Title = _faker.Commerce.ProductName(), Description = _faker.Commerce.ProductDescription(), PublicationDate = _faker.Date.Past(10, DateTime.Parse("2021-03-01")).Date, // Random difficulty level Level = (DifficultyLevel)rnd.Next(maxLevels), // Add random LiteratureType & corresponding TypeId Type = type, TypeId = type.Id, // Add random Subject & corresponding SubjectId Subject = subject, SubjectId = subject.Id, Authors = new List <Author>() }; // type.Publications.Add(publication); // subject.Publications.Add(publication); publications.Add(publication); } // Associate Authors with Publications // 1. Go over all the authors and to each add a random publication foreach (var author in authors) { var publication = publications[rnd.Next(_maxPublications)]; author.Publications.Add(publication); } // 2. Go over all the publications and to each add some author foreach (var publication in publications) { var author = authors[rnd.Next(_maxAuthors)]; publication.Authors.Add(author); } await db.Authors.AddRangeAsync(authors); await db.Publications.AddRangeAsync(publications); AddSpecial2(db, allTypes, allSubjects); await db.SaveChangesAsync(); } }
public PublicationTypeVisitor(Publication publication, HtmlHelper<object> html) { _publication = publication; _html = html; }
public void Create(Publication item) { _context.Publications.Add(item); }