SignalR: can't connect to local or any other ip address - asp.net-mvc

I am trying to make SignalR server and client architecture in which i am able to connect to "http://localhost:8080" or http://127.0.0.1:8080/ but i am not able to connect my local ip address like "192. x.x.x" so what could be reason?
please help me i am also placing my code overhere...
public partial class WinFormsServer : Form
{
private IDisposable SignalR { get; set; }
const string ServerURI = "http://localhost:8080";
private void ButtonStart_Click(object sender, EventArgs e)
{
WriteToConsole("Starting server...");
ButtonStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
SignalR = WebApp.Start(ServerURI);
}
catch (TargetInvocationException)
{
WriteToConsole("Server failed to start. A server is already running on " + ServerURI);
//Re-enable button to let user try to start server again
this.Invoke((Action)(() => ButtonStart.Enabled = true));
return;
}
this.Invoke((Action)(() => ButtonStop.Enabled = true));
WriteToConsole("Server started at " + ServerURI);
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}

I tried different solutions but could not find correct one.
Finally I found the issue that was only related to the permission.
Run your SignalR server application as administrator. It will start running on the local IP like 192.168.X.X:9090 and then your client application can connect this server from any other PC using this IP address.
class Program
{
static void Main(string[] args)
{
var url = $"http://{GetLocalIPAddress()}:8080";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine($"Server running at {{{url}}}");
Console.ReadLine();
}
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
}

To get your local IP address you could use this function:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
If you want to use FQDN - Fully Qualified Domain Name, then you could use this function:
public static string GetLocalFQDN()
{
var props = IPGlobalProperties .GetIPGlobalProperties();
return props.HostName + (string.IsNullOrWhiteSpace(props.DomainName) ? "" : "." + props.DomainName);
}
After that you could use:
SignalR = WebApp.Start("http://" + GetLocalFQDN() + ":8080");
or
SignalR = WebApp.Start("http://" + GetLocalIPAddress() + ":8080");
I hope this helps.

Since you are using this source i used the same too.
-For FQDN, first create the function below.
public static string GetLocalFQDN()
{
var props = IPGlobalProperties.GetIPGlobalProperties();
return props.HostName + (string.IsNullOrWhiteSpace(props.DomainName) ? "" : "." + props.DomainName);
}
Then modify the const string ServerURI to:
string ServerURI =String.Concat("http://",GetLocalFQDN(),":8080");
-For LocalIPAdress, first create the function below which will the your local address:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
and change the string ServerURI =String.Concat("http://",GetLocalFQDN(),":8080"); to:
string ServerURI =String.Concat("http://",GetLocalIPAddress(),":8080");
Hope this helps you.
Note: The changes should be done in the WinFormsServer:Form class on the WinFormsServer project.

Related

StackExchange.Redis can't write to or read from local Redis Server when I deploy my asp.Net Mvc application to IIS 8.5 on Windows Server 2012 R2

