using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace EchoServer
{
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 31337);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
String msg = "This is a malicious service, muahahahahahahaha!!!";
byte[] encoded_msg = Encoding.ASCII.GetBytes(msg);
handler.Send(encoded_msg);
// An incoming connection needs to be processed.
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
namespace MaliciousService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Thread t = new Thread(EchoServer.SynchronousSocketListener.StartListening);
t.Start();
}
protected override void OnStop()
{
}
}
}
I built this simple service that creates a synchronous socket listener which binds on localhost in port 31337 in a thread. but after I run the service, it seems that the port isn't taken, and the socket calls failed. any ideas why this could happen? (the server was copied from microsoft documentation)
Problem solved. the lines
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 31337);
Didn't bind me to loopback. I changed it to
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 31337);
Related
I can download some files in a random page (a pdf from google, for example) but in the page I need to download them from, I get "Unsuccessful Download" notification on smartphone, with no exception thrown for me. Is there a way to know why this is happening?
Code from the renderer that I use to download below.
using Android.App;
using Android.Webkit;
using MPS.Libertas.Mobile.Droid.Renderers;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Android.Content;
using Xamarin.Essentials;
using System.IO;
using System;
using Android.Widget;
using static Android.Provider.MediaStore;
[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(MPS_MyWebViewRenderer))]
namespace MPS.Libertas.Mobile.Droid.Renderers
{
internal class MPS_MyWebViewRenderer : WebViewRenderer
{
public MPS_MyWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Download += OnDownloadStart;
}
private void OnDownloadStart(object sender, Android.Webkit.DownloadEventArgs e)
{
try
{
var url = e.Url;
string url_formatted = url.Replace("blob:", "");
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url_formatted));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetMimeType("application/pdf");
// if this path is not create, we can create it.
string thmblibrary = FileSystem.AppDataDirectory + "/download";
if (!Directory.Exists(thmblibrary))
Directory.CreateDirectory(thmblibrary);
request.SetDestinationInExternalFilesDir(Android.App.Application.Context, FileSystem.AppDataDirectory, "download");
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
dm.Enqueue(request);
}
catch (System.Exception ex)
{
var message = ex.Message;
throw;
}
}
}
}
I need to make a connection from C# Windows Forms application to an on premise D365 FO.
So far, I created an Azure account and registered an application, so by now I have "Application (client) ID", "Directory (tenant) ID" and created a Client Secret.
What do I need to do to connect to D365 FO by using Data management package REST API?
Take a look at the Authorization Helper, which is part of the sample console app provided by Microsoft for the data management api (see the last sentence in https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-management-api). The Program.cs of the app shows how the Authentication Helper is used.
AuthorizationHelper.cs
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AuthorizationHelper
{
public class AuthorizationHelper
{
const string aadTenant = "https://login.windows.net/<your-tenant>";
public const string aadResource = "https://<yourAOS>.cloudax.dynamics.com";
const string aadClientAppId = "<client id>";
const string aadClientAppSecret = "<client secret>";
/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
/// <returns>The authentication header for the Web API call.</returns>
public static string GetAuthenticationHeader()
{
AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
AuthenticationResult authenticationResult;
var creadential = new ClientCredential(aadClientAppId, aadClientAppSecret);
authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
// Create and get JWT token
return authenticationResult.CreateAuthorizationHeader();
}
}
}
Program.cs
using ODataClient.Microsoft.Dynamics.DataEntities;
using System;
namespace DataPackageHandler
{
using AuthorizationHelper;
using Microsoft.OData.Client;
class Program
{
static void Main(string[] args)
{
string ODataEntityPath = AuthorizationHelper.aadResource + "/data";
Uri oDataUri = new Uri(ODataEntityPath, UriKind.Absolute);
var d365Client = new Resources(oDataUri);
d365Client.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(delegate (object sender, SendingRequest2EventArgs e)
{
var authenticationHeader = AuthorizationHelper.GetAuthenticationHeader();
e.RequestMessage.SetHeader("Authorization", authenticationHeader);
});
PackageImporter.ImportPackage(d365Client, #"..\debug\SampleData\usmf_asset-major-types-01.zip");
PackageExporter.ExportPackage(d365Client, #"..\debug\SampleData\");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
I have seen a number of solutions for .Net Core 2 that I cannot seem to translate to 3.0. In most cases they do not use the Templated Program and Startup, but are purpose-built.
I use the WebApi template supplied in Visual Studio 2019 Community (latest patches).
In Core 3.0, the Configuration appsettings.json is automatically loaded and via DI in startup, is available to the rest of my code.
I need a couple of the items from appsettings.json, Configuration.GetSection("OrAppSettings")["OrSvrBaseUrl"]
Configuration.GetSection("OrAppSettings")["OrSvrUrlPort"] to be available in order to set the Http.sys Options.UrlPrefixes variable serverName in the Program.cs file.
I use Http.sys, as the Apis will be running in internal servers, as self-hosted, and using Kestrel, would only run at localhost. Therefore they will be unreachable unless Kestrel is run behind IIS. Http.sys can run as a self-hosted service, reachable across the LAN.
The apis etc are part of a larger solution offered to many of our customers and must fit into a variety of scenarios over which we have no real control.
I probably also need the same appsettings items for configuring Swagger, but that will be done in Startup.
I also need to use appsettings.json to provide configuration in the WebAPI client asp.net programs, but I have that covered, since DI from Startup is all I need there.
My appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"OrAppSettings": {
"ClientName": "some customer name",
"AsoAka": "mwp",
"AsoLocation": "shadow-10",
"AsoRouting": "unauthenticated",
"AsoClientType": "3",
"AsoClientUserId": "0",
"AsoClientUserName": "shadow-10\\ingres",
"AsoClientIpAddress": "",
"ORSvrBaseUrl": "http://shadow-10",
"ORSvrUrlPort": "5003",
"EnableSwaggerUI": "true"
},
"AllowedHosts": "*"
}
My Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
namespace MwpOrApiCore30
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static string serverName = "http://localhost:5005";
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
// Services
.ConfigureServices(services =>
{
services.Configure<EventLogSettings>(config =>
{
config.LogName = "Mwp Or Api";
config.SourceName = "MwpOrApi Source";
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseHttpSys(options =>
{
options.AllowSynchronousIO = true;
options.Authentication.Schemes = AuthenticationSchemes.None;
options.Authentication.AllowAnonymous = true;
options.MaxConnections = null;
options.MaxRequestBodySize = 30000000;
//options.UrlPrefixes.Add("http://shadow-10:5005");
options.UrlPrefixes.Add(serverName);
});
webBuilder.UseStartup<Startup>();
})
//.ConfigureWebHost(config =>
//{
// config.UseKestrel().UseUrls("http://0.0.0.0:5003");
//})
.UseWindowsService();
}
}
My MODIFIED Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
namespace MwpOrApiCore30
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static string serverName = "http://localhost:5005";
public static IHostBuilder CreateHostBuilder(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
serverName = configuration.GetSection("OrAppSettings")["ORSvrBaseUrl"];
serverName += ":" + configuration.GetSection("OrAppSettings")["ORSvrUrlPort"];
return Host.CreateDefaultBuilder(args)
.UseWindowsService()
. ConfigureServices(services =>
{
// services.AddHostedService<worker>();
})
// Services
.ConfigureServices(services =>
{
services.Configure<EventLogSettings>(config =>
{
config.LogName = "Mwp Or Api";
config.SourceName = "MwpOrApi Source";
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseHttpSys(options =>
{
options.AllowSynchronousIO = true;
options.Authentication.Schemes = AuthenticationSchemes.None;
options.Authentication.AllowAnonymous = true;
options.MaxConnections = null;
options.MaxRequestBodySize = 30000000;
//options.UrlPrefixes.Add("http://shadow-10:5005");
options.UrlPrefixes.Add(serverName);
});
webBuilder.UseStartup<Startup>();
});
}
}
}
My Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace MwpOrApiCore30
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Mwp OR WebApi",
Version = "v1" ,
Description = "An ASP.NET CORE 3.0 Web Api for MWP OpenRoad Server",
Contact = new OpenApiContact
{
Name = "xxxxxx",
Email = "someone#someplace.com.au"
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
string enableSwaggerUi = Configuration.GetSection("OrAppSettings").GetValue<string>("EnableSwaggerUI");
if (enableSwaggerUi == "true")
{
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Mwp OR API V1");
});
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I am working on a asp.net mvc5 project and I want to implement chatroom with signalR So I got Microsoft.Aspnet.SignalR from nuget and I used a SignalR Hub class for hub and now i want to override OnDisconnected() method .but I get error
'ChatHub.OnDisconnected()': no suitable method found to override
I dont know how to solve this problem please help me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace WebApplication3.Hubs
{
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
static ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
public void SendToSpecific(string name, string message, string to)
{
// Call the broadcastMessage method to update clients.
Clients.Caller.broadcastMessage(name, message);
Clients.Client(dic[to]).broadcastMessage(name, message);
}
public void Notify(string name, string id)
{
if (dic.ContainsKey(name))
{
Clients.Caller.differentName();
}
else
{
dic.TryAdd(name, id);
foreach (KeyValuePair<String, String> entry in dic)
{
Clients.Caller.online(entry.Key);
}
Clients.Others.enters(name);
}
}
public override Task OnDisconnected()
{
var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
string s;
dic.TryRemove(name.Key, out s);
return Clients.All.disconnected(name.Key);
}
}
}
For SignalR 2.1.0+, you need to use OnDisconected(bool stopCalled).
// Microsoft.AspNet.SignalR.Hub
// Summary:
// Called when a connection disconnects from this hub gracefully or due to a timeout.
//
// Parameters:
// stopCalled:
// true, if stop was called on the client closing the connection gracefully; false,
// if the connection has been lost for longer than the Microsoft.AspNet.SignalR.Configuration.IConfigurationManager.DisconnectTimeout.
// Timeouts can be caused by clients reconnecting to another SignalR server in scaleout.
//
// Returns:
// A System.Threading.Tasks.Task
public virtual Task OnDisconnected(bool stopCalled);
I am currently building a client app with a forms UI for a scanner device running Windows Mobile 6.5.
The client app needs to communicate via TCP async sockets with a console server app.
Server and client built using the following info:
Server & Client.
My dev/test environment is as follows:
Console server app running on windows 7 desktop.
The cradled device is connected via USB and Windows Mobile Device Center.
The mobile client app manages to connect to the server, send the message and receive a response back initially.
However when I try and send another message (new socket), the app fails. The new socket doesn't seem to be connected the second time around?
I get the following exception:
NullReferenceException
at
SocketClient.ReceiveCallback()at System.Net.LazyAsyncresult.InvokeCallback()
at
WorkerThread.doWork()...
Code follows:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SeatScan
{
static class Program
{
public static string serverIP;
public static int serverPort;
public static string response;
public static string message = string.Empty;
/// <summary>
/// The main entry point for the application.
/// </summary>
[MTAThread]
static void Main()
{
serverIP = MobileConfiguration.Settings["ServerIP"];
serverPort = int.Parse(MobileConfiguration.Settings["ServerPort"]);
Application.Run(new frmLogin());
}
public static void SendMessage(string message)
{
SocketClient.StartClient(serverIP, serverPort, message);
response = SocketClient.response;
}
}
static class SocketClient
{
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
// The response from the remote device.
public static string response = String.Empty;
public static void StartClient(string serverIP, int serverPort, string message)
{
response = String.Empty;
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(serverIP);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, serverPort);
// Create a TCP/IP socket.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.DontLinger, false);
//socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// Connect to the remote endpoint.
socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), socket);
connectDone.WaitOne();
MessageBox.Show("connect=" + socket.Connected, "Connecting?");
// Send test data to the remote device.
Send(socket, message);
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(socket);
receiveDone.WaitOne();
// Release the socket.
socket.Shutdown(SocketShutdown.Both);
socket.Close();
socket = null;
}
catch (Exception e)
{
//response = e.Message;
//Console.WriteLine(e.ToString());
MessageBox.Show(e.Message.ToString(), "StartClient");
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
//Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
//MessageBox.Show("Socket connected to {0}", client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
MessageBox.Show(e.Message.ToString(), "ConnectCallback");
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
MessageBox.Show(e.Message.ToString(), "Receive");
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
MessageBox.Show(e.Message.ToString() + e.InnerException.Message, "ReceiveCallback");
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
//Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
MessageBox.Show(e.Message.ToString() + e.InnerException.Message, "SendCallback");
}
}
}
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
}
Any help is appreciated.
Nevermind, I found the solution :)
This will teach me to copy paste sample code without fully understanding it.
It turns out, since I am reconnecting after first connect, I need to reset the state of the ManualResetEvents... Duh.
I needed to add:
connectDone.Reset();
sendDone.Reset();
receiveDone.Reset();
just before the line...
socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), socket);
I hope this helps someone as I lost a bit of hair figuring this one out...