I have a news site that is powered by C# ASP.Net MVC 5.0 and I want to push notification to clients browser when an admin add/edit or delete a news.
so I added a signalr script to my template which is used in all pages.
_Layout.cshtml
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
};
var notification = new Notification(title, options);
};
});
and added this code to the page that redirects after news add/edit/delete is done
<script>
$.connection.hub.start().done(function() {
notificationsHub.server.toast('#NotificationHub.Type.ToString()', '#Html.Raw(NotificationHub.Title)', '#Html.Raw(NotificationHub.Body)');
});
</script>
when I add/edit/delete a news it works fine but the problem is it pushes notification to all opened tabs in my site. is there a trick to avoid this happening and show only one browser notification per site?
Then you have to know the number of open tabs and the URL used. See the "How to get the number of tabs opened of my web in a browser using jquery?" SO question for a discussion that this is not desired for privacy reasons.
OK I found answer in this SO question.
The trick is to use tag in options:
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
tag: 'my-unique-id',
};
var notification = new Notification(title, options);
};
});
Related
I have a CEF WinForm Application which loads a webpage for creating helpdesk tickets.
I want the user to be able to click a SCREENSHOT button and have it save the file to the desktop and then automatically attach it to the webform inside the CHROMIUM Browser control.
I can easily save the file to the desktop, that is easy and not a problem.
I have also tried
browser.DialogHandler = new TempFileDialogHandler(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\Capture.jpg");
This will take the file (CAPTURE.JPG) and attach it to the browser control, but not to the actual web page.
Can I use the javascript (script) option and somehow programmatically put this file into the FileUpload control in the page (see below)
I know I can have the user just click the button and manually add the file themselves, but I want to automate this process. Any help or direction would be greatly appreciated.
**** Edited Jan 7, 2021.
I tried to use the following code to use the DOM objects.
using (CefSharp.DevTools.DevToolsClient client = browser.GetDevToolsClient())
{
Task<GetDocumentResponse> dom = client.DOM.GetDocumentAsync();
QuerySelectorResponse querySelectorResponse = await client.DOM.QuerySelectorAsync(dom.Result.Root.NodeId, "fileupload");
_ = client.DOM.SetFileInputFilesAsync(new string[] { #"c:\temp\scr.png" }, querySelectorResponse.NodeId);
}
I am using CefSharp WinForms v83. When I run the code, it hangs on the
await client.DOM.QuerySelectorAsync(dom.Result.Root.NodeId, "fileupload");
Do I need event handlers?
Edit Jan 7 2021 #2
The Following changes to the code made it work once.
await Task.Run(async () =>
{
using (CefSharp.DevTools.DevToolsClient client = browser.GetDevToolsClient())
{
var dom = client.DOM.GetDocumentAsync();
var querySelectorResponse = await client.DOM.QuerySelectorAsync(dom.Result.Root.NodeId, "#fileupload");
_ = client.DOM.SetFileInputFilesAsync(new string[] { #"C:\Users\Chris\Desktop\capture.jpg" }, querySelectorResponse.NodeId);
_ = client.DOM.SetFileInputFilesAsync(new string[] { #"C:\Users\Chris\Desktop\capture1.jpg" }, querySelectorResponse.NodeId);
}
});
When I try to do it again, I get the follow error:
Generated MessageId 100005 doesn't match returned Message Id 100001
** Edit Jan 7 2021 #3 - I think this works.
if (client == null)
{
client = browser.GetDevToolsClient();
dom = client.DOM.GetDocumentAsync();
}
await Task.Run(async () =>
{
var querySelectorResponse = await client.DOM.QuerySelectorAsync(dom.Result.Root.NodeId, "#fileupload");
_ = client.DOM.SetFileInputFilesAsync(new string[] { filename }, querySelectorResponse.NodeId);
});
Thank you to amaitland for all the help I received on this one.
Here is the code I used to make it all happen.
if (client == null)
{
client = browser.GetDevToolsClient();
dom = client.DOM.GetDocumentAsync();
}
await Task.Run(async () =>
{
var querySelectorResponse = await
client.DOM.QuerySelectorAsync(dom.Result.Root.NodeId, "#fileupload");
_ = client.DOM.SetFileInputFilesAsync(new string[] { filename },
querySelectorResponse.NodeId);
});
I was receiving the error message:
Generated MessageId 100005 doesn't match returned Message Id 100001
until I moved the
client = browser.GetDevToolsClient();
dom = client.DOM.GetDocumentAsync();
out of the task.run... I am not sure why this works but it does. So... code above is what I used after the user clicked the SCREEN CAPTURE button on the windows form to capture the screen shot. I saved the file to disk (jpg) and then used this code to attach the newly created jpg file to the web page.
There is this online form (https://servizi.ivass.it/RuirPubblica/) where you can make a search (just make a blank search). For each result it gives, I need to click on the result and export the list that is in the 5th table of the details page.
So basically I want to make a software that does that for me:
Submit a search with my own criteria
Access each page of the result items
Access each item detail page
Obtain the rows in the 5th tag so that I can append them to a list
Using Fiddler I checked which parameters where used in the POST request when I clicked the "Search" button, and tried to do the same with .Net.
If I try to access the base address with HttpClient it returns the correct HTML of the search form, but when I submit the following POST request with search parameters I get a web page showing the error "Warning: Session Expired".
This happens also if I make the search POST call alone, without first accessing the home page, so I'm not sure it is related to keeping the session alibe between two requests.
public MainWindow()
{
InitializeComponent();
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false
};
client = new HttpClient(handler)
{
BaseAddress = new Uri("https://servizi.ivass.it/RuirPubblica/Search.faces")
};
}
private async Task TryHttp()
{
// Access the search page
var response = await client.GetAsync(client.BaseAddress);
var responseString = await response.Content.ReadAsStringAsync();
// Perform the search
var values = new Dictionary<string, string>
{
{ "FormSearch", "FormSearch" },
{ "FormSearch:j_id_jsp_558348152_13", "PG" },
{ "FormSearch:j_id_jsp_558348152_16", "custom" },
{ "FormSearch:SecE", "on" },
{ "FormSearch:matricola", "" },
{ "FormSearch:ragioneSociale", "" },
{ "FormSearch:provincia", "NA" },
{ "FormSearch:SearchButton", "Ricerca" },
{ "javax.faces.ViewState", "j_id1:j_id5" },
};
var content = new FormUrlEncodedContent(values);
response = await client.PostAsync(client.BaseAddress, content);
// Here I'm getting a web page showing the error "Warning: Session expired"
responseString = await response.Content.ReadAsStringAsync();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
TryHttp();
}
If you can define it, it can be done. As you will understand from the comments StackOverflow is all about programming questions, so I will only help you with that.
In principal if the web page is "parsable" as HTML and communicates using HTTP you can do anything with it that a normal web browser would do. The website you reference does initially appear to do anything out of the ordinary.
HTMLAgilityPack can be very useful for parsing the DOM and navigating and extracting the contents.
To make HTTP requests with C# you should use the HttpClient class.
There are older options like the HttpWebClient, there is good answer here on SO to help you decide between the two.
For quick reference, Fiddler is available here, I too have used it many times and would recommended it, although it can cause problems with HTTPS traffic and debugging.
I want to send pushnotifications to firefox web browser.......
<script>
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
} Notification.requestPermission().then(function (result) {
console.log(result);
}); function spawnNotification(theBody, theIcon, theTitle) {
var options = {
body: theBody,
icon: theIcon
}
var n = new Notification(theTitle, options);
}
</script>
whenever first time my website run permission popup will come.but when user click allow button how to get browser info like id.I want save that browser id into my database.next time I will send notification using that id. I did not find any code please help me.please anyone help me.
The Web Notifications API does not do what think it does.
It can only be used to display notifications from a web page that a user currently has open in their browser. It is comparable to alert(), except with a larger variety of formatting options.
It is not a push notification service, and cannot be used as one.
I am following the wpf auth0 login example. I am not clear on what is the best method to customize logo / icon ?
icon: 'https://auth0.com/boot/badge.png'
I have added a full Auth0.Windows project to the solution, where I am appending css and js to the html in the UpdateStatus(string message) once login window is loaded, which feels hackish way of doing it. Any Advises or samples would be helpful.
var auth0 = new Auth0Client(AuthDomain, ClientId);
var userAthenticate = await auth0.LoginAsync(null);
Edit: Just realized this was 8 months old... sorry for the resurrection.
You should be able to supply a third param to Auth0Client...
var options = {
theme: {
logo: '/images/logo.png'
}
};
var auth0 = new Auth0Client(AuthDomain, ClientId, options);
I have an aspx page (webforms) that is called from a jQuery Post method (which works fine), however the Response.Redirect method from the code behind does not reload the browser with the redirected URL. It does actually hit the URL, however.
I'm pretty sure this has something to do with the page being called from jQuery, but not sure why this behavior is happening.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//lid = Validation.StripToGUID(ObjToGUID(Request.QueryString("lid")))
lid = Validation.StripToGUID(ObjToGUID(Request.Form["lid"]));
string sid = null;
if (lid.Length == 36)
{
//retrieve the link (and product data) from the database
LiveItem_Data.DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem o = new LiveItem();
o = LiveItem_Data.GetLive_ItemFromLID(lid);
if (HTTPStuff.RemoteFileExists(o.product_link))
{
Response.Redirect(o.product_link, true);
}
else
{
//generate an error
}
}
}
}
I stepped through the code and the product_link is working (manually cutting and pasting into a browser), and the remote page is being called (I'm testing the link with another site that has logging).
The browser however does not open (tried FF, IE, Opera, Chrome) the new URL.
The jQuery post:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID });
});
I verified that HTTPredirect feature is turned on in IIS Express (from Visual Studio 2012). Stumped!
I think from the jquery function, it will not redirect the page from server you will have to do this on client side itself i.e in the success part of the click function
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID }).success(function() {
//write the redirection code here
});
});
I don't think you're using post right. Post is for making a hidden service call and does not affect the browser window.
If you just want to redirect the browser window, and redir.aspx will accept either GET or POST, you can use window.location.href:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
window.location.href = "redir.aspx?lid=" + ListID;
});
If redir.aspx does not accept GET, I suggest you create a hidden form on your page (with an lid hidden input element) and post it programmatically.