SignalR Page Refresh Makes Multiple Connection - c#

I want to show some live random data on client using SignalR.
Problem Is whenever I refresh the page it creates one more connection
and shows multiple data.
Mostly I think my approach is wrong.
So what I have done.
Step 1: Installed SignalR Using Nuget Install-Package Microsoft.AspNet.SignalR
Step 2: Made changes in Startup.cs File as follows.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR(); //Added this line for SignalR
}
}
Step 3: Created Hub Class. "ServerStatisticsHub.cs"
public class ServerStatisticsHub : Hub
{
public void ServerParameter()
{
Random r = new Random();
int p = 0;
int m = 0;
int s = 0;
while(true) //May be this is the foolish thing I'm doing
{
p = r.Next(0, 100);
m = r.Next(0, 100);
s = r.Next(0, 100);
Clients.All.broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
System.Threading.Thread.Sleep(2000);
}
}
}
Step 4: Created an View in Home "ServerState.cshtml".
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<title>TestSignalR</title>
</head>
<body>
<div id="serverProcessor"></div>
<div id="serverMemory"></div>
<div id="serverStorage"></div>
<script src="#Url.Content("~/Scripts/jquery-2.2.3.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.signalR-2.2.1.min.js")"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var serverStatistics = $.connection.serverStatisticsHub;
// Create a function that the hub can call back to display messages.
serverStatistics.client.broadcastServerStatistics = function (serverStat) {
var serverStatistic = JSON.parse(serverStat);
console.log(serverStatistic);
$('#serverProcessor').html(serverStatistic.processor + "%");
$('#serverMemory').html(serverStatistic.memory + "%");
$('#serverStorage').html(serverStatistic.storage + "%");
};
// Start the connection.
$.connection.hub.start().done(function () {
serverStatistics.server.serverParameter();
});
});
</script>
</body>
</html>

I found a workaround to fix this issue.
I don't know how to describe it.
The following code change done in Hub Class file. "ServerStatisticsHub.cs"
Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
Changed
Clients.All.
to
Clients.Client(Context.ConnectionId).

Related

C#.Net Update Column in HTML Table After Page has Been Rendered

I'm trying to send new values to an HTML table after a page has already been rendered. New values are sent 'x minutes' after the page has already been rendered on the client end, and are displayed in a new column in the html table.
The HTML is created with C# code with the code behind file, and initiated via a function call inside the actual html on the aspx page.
htmlStr = "<tr><td>" + market[0].runners[marketCounter].runnerName + "</text></td>" + "<td>" + marketOdds[0].runners[marketCounter].lastPriceTraded.ToString() + "</td>" + "<td>" + "</td>" + "<td>" + NewValuesin10Mins()???????????????? + </td></tr>;
if you want to modify the client side after render, try to use the function RegisterStartupScript, the script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised
public String GetNewKey()
{
String _string_key = String.Empty;
Guid _guid = Guid.NewGuid();
foreach (char _char in Convert.ToBase64String(_guid.ToByteArray()))
{
_string_key += char.IsLetterOrDigit(_char) ? _char.ToString() : string.Empty;
}
return _string_key;
}
public void RunScript(String _script)
{
String function = #"<script type='text/javascript'> $(function () { " + _script + " }); </script>";
this.ClientScript.RegisterStartupScript(_page.GetType(), Utilities.GetNewKey(), function, false);
}

Why code behind C# button_clicked function doesn't call Javascript function?