I have an asp.net mvc application which works on .Net 4.6.2 framework. This app has Dependency Injection with Inversion of Control technics using SimpleInjector and Aspect Oriented Programming technics using PostSharp.
StackExchange.Redis library working fine on my local machine when I start to debug my solution in Visual Studio 2015 Ent. on Windows 10 Pro. I can write to and read from redis server on my local also my app can write to and read from redis server on my local when I deploy/publish my app IIS server on my remote server.
But I can't write the redis server on remote server. I check the ports and firewalls but it can't write or read in any way. Also when I trace my app it can successfully connect to redis server on same server also can send commands to it but when look up to redis monitor it does not show that commands.
What could be cause to this?
Code Samples are below
Redis Cache Manager
using System;
using System.Collections.Generic;
using System.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace Cits.Portal.Core.CrossCuttingConcern.Caching.Redis
{
public class RedisCacheManager : ICacheManager
{
private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
var configurationOptions = new ConfigurationOptions();
#if DEBUG
configurationOptions.EndPoints.Add("localhost", 6379);
#else
configurationOptions.EndPoints.Add("141.11.11.212", 6379);
#endif
configurationOptions.AllowAdmin = true;
configurationOptions.AbortOnConnectFail = false;
return ConnectionMultiplexer.Connect(configurationOptions);
});
public static ConnectionMultiplexer Connection => LazyConnection.Value;
public static IDatabase RedisCache => Connection.GetDatabase();
public void Add(string key, object data, int cacheTime)
{
if (data == null || IsAdd(key))
return;
var value = TimeSpan.FromMinutes(cacheTime);
RedisCache.StringSet(key, Serialize(data), value);
}
public T Get<T>(string key)
{
var value = RedisCache.StringGet(key);
if (!value.HasValue)
return default(T);
return Deserialize<T>(value);
}
public bool IsAdd(string key)
{
return RedisCache.KeyExists(key);
}
public void Remove(string key)
{
RedisCache.KeyDelete(key);
}
public void RemoveByPattern(string pattern)
{
var endPoints = Connection.GetEndPoints();
foreach (var endpoint in endPoints)
{
var server = Connection.GetServer(endpoint);
var enumerable = server.Keys(RedisCache.Database, pattern);
foreach (var current in enumerable)
Remove(current);
}
}
public void Clear()
{
var endPoints = Connection.GetEndPoints();
foreach (var endpoint in endPoints)
{
var server = Connection.GetServer(endpoint);
var enumerable = server.Keys(RedisCache.Database);
foreach (var current in enumerable)
Remove(current);
}
}
public List<string> GetKeyList()
{
var list = new List<string>();
var endPoints = Connection.GetEndPoints();
foreach (var endpoint in endPoints)
{
var server = Connection.GetServer(endpoint);
var enumerable = server.Keys(RedisCache.Database);
foreach (var redisKey in enumerable)
list.Add(redisKey);
}
return list;
}
protected virtual string Serialize(object serializableObject)
{
var jsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
return JsonConvert.SerializeObject(serializableObject, jsonSerializerSettings);
}
protected virtual T Deserialize<T>(string serializedObject)
{
if (serializedObject == null)
return default(T);
var jsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
return JsonConvert.DeserializeObject<T>(serializedObject, jsonSerializerSettings);
}
}
}
Redis Cache Aspect
using System;
using System.Linq;
using Cits.Portal.Core.CrossCuttingConcern.Caching.Redis;
using PostSharp.Aspects;
namespace Cits.Portal.Core.Aspects.Caching
{
[Serializable]
public class CacheAspectAttribute : MethodInterceptionAspect
{
private readonly int _cacheTimeOut;
public CacheAspectAttribute(int cacheTimeOut = 540)
{
_cacheTimeOut = cacheTimeOut;
}
public override void OnInvoke(MethodInterceptionArgs args)
{
var cacheManager = new RedisCacheManager();
if (args.Method.ReflectedType != null)
{
var methodFullName = $"{args.Method.ReflectedType.Namespace}.{args.Method.ReflectedType.Name}.{args.Method.Name}";
var arguments = args.Arguments.ToList();
var key = $"{methodFullName}({string.Join(",", arguments.Select(x => x?.ToString() ?? "<null>"))})";
if (cacheManager.IsAdd(key))
{
args.ReturnValue = cacheManager.Get<object>(key);
return;
}
base.OnInvoke(args);
cacheManager.Add(key, args.ReturnValue, _cacheTimeOut);
}
}
}
}
Our Module List Method which is cached
[CacheAspect]
public List<ModuleViewModel> GetListAsList()
{
var rowLogQuery = _rowLogService.GetListQueryable("Module");
var moduleQuery =
_moduleDal.GetQueryable(p => p.RowStateId != _rowState)
.Select(p => new ModuleViewModel
{
Id = p.Id,
Code = p.Code,
Name = p.Name,
IsActive = p.IsActive,
RowLogViewModel = rowLogQuery.FirstOrDefault(q => q.RowId.Equals(p.Id)),
RowStateId = p.RowStateId
}).ToList();
return moduleQuery;
}
Also These are my redis.windows.configs
bind 127.0.0.1
bind 141.11.11.212
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 0
databases 16
Also These are my redis.windows.service.configs
bind 127.0.0.1
bind 141.11.11.212
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 0
databases 16
Also I don't have redis auth password. I'm testing my app on remote server using remote servers browser but result the same.
Can you give me any suggestions about steps that I can find the issue/s?
And this the redis.server.log
[2252] 04 Aug 15:05:42.664 # Creating Server TCP listening socket 141.11.11.212:6379: bind: No error
[7504] 07 Aug 10:03:01.666 * Redis 3.2.100 (00000000/0) 64 bit, standalone mode, port 6379, pid 7504 ready to start.
[7504] 07 Aug 10:03:01.666 # Server started, Redis version 3.2.100
[7504] 07 Aug 10:03:01.666 * DB loaded from disk: 0.002 seconds
[7504] 07 Aug 10:03:01.666 * The server is now ready to accept connections on port 6379

