private void AddUrls(Webpage webpage, List <string> urlsToAdd, ISession session)
 {
     foreach (string item in urlsToAdd)
     {
         UrlHistory history =
             _session.Query <UrlHistory>().FirstOrDefault(urlHistory => urlHistory.UrlSegment == item);
         bool isNew = history == null;
         if (isNew)
         {
             history = new UrlHistory {
                 UrlSegment = item, Webpage = webpage
             };
             session.Save(history);
         }
         else
         {
             history.Webpage = webpage;
         }
         if (!webpage.Urls.Contains(history))
         {
             webpage.Urls.Add(history);
         }
         session.Update(history);
     }
 }
Esempio n. 2
0
        protected override BatchJobExecutionResult OnExecute(CompleteMergeBatchJob batchJob)
        {
            using (new NotificationDisabler())
            {
                var webpage = _session.Get <Webpage>(batchJob.WebpageId);
                if (webpage == null)
                {
                    return(BatchJobExecutionResult.Failure("Could not find the webpage with id " + batchJob.WebpageId));
                }
                var mergeInto = _session.Get <Webpage>(batchJob.MergedIntoId);
                if (mergeInto == null)
                {
                    return(BatchJobExecutionResult.Failure("Could not find the webpage with id " + batchJob.MergedIntoId));
                }

                _session.Transact(session =>
                {
                    ApplyCustomMergeLogic(webpage, mergeInto);

                    var urlSegment = webpage.UrlSegment;
                    session.Delete(webpage);
                    var urlHistory = new UrlHistory
                    {
                        UrlSegment = urlSegment,
                        Webpage    = mergeInto,
                    };
                    mergeInto.Urls.Add(urlHistory);
                    session.Save(urlHistory);
                });


                return(BatchJobExecutionResult.Success());
            }
        }
Esempio n. 3
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            Uri matchedUri    = new Uri(arguments[0].Value);
            var mentionConfig = UrlHistory.GetConfig();
            var mention       =
                UrlHistory.GetUrlMention(mentionConfig, messageEvent.Channel, matchedUri.AbsoluteUri);

            if (mention == null)
            {
                UrlHistory.AddUrlMention(messageEvent.Nick, messageEvent.Channel, matchedUri.AbsoluteUri);
                return(null);
            }

            if (!UrlHistory.IsChannelEnabled(messageEvent.Channel))
            {
                return(null);
            }

            if (String.Equals(mention.User, messageEvent.Nick, UrlHistory.ComparisonCulture))
            {
                return(null);
            }

            return(UrlHistory.FormatResponse(mention, messageEvent.Nick,
                                             UrlHistory.GetResponse(mentionConfig, messageEvent.Channel),
                                             preventHighlight: UrlHistory.ShouldPreventNickHighlight(mention.User)).SplitInParts(430).ToList());
        }
Esempio n. 4
0
        public void MovesTheUrlHistoryBetweenPagesIfTheyAreChanged()
        {
            var urlHistory = new UrlHistory {
                UrlSegment = "test"
            };
            var basicMappedWebpage1 = new BasicMappedWebpage {
                Urls = new List <UrlHistory> {
                    urlHistory
                }
            };

            urlHistory.Webpage = basicMappedWebpage1;
            var basicMappedWebpage2 = new BasicMappedWebpage {
                Urls = new List <UrlHistory>()
            };

            _urlHistoryRepository.Add(urlHistory);

            basicMappedWebpage1.Urls.Should().HaveCount(1);
            basicMappedWebpage2.Urls.Should().HaveCount(0);

            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string>()
            },
                                                   basicMappedWebpage1);
            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string> {
                    "test"
                }
            },
                                                   basicMappedWebpage2);

            basicMappedWebpage1.Urls.Should().HaveCount(0);
            basicMappedWebpage2.Urls.Should().HaveCount(1);
        }
        public void ShouldNotCreateNewUrlHistoryWhileMovingUrls()
        {
            var urlHistory = new UrlHistory {
                UrlSegment = "test"
            };
            var basicMappedWebpage1 = new BasicMappedWebpage {
                Urls = new List <UrlHistory> {
                    urlHistory
                }
            };

            urlHistory.Webpage = basicMappedWebpage1;
            var basicMappedWebpage2 = new BasicMappedWebpage {
                Urls = new List <UrlHistory>()
            };

            Session.Transact(session => session.Save(urlHistory));
            Session.Transact(session => session.Save(basicMappedWebpage1));
            Session.Transact(session => session.Save(basicMappedWebpage2));

            GetAllHistories().Should().HaveCount(1);

            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string>()
            },
                                                   basicMappedWebpage1);
            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string> {
                    "test"
                }
            },
                                                   basicMappedWebpage2);

            GetAllHistories().Should().HaveCount(1);
        }
 public void Delete(UrlHistory urlHistory)
 {
     if (urlHistory.Webpage != null)
     {
         urlHistory.Webpage.Urls.Remove(urlHistory);
     }
     _session.Transact(session => _session.Delete(urlHistory));
 }
 public void Add(UrlHistory urlHistory)
 {
     if (urlHistory.Webpage != null)
     {
         urlHistory.Webpage.Urls.Add(urlHistory);
     }
     _session.Transact(session => session.Save(urlHistory));
 }
 private static void RemoveUrls(Webpage webpage, List <UrlHistory> urlsToRemove, ISession session)
 {
     foreach (UrlHistory history in urlsToRemove)
     {
         webpage.Urls.Remove(history);
         history.Webpage = null;
         UrlHistory closureHistory = history;
         session.Update(closureHistory);
     }
 }