I want to test the C# code side when user click the button, the method in C# function should be able to call the JavaScript function to show alert C# public variable results. Somehow it doesn't call anything at all. At the bottom of ButtonRequest_Click function, I wrote Page.ClientScript.RegisterStartupScript(this.GetType(), "CreateIsm();", "CreateIsm();", true); to call CreateIsm(); function in JavaScript. Maybe this doesn't work?
Here is C# codes,
public Collection<PSObject> output = new Collection<PSObject>();
public string deviceName = "";
public string ipAddresses = "";
public string YourScript = "";
protected void ButtonRequest_Click(object sender, EventArgs e)
{
deviceName = string.Empty;
ipAddresses = string.Empty;
HiddenName.Visible = false;
string str = "";
string ipAddress = "";
string name = "";
var tbids = (List<string>)Session["tbids"];
//create a powershell
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
RunspaceInvoke invoke = new RunspaceInvoke();
Pipeline pipeline = runSpace.CreatePipeline();
Command invokeScript = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb = invoke.Invoke(#"{D:\Scripts\Get-FreeAddress.ps1 '" + DropDownListContainer.SelectedValue + "' " + DropDownListIP.SelectedValue + "}")[0].BaseObject as ScriptBlock;
invokeScript.Parameters.Add("scriptBlock", sb);
invokeScript.Parameters.Add("computername", TextBoxServer.Text);
pipeline.Commands.Add(invokeScript);
Collection<PSObject> output = pipeline.Invoke();
runSpace.Close();
Runspace runSpace2 = RunspaceFactory.CreateRunspace();
runSpace2.Open();
foreach(PSObject psObject in output)
{
ipAddress = "" + psObject;
ipAddresses += "" + psObject;
foreach(var id in tbids)
try
{
name = Request[id];
deviceName += Request[id] + "\r\n";
Pipeline pipeline2 = runSpace2.CreatePipeline();
Command invokeScript2 = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb2 = invoke.Invoke(#"{D:\Scripts\Set-IPAddress.ps1 " + ipAddress + " " + name + "}")[0].BaseObject as ScriptBlock;
invokeScript2.Parameters.Add("scriptBlock", sb2);
invokeScript2.Parameters.Add("computername", TextBoxServer.Text);
pipeline2.Commands.Add(invokeScript2);
tbids.RemoveAt(0);
Collection<PSObject> output2 = pipeline2.Invoke();
foreach(PSObject psObject2 in output2)
{
str = str + psObject2;
}
break;
}
catch
{
}
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "CreateIsm();", "CreateIsm();", true);
}
Javascript on aspx side in html,
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" CodeBehind="~/Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script>
CreateIsm = function (funct) {
alert('<%=ipAddresses%>');
alert('<%=deviceName%>');
};
</script>
</head>
<body>
<form id="form1" runat="server">
//the are html codes here but I cut it off except ButtonRequest
<asp:Button ID="ButtonRequest" runat="server" Text="Request" Visible="False"
onclick="ButtonRequest_Click" />
</form>
</body>
</html>
Read this: http://msdn.microsoft.com/en-us/library/3hc29e2a(v=vs.100).ASPX
You can use OnClientClick like this:
<asp:button id="Button1" runat="server" OnClientClick="return confirm('Ok to post?')" onclick="Button1_Click" Text="Click!" />

asp.net gridview printing

i am printing a gridview in asp.net that is contained within a panel - it works in IE perfectly
In Opera 12.02 it appears to be printing out my main form not the print page ? Do you know why this is.
In Mozilla firefox 16.0.2 it only loads one page in the print preview and prints that one page? Do you know why this is?
I'm assuming the issue is in my javascript - i can post markup if needed but hopefully that will not be required.
thanks
Damo
javascript
<script type="text/javascript">
function PrintGridData(GridToPrint, PanelName) {
try {
var Grid = document.getElementById(GridToPrint);
var printContent = document.getElementById(PanelName);
//alert(printContent);
if (Grid) // See if the Grid Exists First
{
if (Grid.rows.length > 0) { // See if the Grid contains any rows
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var Database = 'ProductionDatabase';
var windowName = 'Report';
var AuditPrintDetailEverypage = UserLoggedIn + ' Time : ' + strDateTime ;
var AuditPrintDetailLastPage = ' System Report ' + ' Source Database: ';
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="assets/css/Print.css" rel="stylesheet" type="text/css" /><title>' + AuditPrintDetailEverypage + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write(' ' + AuditPrintDetailLastPage);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
//alert(printContent.innerHTML);
//alert(WinPrint.document);
if (window.opera) {
//alert('opera browser detected')
window.onload = window.print();
//window.onload = WinPrint.print();
//WinPrint.close();
}
else {
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
else { // No Results to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Results to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
}
}
else { // No Grid to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Grid to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
function AddZero(num) {
try {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
</script>
window.onload = window.print(); should be window.onload = window.print;
Also my css had overflow: hidden; which opera and mozilla dont like so i removed these
now its working ok
thanks
damo

asp gridview Print

I have a javascript function as shown below that is working. Note - i did change the line (from the internet examples)
WinPrint.document.write(printContent.innerHTML);
to
WinPrint.document.write(printContent.outerHTML);
i dont think i am supposed to do that but with innerhtml the grid wasnt formatted at all but with the value outerhtml it was fine...
So to summarize
why cant i use innerhtml like all the examples show - must be a bug
in my code somewhere
thanks,
Damo
Javascript
<script type="text/javascript">
function PrintGridData(GridToPrint) {
var printContent = document.getElementById(GridToPrint);
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var windowName = 'Report';
var AuditPrintDetail = 'Report ' + UserLoggedIn + " " + strDateTime;
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="cssreference" rel="stylesheet" type="text/css" /><link href="assets/css/Main.css" rel="stylesheet" type="text/css" /> <title>' + AuditPrintDetail + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.outerHTML);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
function printItn() {
//you can put your contentID which is you want to print.
var printContent = document.getElementById('<%= pnlForm.ClientID %>');
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
// you should add all css refrence for your Gridview. something like.
var WinPrint= window.open(windowUrl,windowName,'left=300,top=300,right=500,bottom=500,width=1000,height=500');WinPrint.document.write('<'+'html'+'><head><link href="cssreference" rel="stylesheet" type="text/css" /><link href="gridviewcssrefrence" rel="stylesheet" type="text/css" /></head><'+'body style="background:none !important"'+'>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write('<'+'/body'+'><'+'/html'+'>');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
reference it from here... click to view discussion.
and also see complete example with sample code javascript to print gridview data from client-side.

The remote server returned an error: (401) Unauthorized

I m trying to embed Bulk SMS API in my website ...But the code is giving 401
ASPX :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Send SMS</title>
</head>
<body>
<form id="form2" runat="server">
<div>
</div>
</form>
</body>
</html>
ASPX.CS
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Net;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
public void SendSMS()
{
UriBuilder urlBuilder = new UriBuilder();
urlBuilder.Host = "IP";
urlBuilder.Port = port;
string UserName = "username";
string password = "password";
string PhoneNumber = "919999999999";
string Text = "Testing";
string Sender = "sender name";
urlBuilder.Query = string.Format("user=" + UserName + "password=" + password + "PhoneNumber=" + PhoneNumber + "&Text=" + Text + "&Sender=" + Sender);
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(urlBuilder.ToString(), false));
HttpWebResponse httpResponse = (HttpWebResponse)(httpReq.GetResponse());
}
protected void Page_Load(object sender, EventArgs e)
{
SendSMS();
}
}
This code:
urlBuilder.Host = "IP";
urlBuilder.Port = port;
Is telling your HttpWebRequest to go to http://IP:port as in literally the server IP. http://IP doesn't exist, you need to put the actual hostname there, like "www.google.com"...whatever server you're trying to hit.
The problem is most likely in:
urlBuilder.Query = string.Format("user=" + UserName + "password=" + password + "PhoneNumber=" + PhoneNumber + "&Text=" + Text + "&Sender=" + Sender);
You're missing a few &s. Should probably be something like:
urlBuilder.Query = string.Format("user=" + UserName + "&password=" + password + "&PhoneNumber=" + PhoneNumber + "&Text=" + Text + "&Sender=" + Sender);
Edit: Also there is no reason to be using string.Format() here. This would work the same:
urlBuilder.Query = "user=" + UserName + "&password=" + password + "&PhoneNumber=" + PhoneNumber + "&Text=" + Text + "&Sender=" + Sender;

Categories