Signalr .Net Client Console application receive messages from hub only once

I'm using Signalr .Net Client in my Console application to receive messages from the Signalr Hub which is a separate web application.
My console application is connecting to the hub correctly and receive message from the hub only once. Then the client method in the Signalr .Net client not getting called.
Once I stop the console application and run it, again it receive a message from the hub only once and nothing happens.
Here is my Hub Code
public override Task OnConnected()
{
try
{
var cType = Context.QueryString["type"];
var connectionId = Context.ConnectionId;
var connectedUserList = (from d in Users
where d.ClientType == cType
select d).ToList();
if (connectedUserList.Count > 0)
{
var conUser = connectedUserList.First<ConnectedUsers>();
conUser.ConnectionIds.Add(connectionId);
}
else
{
var newUser = new ConnectedUsers
{
ConnectionIds = new HashSet<string> {connectionId}
,
ClientType = cType
};
Users.Add(newUser);
}
}
catch (Exception ex)
{
).Error(ex);
}
return base.OnConnected();
}
And My .Net Client Connection
static void Main(string[] args)
{
SignalrHandler();
Console.ReadLine();
}
public static async void SignalrHandler()
{
var url = ConfigurationSettings.AppSettings["Url"] ?? #"http://localhost:1010/";
var querystringData = new Dictionary<string, string> { { "type", "WIN" } };
_hubConnection = new HubConnection(url, querystringData);
MarcolinMainProxy = _hubConnection.CreateHubProxy("MainHub");
MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type));
await _hubConnection.Start();
}
Client Method
private static void InvokeMethod(string type)
{
Console.WriteLine(String.Format("Recieved Message From Server On :{0}",System.DateTime.Now.ToString()));
Console.WriteLine("Message Received");
Console.ReadLine();
}
And This happens when I use an Invoke method with following line
MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type));
And when I use following line it works..
MarcolinMainProxy.On<string>("sendAlert", stock => Console.WriteLine("Symbol {0} Price {1}", "sd", "sdde"));
Check the following link
https://damienbod.com/2013/11/13/signalr-messaging-a-complete-client-with-a-console-application/
You have to change your code to
MarcolinMainProxy.On<string>("sendAlert", InvokeMethod);

How get current url in Microsoft Edge? [duplicate]