Esempio n. 9
0
        public void UrlHistoryAdminService_Delete_ShouldRemoveAPassedHistoryFromTheDb()
        {
            var urlHistory = new UrlHistory();

            Session.Transact(session => session.Save(urlHistory));

            _urlHistoryAdminService.Delete(urlHistory);

            Session.QueryOver <UrlHistory>().List().Should().NotContain(urlHistory);
        }
        private async Task Run()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { UrlshortenerService.Scope.Urlshortener },
                    "user", CancellationToken.None, new FileDataStore("UrlShortener.Auth.Store"));
            }


            // Create the service.
            var service = new UrlshortenerService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "UrlShortener.ListURLs Sample",
            });

            // List all shortened URLs:
            Console.WriteLine("Retrieving list of shortened urls...");

            int    i             = 0;
            string nextPageToken = null;

            do
            {
                // Create and execute the request.
                var request = service.Url.List();
                request.StartToken = nextPageToken;
                UrlHistory result = await request.ExecuteAsync();

                // List all items on this page.
                if (result.Items != null)
                {
                    foreach (Url item in result.Items)
                    {
                        Console.WriteLine((++i) + ") URL" + item.Id + " -> " + item.LongUrl);
                    }
                }

                // Continue with the next page.
                nextPageToken = result.NextPageToken;
            } while (!string.IsNullOrEmpty(nextPageToken));

            if (i == 0)
            {
                Console.WriteLine("You don't have any shortened URLs! Visit http://goo.gl and create some.");
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // Initialize this sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("URLShortener -- List URLs");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();

            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret     = credentials.ClientSecret;
            var auth = new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var service = new UrlshortenerService(auth);

            // List all shortened URLs:
            CommandLine.WriteAction("Retrieving list of shortened urls...");

            int    i             = 0;
            string nextPageToken = null;

            do
            {
                // Create and execute the request.
                var request = service.Url.List();
                request.StartToken = nextPageToken;
                UrlHistory result = request.Fetch();

                // List all items on this page.
                if (result.Items != null)
                {
                    foreach (Url item in result.Items)
                    {
                        CommandLine.WriteResult((++i) + ".) URL", item.Id + " -> " + item.LongUrl);
                    }
                }

                // Continue with the next page
                nextPageToken = result.NextPageToken;
            } while (!string.IsNullOrEmpty(nextPageToken));

            if (i == 0)
            {
                CommandLine.WriteAction("You don't have any shortened URLs! Visit http://goo.gl and create some.");
            }

            // ... and we are done.
            CommandLine.PressAnyKeyToExit();
        }