I'm trying to read out the TITLE & URL from the Microsoft EDGE Browser.
Doing this with System.Windows.Automation most preferably since the code base already uses this for other problems.
Is it possible with System.Windows.Automation?
How to access the URL?
I'm currently this far:
AutomationId "TitleBar"
ClassName "ApplicationFrameWindow"
Name = [string]
=> Reading out this element gives me the TITLE
=> Walking it's children, I find the item "addressEditBox":
AutomationId "addressEditBox"
ClassName "RichEditBox"
Name "Search or enter web address"
=> I always get back the string "Search or enter web address"
=> This is the control where the url is in, though it isn't updated as the user goes to a website, it always returns a fixed string.
In code:
var digger1 = AutomationElement.FromHandle(process.MainWindowHandle).RootElement.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d1 in digger1 {
if(d1.Current.ClassName.Equals("ApplicationFrameWindow")) {
var digger2 = d1.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d2 in digger2) {
if(d2.Current.ClassName.Equals("Windows.Ui.Core.CoreWindow")) {
var digger3 = d2.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d3 in digger3) {
if(d3.Current.AutomationId.Equals("addressEditBox")) {
var url = d3.Current.Name;
return url;
}
}
}
}
}
}
You're almost there. You just need to get the TextPattern from the addressEditBox element. Here is a full sample Console app that dumps out all currently running Edge's windows on the desktop:
class Program
{
static void Main(string[] args)
{
AutomationElement main = AutomationElement.FromHandle(GetDesktopWindow());
foreach(AutomationElement child in main.FindAll(TreeScope.Children, PropertyCondition.TrueCondition))
{
AutomationElement window = GetEdgeCommandsWindow(child);
if (window == null) // not edge
continue;
Console.WriteLine("title:" + GetEdgeTitle(child));
Console.WriteLine("url:" + GetEdgeUrl(window));
Console.WriteLine();
}
}
public static AutomationElement GetEdgeCommandsWindow(AutomationElement edgeWindow)
{
return edgeWindow.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
new PropertyCondition(AutomationElement.NameProperty, "Microsoft Edge")));
}
public static string GetEdgeUrl(AutomationElement edgeCommandsWindow)
{
var adressEditBox = edgeCommandsWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "addressEditBox"));
return ((TextPattern)adressEditBox.GetCurrentPattern(TextPattern.Pattern)).DocumentRange.GetText(int.MaxValue);
}
public static string GetEdgeTitle(AutomationElement edgeWindow)
{
var adressEditBox = edgeWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "TitleBar"));
return adressEditBox.Current.Name;
}
[DllImport("user32")]
public static extern IntPtr GetDesktopWindow();
}

c# server and android client,connectivity

i am trying to develop an application in c# which acts as a server for an android phone.i am using 32feet.net for bluetooth in c# and i have a server running in android, which simply sends a socket to server. the server running in pc need to listen the connection and display ,the status of connection. all these things are base for my project. the server code is as shown :
namespace testserver
{
class Program
{
static void Main(string[] args)
{
BluetoothClient bc = new BluetoothClient();
BluetoothDeviceInfo[] dev;
BluetoothDeviceInfo td=null;
Guid id = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");
// Console.WriteLine(id.ToString());
// Console.Read();
dev = bc.DiscoverDevices();
foreach (BluetoothDeviceInfo d in dev)
{
if (d.DeviceName == "ST21i")//my phone name
{
td=d;
break;
}
}
try
{
BluetoothAddress addr = td.DeviceAddress;
BluetoothListener bl = new BluetoothListener(addr, id);
bl.Start();
if (bl.AcceptSocket() != null)
Console.WriteLine("Success");
}
catch (Exception e)
{
Console.WriteLine("Exception : "+e.Message);
Console.Read();
}
}
}
}
and here is my android code :
public class MainActivity extends Activity {
BluetoothAdapter adapter;
BluetoothDevice bd;
BluetoothSocket sock;
OutputStream ostr;
int REQUEST_ENABLE_BT;
String str="5C:AC:4C:DD:CC:0D";
private static final UUID id=UUID.fromString("00112233-4455-6677-8899- aabbccddeeff");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter=BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked button", Toast.LENGTH_LONG).show();
try
{
bd=adapter.getRemoteDevice(str); Toast.makeText(getApplicationContext(),"Server is running at "+bd.getName().toString()+"...", Toast.LENGTH_LONG).show();
sock=bd.createInsecureRfcommSocketToServiceRecord(id); sock.connect();
ostr=sock.getOutputStream();
ostr.write(0);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
my problems are :
1) in pc i am getting an exception, the requested address is not valid in its context(so that server cant run )
2)in phone, the service discovery failed( because of unavailability of server)
how can i correct the server and run the program ?
i changed the bluetooth listener object's creation from
BluetoothListener bl = new BluetoothListener(addr, id); to
BluetoothListener bl = new BluetoothListener(id); and everything worked fine..