Esempio n. 12
0
        private void MakeRequestCommand_OnExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var currentUrlHistoryItem = getCurrentUrlHistoryModel();

            if (!UrlHistory.Contains(currentUrlHistoryItem, urlHistoryModelEqualityComparer))
            {
                UrlHistory.Insert(0, currentUrlHistoryItem);
                saveHistory();
            }
            CurrentRequestViewModel.Headers           = CurrentRequestViewModel.UIHeaders.Where(h => h.IsSelected).Select(h => new HttpHeader(h.Name, h.Value)).ToList();
            _MainWindow.IsEnabled                     = false;
            new Action(() => CurrentResponseViewModel = xhrLogicManager.SendXHR(CurrentRequestViewModel)).BeginInvoke((ar =>
                                                                                                                       Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => _MainWindow.IsEnabled = true))), null);
        }
Esempio n. 13
0
        /// <summary>Handle navigation events</summary>
        private void HandleNavigating(object sender, WebBrowserNavigatingEventArgs args)
        {
            // Ignore recursive calls (and navigation events that happen after
            // this method returns but are due to the assignment of DocumentStream)
            if (m_rdr_content || args.Url == AboutBlankUrl)
            {
                return;
            }
            using (Scope.Create(() => m_rdr_content = true, () => m_rdr_content = false))
            {
                var idx = UrlHistory.Position + 1;

                // Add the selected URL to the history
                if (idx == UrlHistory.Count)
                {
                    // Resolve the URL to content
                    var a = new ResolveContentEventArgs(args.Url);
                    OnResolveContent(a);

                    // Add to the history
                    UrlHistory.Add(new Visit(a.Url, a.Content));
                }
                else if (!m_fwd_or_back || args.Url != UrlHistory[idx].Url)
                {
                    // Resolve the URL to content
                    var a = new ResolveContentEventArgs(args.Url);
                    OnResolveContent(a);

                    // Set the current visit and remove the future history
                    UrlHistory[idx] = new Visit(a.Url, a.Content);
                    m_url_history.RemoveToEnd(idx + 1);
                }

                UrlHistory.Position = idx;

                // Display the content
                var content = UrlHistory.Current.Content;
                if (content != null)
                {
                    // Setting DocumentStream is considered a navigation (to about:blank)
                    // This may or may not result in a recursive call to this method
                    m_wb.DocumentStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
                    args.Cancel         = true;
                }
                m_fwd_or_back = false;
            }

            System.Diagnostics.Debug.WriteLine($"{UrlHistory.Position} : {string.Join("->", UrlHistory.Select(x => x.Url.ToString()))}");
        }
        void BindUrlHistory()
        {
            var urlHistory = new UrlHistory(Session);
            var urls       = urlHistory.GetBindableUrls();

            if (urls.Count > 0)
            {
                comboUrlHistory.DataSource = urls;
                comboUrlHistory.DataBind();
            }
            else
            {
                panelUrlHistory.Visible = false;
            }
        }
Esempio n. 15
0
 private void SaveChangedUrl(string oldUrl, string newUrl, ISession session, Webpage webpage)
 {
     //check that the URL is different and doesn't already exist in the URL history table.
     if (!StringComparer.OrdinalIgnoreCase.Equals(oldUrl, newUrl) && !CheckUrlExistence(session, oldUrl))
     {
         DateTime createdOn  = CurrentRequestData.Now;
         var      urlHistory = new UrlHistory
         {
             Webpage    = webpage,
             UrlSegment = Convert.ToString(oldUrl),
             CreatedOn  = createdOn,
             UpdatedOn  = createdOn,
             Site       = session.Get <Site>(CurrentRequestData.CurrentSite.Id)
         };
         webpage.Urls.Add(urlHistory);
         session.Transact(ses => ses.Save(urlHistory));
     }
 }
Esempio n. 16
0
 public override void ClonePart(Webpage @from, Webpage to, SiteCloneContext siteCloneContext)
 {
     if ([email protected]())
     {
         return;
     }
     _session.Transact(session =>
     {
         foreach (UrlHistory urlHistory in @from.Urls)
         {
             UrlHistory copy = urlHistory.GetCopyForSite(to.Site);
             copy.Webpage    = to;
             to.Urls.Add(copy);
             siteCloneContext.AddEntry(urlHistory, copy);
             session.Save(copy);
             session.Update(to);
         }
     });
 }
Esempio n. 17
0
        public Webpage Get(RequestContext context)
        {
            string     data             = Convert.ToString(context.RouteData.Values["data"]);
            UrlHistory historyItemByUrl = GetHistoryItemByUrl(data);

            if (historyItemByUrl != null && historyItemByUrl.Webpage.Published)
            {
                return(historyItemByUrl.Webpage);
            }
            if (context.HttpContext.Request.Url != null)
            {
                UrlHistory historyItemByUrlContent =
                    GetHistoryItemByUrl(context.HttpContext.Request.Url.PathAndQuery.TrimStart('/'));
                if (historyItemByUrlContent != null && historyItemByUrlContent.Webpage.Published)
                {
                    return(historyItemByUrlContent.Webpage);
                }
            }
            return(null);
        }
Esempio n. 18
0
        public static async Task <IList <Url> > GetAllShortURLs()
        {
            var json = string.Empty;

            Barrel.ApplicationId = "GoogleUrl";
            IBarrel        barrel     = Barrel.Current;
            UserCredential credential = await Authenticate();

            UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "UrlShortener.ShortenURL sample",
                //ApiKey = ""
            });

            if (!Barrel.Current.IsExpired(service.BaseUri))
            {
                return(JsonConvert.DeserializeObject <IList <Url> >(Barrel.Current.Get(service.BaseUri)));
            }
            else
            {
                List <Url> fullList = new List <Url>();

                // Get All Short URLs

                UrlHistory response = service.Url.List().Execute();
                fullList.AddRange(response.Items);
                while (response.NextPageToken != null)
                {
                    var request = service.Url.List();
                    request.StartToken = response.NextPageToken;
                    //UrlHistory result = request.Execute();
                    response = request.Execute(); // service.Url.List().Execute();
                    fullList.AddRange(response.Items);
                }
                Barrel.Current.Add(service.BaseUri, fullList, TimeSpan.FromDays(1));
                // Display response
                return(fullList);
            }
        }
        public void UnAssigningAUrlHistoryRemoveTheItemFromTheWebpageUrlList()
        {
            var urlHistory = new UrlHistory {
                UrlSegment = "test"
            };
            var basicMappedWebpage = new BasicMappedWebpage {
                Urls = new List <UrlHistory> {
                    urlHistory
                }
            };

            urlHistory.Webpage = basicMappedWebpage;
            Session.Transact(session => session.Save(urlHistory));

            basicMappedWebpage.Urls.Should().HaveCount(1);

            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string>()
            },
                                                   basicMappedWebpage);

            basicMappedWebpage.Urls.Should().HaveCount(0);
        }
        public void UnAssigningAUrlHistoryShouldSetTheWebpageToNull()
        {
            var urlHistory = new UrlHistory {
                UrlSegment = "test"
            };
            var basicMappedWebpage = new BasicMappedWebpage {
                Urls = new List <UrlHistory> {
                    urlHistory
                }
            };

            urlHistory.Webpage = basicMappedWebpage;
            Session.Transact(session => session.Save(urlHistory));

            GetAllHistories().Should().HaveCount(1);

            _updateUrlHistoryService.SetUrlHistory(new DocumentImportDTO {
                UrlHistory = new List <string>()
            },
                                                   basicMappedWebpage);

            GetAllHistories().ElementAt(0).Webpage.Should().BeNull();
        }
        public void ImportUrlHistory(ProductImportDataTransferObject productDto, Product product)
        {
            List<string> urlsToAdd =
                 productDto.UrlHistory.Where(
                     s =>
                         !product.Urls.Select(history => history.UrlSegment)
                             .Contains(s, StringComparer.InvariantCultureIgnoreCase)).ToList();
            //List<UrlHistory> urlsToRemove =
            //    product.Urls.Where(
            //        history =>
            //            !productDto.UrlHistory.Contains(history.UrlSegment, StringComparer.InvariantCultureIgnoreCase))
            //        .ToList();
            foreach (string item in urlsToAdd)
            {
                UrlHistory history =
                    _session.Query<UrlHistory>().FirstOrDefault(urlHistory => urlHistory.UrlSegment == item);
                bool isNew = history == null;
                if (isNew)
                {
                    history = new UrlHistory { UrlSegment = item, Webpage = product };
                    _session.Transact(session => session.Save(history));
                }
                else
                    history.Webpage = product;
                if (!product.Urls.Contains(history))
                    product.Urls.Add(history);
                _session.Transact(session => session.Update(history));
            }

            //foreach (UrlHistory history in urlsToRemove)
            //{
            //    product.Urls.Remove(history);
            //    history.Webpage = null;
            //    UrlHistory closureHistory = history;
            //    _session.Transact(session => session.Update(closureHistory));
            //}
        }