Which MBeans to use (and how) to programmatically determine memory lows for app (CQ5) deployed inside Weblogic

I have to write a standalone Java app that monitors CQ5, deployed inside Weblogic (especially memory usage).
I was able to connect to the Domain Runtime Server in weblogic, using the class below (as found in the docs).
Now, I want to know which MBeans I need to monitor memory lows, so I can fire an event whenever a certain threshold is being hit.
Can any of you give me some insight? This is a pure JMX / Java question, unrelated to CQ.
I am trying to programmatically recreate what Jconsole already does. But I need it programmatically because I need to talk to an external API in case certain thresholds are being hit.
public class PrintServerState {
private static MBeanServerConnection connection;
private static JMXConnector connector;
private static final ObjectName service;
private static final ObjectName bundleWrite;
static {
try {
service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
} catch (MalformedObjectNameException e) {
throw new AssertionError(e.getMessage());
}
}
/*
* Initialize connection to the Domain Runtime MBean Server
*/
public static void initConnection(String hostname, String portString,
String username, String password) throws IOException,
MalformedURLException {
String protocol = "t3";
Integer portInteger = Integer.valueOf(portString);
int port = portInteger.intValue();
String jndiroot = "/jndi/";
String mserver = "weblogic.management.mbeanservers.domainruntime";
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname,
port, jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
"weblogic.management.remote");
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
System.out.println("***************** get mbean count ************************* " + connection.getMBeanCount());
Set<ObjectName> mbeans = connection.queryNames(null, null);
for (ObjectName mbeanName : mbeans) {
System.out.println(mbeanName);
}
System.out.println("********************** ---- ***********************");
}
/*
* Print an array of ServerRuntimeMBeans.
* This MBean is the root of the runtime MBean hierarchy, and
* each server in the domain hosts its own instance.
*/
public static ObjectName[] getServerRuntimes() throws Exception {
return (ObjectName[])connection.getAttribute(service,
"ServerRuntimes");
}
/*
* Iterate through ServerRuntimeMBeans and get the name and state
*/
public void printNameAndState() throws Exception {
ObjectName[] serverRT = getServerRuntimes();
System.out.println("got server runtimes");
int length = (int) serverRT.length;
for (int i = 0; i < length; i++) {
String name = (String) connection.getAttribute(serverRT[i],
"Name");
String state = (String) connection.getAttribute(serverRT[i],
"Type");
System.out.println("Server name: " + name + ". Server state: "
+ state);
}
}
public static void main(String[] args) throws Exception {
String hostname = args[0];
String portString = args[1];
String username = args[2];
String password = args[3];
PrintServerState s = new PrintServerState();
System.out.println("hostname " + hostname);
System.out.println("portString " + portString);
System.out.println("username " + username);
System.out.println("password " + password);
initConnection(hostname, portString, username, password);
System.out.println("**************************************************");
s.printNameAndState();
connector.close();
}
}
Would this help -
domainRuntime()
cd('/ServerRuntimes/' + eval('managedServerName') + '/JVMRuntime/' + eval('managedServerName'))
heapFreeCurrentPerOld = str(cmo.getHeapFreePercent())
heapFreeCurrentValOld = str(cmo.getHeapFreeCurrent())

Resources