Esempio n. 22
0
 public ActionResult Delete_Get(UrlHistory history)
 {
     return(View(history));
 }
        void Update(bool ignoreWarnings)
        {
            try {
                if (Page.IsValid)
                {
                    if (!ignoreWarnings)
                    {
                        if (!CheckFileExists(ctlUrl.Url) || !CheckFileSecurity(ctlUrl.Url))
                        {
                            cmdUpdateOverride.Visible = true;
                            cmdUpdate.Visible         = false;
                            // display warning instructing users to click update again if they want to ignore the warning
                            this.Message("msgFileWarningHeading.Text", "msgFileWarning.Text", MessageType.Warning, true);
                            return;
                        }
                    }

                    // get existing document record
                    var document = DocumentsDataProvider.Instance.GetDocument(itemId, ModuleId);
                    if (document == null)
                    {
                        document = new DocumentInfo {
                            ItemId          = itemId,
                            ModuleId        = ModuleId,
                            CreatedByUserId = UserInfo.UserID,
                            OwnedByUserId   = UserId
                        };
                    }

                    var oldDocument = document.Clone();

                    document.Title            = txtName.Text;
                    document.Description      = txtDescription.Text;
                    document.ForceDownload    = chkForceDownload.Checked;
                    document.Url              = ctlUrl.Url;
                    document.LinkAttributes   = textLinkAttributes.Text;
                    document.ModifiedByUserId = UserInfo.UserID;

                    UpdateDateTime(document, oldDocument);
                    UpdateOwner(document);
                    UpdateCategory(document);

                    int sortIndex;
                    document.SortOrderIndex = int.TryParse(txtSortIndex.Text, out sortIndex) ? sortIndex : 0;

                    if (Null.IsNull(itemId))
                    {
                        DocumentsDataProvider.Instance.Add(document);
                    }
                    else
                    {
                        DocumentsDataProvider.Instance.Update(document);
                        if (document.Url != oldDocument.Url)
                        {
                            // delete old URL tracking data
                            DocumentsDataProvider.Instance.DeleteDocumentUrl(oldDocument.Url, PortalId, ModuleId);
                        }
                    }

                    // add or update URL tracking
                    var ctrlUrl = new UrlController();
                    ctrlUrl.UpdateUrl(PortalId, ctlUrl.Url, ctlUrl.UrlType, ctlUrl.Log, ctlUrl.Track, ModuleId, ctlUrl.NewWindow);

                    var urlHistory = new UrlHistory(Session);
                    urlHistory.StoreUrl(document.Url);

                    ModuleSynchronizer.Synchronize(ModuleId, TabModuleId);

                    if (Null.IsNull(itemId))
                    {
                        this.Message(string.Format(LocalizeString("DocumentAdded.Format"), document.Title), MessageType.Success);
                        multiView.ActiveViewIndex = 1;
                        BindUrlHistory();
                    }
                    else
                    {
                        Response.Redirect(Globals.NavigateURL(), true);
                    }
                }
            } catch (Exception exc) {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 public void RunCommand(IrcClient client, GroupCollection values, IrcEventArgs eventArgs, IrcBot ircBot)
 {
     Cache.Set(UrlHistory.CacheName, UrlHistory.GetConfig(false), DateTimeOffset.Now.AddMinutes(UrlHistory.CacheExpiration));
     client.SendMessage(SendType.Message, eventArgs.Data.Channel, "Reloaded URL mention config and saved to cache");
 }
Esempio n. 25
0
        public ActionResult Add_Get(int webpageId)
        {
            UrlHistory urlHistory = _urlHistoryAdminService.GetUrlHistoryToAdd(webpageId);

            return(View(urlHistory));
        }
Esempio n. 26
0
        public ActionResult Add(UrlHistory history)
        {
            _urlHistoryAdminService.Add(history);

            return(RedirectToAction("Edit", "Webpage", new { id = history.Webpage.Id }));
        }
 public NavClientConfig()
 {
     UrlHistory = new UrlHistory();
     UnknownSpnHint = new UnknownSpnHints();
 }