I get this error when I try to connect an # IP (local).
Its a socket (tcp & udp).
I use an emulator
If there is a code to activate WiFi on WP7 emulator??
or maybe I deactivate WiFi coonnection
this all my code to add a connection to can use it
private void AddComputer_Click(object sender, RoutedEventArgs e)
{
IPAddress iPAddress;
if (!IPAddress.TryParse(this.IPAddressTextBox.Text, out iPAddress))
{
MessageBox.Show("Error: Invalid IP Address is empty");
return;
}
this.ipAddressToAdd = iPAddress;
this.progressBar.IsIndeterminate = true;
this.StatusTextBlock.Visibility=(Visibility)0;
this.ContentPanel.Visibility=(Visibility)1;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.AddComputerThread), new NetworkHandler.DiscoveredServer("", this.ipAddressToAdd, false, "", this.checkBoxPassword.IsChecked.Value, this.passwordBox1.Password, NetworkHandler.NetworkCategory.Unknown));
}
private void AddComputerThread(object obj)
{
NetworkHandler.DiscoveredServer info = (NetworkHandler.DiscoveredServer)obj;
NetworkHandlerCommon.ConnectResult connectResult = ConnectionHandler.ConnectToComputer(info, true, MyApp.MajorVersion, MyApp.MinorVersion);
base.Dispatcher.BeginInvoke(delegate
{
this.AddComputerDispatcher(connectResult);
}
);
}
private void AddComputerDispatcher(NetworkHandlerCommon.ConnectResult connectResult)
{
this.progressBar.IsIndeterminate = false;
this.StatusTextBlock.Visibility=(Visibility)1;
this.ContentPanel.Visibility=(Visibility)0;
if (connectResult == NetworkHandlerCommon.ConnectResult.Connected)
{
base.NavigationService.Navigate(MyApp.HomePage());
return;
}
this.ShowConnectError(connectResult);
}
private void ShowConnectError(NetworkHandlerCommon.ConnectResult result)
{
switch (result)
{
case NetworkHandlerCommon.ConnectResult.UpdateServer:
ErrorHandler.ShowErrorMessage(1003);
return;
case NetworkHandlerCommon.ConnectResult.UpdateClient:
ErrorHandler.ShowErrorMessage(1002);
return;
case NetworkHandlerCommon.ConnectResult.Failed:
ErrorHandler.ShowErrorMessage(1005);
return;
case NetworkHandlerCommon.ConnectResult.AuthenticationFailure:
MessageBox.Show("Error: Password is incorrect.");
return;
case NetworkHandlerCommon.ConnectResult.NetworkNotConnected:
MainPage.ShowNetworkDisconnectedMessage();
return;
default:
return;
}
}
and this class is showing the error that it will happen if true
public class ErrorHandler
{
private class ErrorInfo
{
public string ErrorMessage
{
get;
set;
}
public string ErrorURL
{
get;
set;
}
public ErrorInfo(string errorMessage, string errorURL)
{
this.ErrorMessage = errorMessage;
this.ErrorURL = errorURL;
}
}
private static Dictionary<int, ErrorHandler.ErrorInfo> errorMapping;
static ErrorHandler()
{
ErrorHandler.errorMapping = new Dictionary<int, ErrorHandler.ErrorInfo>();
ErrorHandler.errorMapping.Add(1000, new ErrorHandler.ErrorInfo("Error 1000: We have detected that WiFi is NOT turned-on at your phone.", "http://wp.me/p1ZVRQ-w"));
ErrorHandler.errorMapping.Add(1001, new ErrorHandler.ErrorInfo("Error 1001: Password is incorrect.", "http://wp.me/p1ZVRQ-E"));
ErrorHandler.errorMapping.Add(1002, new ErrorHandler.ErrorInfo("Error 1002: Older version of application is running. Update application from Marketplace.", "http://wp.me/p1ZVRQ-H"));
ErrorHandler.errorMapping.Add(1003, new ErrorHandler.ErrorInfo("Error 1003: Older version of PC Remote server is running at PC", "http://wp.me/p1ZVRQ-K"));
ErrorHandler.errorMapping.Add(1004, new ErrorHandler.ErrorInfo("Error 1004: Computer is connected to a public network", "http://wp.me/p1ZVRQ-d"));
ErrorHandler.errorMapping.Add(1005, new ErrorHandler.ErrorInfo("Error 1005: Failed connecting to your PC", "http://wp.me/p1ZVRQ-j"));
ErrorHandler.errorMapping.Add(1006, new ErrorHandler.ErrorInfo("Error 1006: Could not wake up your computer", "http://wp.me/p1ZVRQ-S"));
ErrorHandler.errorMapping.Add(1007, new ErrorHandler.ErrorInfo("Error 1007: Unable to resume the app.", "http://wp.me/p1ZVRQ-W"));
}
public static void ShowErrorMessage(int errorId)
{
if (ErrorHandler.errorMapping.ContainsKey(errorId))
{
ErrorHandler.ErrorInfo errorInfo = ErrorHandler.errorMapping[errorId];
string text = errorInfo.ErrorMessage + Environment.NewLine + Environment.NewLine + "Need help troubleshooting this? ";
if (MessageBox.Show(text, "Error", MessageBoxButton.OKCancel).Equals(1))
{
MyApp.GoToWebURL(errorInfo.ErrorURL);
}
}
}
}
Related
I've written a Xamarin.Forms Application that connects to an ESP32 via Bluetooth. Now I'd like to get a value from a CustomControl.JoystickControl from the MainPage.xaml Page.
I've tried it like that:
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public static Bluetooth.IBth bth = new Bluetooth.Bth();
public MainPage()
{
InitializeComponent();
Task.Run(async () => bth.Start("mecanumWheelRobot", 200, false));
}
public CustomControls.JoystickControl JoystickControlElement
{
get { return JoystickControl; }
}
public CustomControls.JoystickControl JoystickControlElement1
{
get { return JoystickControl1; }
}
}
Now I'd like to get the JoystickControlElement from the following Async Function:
var mainpage = new Views.MainPage();
string test = mainpage.test;
(these two lines are the problem)
class Bth : IBth
{
private CancellationTokenSource _ct { get; set; }
const int RequestResolveError = 1000;
public Bth()
{
}
public void Start(string name, int sleepTime = 200, bool readAsCharArray = false)
{
Task.Run(async () => loop(name, sleepTime, readAsCharArray));
}
private async Task loop(string name, int sleepTime, bool readAsCharArray)
{
BluetoothDevice device = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket BthSocket = null;
_ct = new CancellationTokenSource();
while (_ct.IsCancellationRequested == false)
{
try
{
Thread.Sleep(sleepTime);
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
else
System.Diagnostics.Debug.WriteLine("Adapter found!!");
if (!adapter.IsEnabled)
System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled.");
else
System.Diagnostics.Debug.WriteLine("Adapter enabled!");
System.Diagnostics.Debug.WriteLine("Try to connect to " + name);
foreach (var bd in adapter.BondedDevices)
{
System.Diagnostics.Debug.WriteLine("Paired devices found: " + bd.Name.ToUpper());
if (bd.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
{
System.Diagnostics.Debug.WriteLine("Found " + bd.Name + ". Try to connect with it!");
device = bd;
break;
}
}
if (device == null)
{
System.Diagnostics.Debug.WriteLine("Named device not found.");
MainThread.BeginInvokeOnMainThread(() =>
{
// Code to run on the main thread
});
}
else
{
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
BthSocket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
else
BthSocket = device.CreateRfcommSocketToServiceRecord(uuid);
if (BthSocket != null)
{
//Task.Run ((Func<Task>)loop); /*) => {
await BthSocket.ConnectAsync();
if (BthSocket.IsConnected)
{
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Connected!");
// Code to run on the main thread
//pages.bluetoothBarcodeScan.connectedScanner();
});
System.Diagnostics.Debug.WriteLine("Connected!");
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Writing!");
// Code to run on the main thread
//
});
while (_ct.IsCancellationRequested == false)
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
var bytes = Encoding.ASCII.GetBytes("{test}-");
BthSocket.OutputStream.Write(bytes, 0, bytes.Length);
Thread.Sleep(100);
}
System.Diagnostics.Debug.WriteLine("Exit the inner loop");
}
}
else
System.Diagnostics.Debug.WriteLine("BthSocket = null");
}
}
catch(Exception ex)
{
service.toast.toastSuccess(ex.Message);
}
finally
{
if (BthSocket != null)
BthSocket.Close();
device = null;
adapter = null;
}
}
System.Diagnostics.Debug.WriteLine("Exit the external loop");
}
public void Cancel()
{
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastError("Disconnected");
// Code to run on the main thread
});
}
}
public async Task<string> GetData()
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
return "1";
}
public ObservableCollection<string> PairedDevices()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
ObservableCollection<string> devices = new ObservableCollection<string>();
foreach (var bd in adapter.BondedDevices)
devices.Add(bd.Name);
return devices;
}
#endregion
}
The async function always starts new when it comes to this line.
How should I get the variable?
You can change your constructor method like:
public Bth(string txt)
{}
And then pass the mainpage.test like:
public static Bluetooth.IBth bth = new Bluetooth.Bth(txt);
I am trying to get my EasyLogger C# Project to work, but I can't debug this code because it is a Class Library. I use this logger in a Windows Console Application which is installed with squirrel as a Windows Service, so I can't see whats inside the variables....
What do I wrong?
This is in a Windows Console Application:
public void Start()
{
//Define EasyLogger
EasyLogger.Logger.Loggerpath = #"C:\Development\ServerSF";
EasyLogger.Logger.Logname = "Testlog";
Thread.Sleep(1000);
//Start EasyLogger
bool test = EasyLogger.Logger.Log;
EasyLogger.Logger.StartLog();
if (test == true)
{
//Start service
_timer.Start();
ExThred(configManager.ServerName);
}
else
{
//ERROR log isnt started
}
}
This is my EasyLogger Project:
using System;
using System.IO;
using System.Text;
namespace EasyLogger
{
public static class Logger
{
#region GET SET
private static string loggerpath;
private static string logname;
private static string message;
private static bool log;
public static string Loggerpath
{
get => loggerpath;
set => loggerpath = value;
}
public static string Logname
{
get => logname;
set => logname = value;
}
public static string Message
{
get => message;
set => message = value;
}
public static bool Log
{
get => log;
set => log = value;
}
#endregion
#region Logger
private static readonly string loggingpath = loggerpath + #"\logs\"+ logname + "-" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";
public static void StartLog()
{
if(loggerpath == null)
{
Message = "Program path is empty!";
log = false;
}
else
{
try
{
using (FileStream fs = File.Create(loggingpath))
{
byte[] info = new UTF8Encoding(true).GetBytes(DateTime.Now.ToString() + " - Logger v0.1 Started...");
fs.Write(info, 0, info.Length);
}
log = true;
}
catch
{
Message = "Can't create logfile!";
log = false;
}
}
}
public static void WriteLog(string msg)
{
if (Logname != null)
{
if (log == true)
{
string[] lines = new string[] { DateTime.Now.ToString() + " - " + msg };
File.AppendAllLines(loggingpath, lines);
}
else
{
try { Message = "Logger isn't started yet!"; }
catch { Message = "Logger Error!"; }
}
}
else { Message = "Please define first a Logname!"; }
}
public static void StopLog()
{
log = false;
}
#endregion
}
}
Your problem is not the logger. Your problem is how to debug a Windows Service.
With Visual Studio, you can do it this way:
Compile your Windows service with Debug informaton.
Install the Service and run it.
Start Visual Studio.
Select "Debug" --> "Attach Process"
Click "Show processes from all users"
Search for your service and click "Attach".
Select "Common Language Runtime"
I am trying to insert data into database by using windows from application . I hosted it into console application . I am using .net remoting to invoke the method . My host is running without any problem and i also can run the windows form application without any problem . But problem is when i clicked the submit button to insert data i got error.I do not know why i am getting this error .
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Additional information: Object reference not set to an instance of an object. occurred
Here is the Interface .
namespace IHelloRemotingService
{
public interface IHelloRemotingService
{
void Insert(string Name, string Address, string Email, string Mobile)
}
}
Here is the Implementation of the interface ..
public class HelloRemotingService : MarshalByRefObject , IHelloRemotingService.IHelloRemotingService
{
public void Insert(string Name, string Address, string Email, string Mobile)
{
string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("AddNewStudent", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#EmailID", Email);
cmd.Parameters.AddWithValue("#Mobile", Mobile);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Code for Hosting service ....
namespace RemotingServiceHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" .NET Remoting Test Server");
Console.WriteLine(" *************************");
Console.WriteLine();
try
{
StartServer();
Console.WriteLine("Server started");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine("Server.Main exception: " + ex);
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
StopServer();
}
static void StartServer()
{
RegisterBinaryTCPServerChannel(500);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService.HelloRemotingService),
"Insert.rem",
WellKnownObjectMode.Singleton);
}
static void StopServer()
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch (Exception ex)
{
Console.WriteLine("Server.StopServer exception: " + ex);
}
}
}
static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
{
IServerChannelSinkProvider firstServerProvider;
IClientChannelSinkProvider firstClientProvider;
var channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = port;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Code for windows form application ..
namespace HelloRemotingServiceClient
{
public partial class InsertStudentData : Form
{
public InsertStudentData()
{
InitializeComponent();
RegisterBinaryTcpClientChannel();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
remService.Insert(textName.Text, textAddress.Text, textEmail.Text, textBox1.Text);
label5.Text = "Recored Inserted Successfully";
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RegisterBinaryTcpClientChannel(string name = "tcp client")
{
IClientChannelSinkProvider firstClientProvider;
IServerChannelSinkProvider firstServerProvider;
var channelProperties = new Hashtable();
channelProperties["name"] = name;
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = 0; // auto
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null);
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Design of the form ..
Here is the screen shot of errors messages .
The text boxes are able to catch the values but why its throwing this error ?
Here is a working project. You did not configure the formatter.
SharedLib Project:
namespace IHelloRemotingService
{
public interface IHelloRemotingService
{
void Insert(string Name, string Address, string Email, string Mobile);
}
}
Server Console Project:
namespace Server
{
public class HelloRemotingService : MarshalByRefObject, IHelloRemotingService.IHelloRemotingService
{
public HelloRemotingService()
{
}
public void Insert(string Name, string Address, string Email, string Mobile)
{
Console.WriteLine("HelloRemotingService.Insert called");
}
public override object InitializeLifetimeService()
{
return null; // manage lifetime by myself
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" .NET Remoting Test Server");
Console.WriteLine(" *************************");
Console.WriteLine();
try
{
StartServer();
Console.WriteLine("Server started");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine("Server.Main exception: " + ex);
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
StopServer();
}
static void StartServer()
{
RegisterBinaryTCPServerChannel(500);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService),
"Insert.rem",
WellKnownObjectMode.Singleton);
}
static void StopServer()
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch(Exception ex)
{
Console.WriteLine("Server.StopServer exception: " + ex);
}
}
}
static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
{
IServerChannelSinkProvider firstServerProvider;
IClientChannelSinkProvider firstClientProvider;
var channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = port;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Client WinForms Project:
namespace Client
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
RegisterBinaryTcpClientChannel();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (MainForm form = new MainForm())
{
Application.Run(form);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch (Exception ex)
{
Debug.WriteLine("Client.Dispose exception: " + ex);
}
}
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
private void _btnAccessServer_Click(object sender, EventArgs e)
{
try
{
var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
remService.Insert("MyName", "MyAddress", "MyEmail", "MyMobile");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RegisterBinaryTcpClientChannel(string name = "tcp client")
{
IClientChannelSinkProvider firstClientProvider;
IServerChannelSinkProvider firstServerProvider;
var channelProperties = new Hashtable();
channelProperties["name"] = name;
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = 0; // auto
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null);
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
I have an Android application created in C# using Xamarin.
This is essentially a web browser with some additional functionalities and now I would like add the option to set up a proxy to use. In the application I use WebView for connection to websites.
I tried to implement solution from this topic (How can I set ProxySettings and ProxyProperties on Android Wi-Fi connection using Java?), but there is no linkProperties in WifiConfiguration. This is how it looks like:
private static Java.Lang.Object getField(Java.Lang.Object obj, String name)
{
Field f = obj.Class.GetField(name);
Java.Lang.Object o = f.Get(obj);
return o;
}
public void SetHttpProxy(string proxyServerAddress, int proxyServerInt)
{
try
{
var wifiManager = context.GetSystemService(Context.WifiService) as WifiManager;
if (!wifiManager.IsWifiEnabled)
return;
var configurationList = wifiManager.ConfiguredNetworks;
var cur = wifiManager.ConnectionInfo.NetworkId;
var configuration = configurationList.FirstOrDefault(conf => conf.NetworkId == cur);
getField(configuration, "linkProperties");
}
catch (Exception e)
{
throw;
}
}
Here is solution that works for 4., 5., 6.* and 7.* Android OS versions for sure:
public static void SetProxy(WebView webView, string host, int port, bool bypass)
{
Context appContext = webView.Context.ApplicationContext;
JavaSystem.SetProperty("http.proxyHost", host);
JavaSystem.SetProperty("http.proxyPort", port + "");
JavaSystem.SetProperty("https.proxyHost", host);
JavaSystem.SetProperty("https.proxyPort", port + "");
if (bypass)
JavaSystem.SetProperty("http.nonProxyHosts", BYPASS_PATTERN);
try
{
Class applictionCls = Class.ForName(APPLICATION_CLASS_NAME);
Field loadedApkField = applictionCls.GetField("mLoadedApk");
loadedApkField.Accessible = true;
Object loadedApk = loadedApkField.Get(appContext);
Class loadedApkCls = Class.ForName("android.app.LoadedApk");
Field receiversField = loadedApkCls.GetDeclaredField("mReceivers");
receiversField.Accessible = true;
ArrayMap receivers = (ArrayMap) receiversField.Get(loadedApk);
foreach (Object receiverMap in receivers.Values())
{
foreach (Object rec in Extensions.JavaCast<ArrayMap>(receiverMap).KeySet())
{
Class clazz = rec.Class;
if (clazz.Name.Contains("ProxyChangeListener"))
{
Method onReceiveMethod = clazz.GetDeclaredMethod("onReceive", Class.FromType(typeof(Context)), Class.FromType(typeof(Intent)));
Intent intent = new Intent(Android.Net.Proxy.ProxyChangeAction);
onReceiveMethod.Invoke(rec, appContext, intent);
}
}
}
}
catch (Exception)
{
}
}
I found plenty of partial answers, but nothing really sufficient.
The case:
App is a working command line app, with no user interaction, except for the ability to receive an key press on enter to stop, this is already written in a way that disables even that when not run as Environment.UserInteractive == true.
I'm using Visual Studio 2010.
The problem is I need to convert this app to a windows service. Is it "just" making a new class file as a service, and have it call my start and stop methods on the existing application?
How about the installer (VS' default msi installer), can the existing installer project be "upgraded" to handle the Service installation as well?
I messed with this before, and ended up with an installer that kept refusing to install, as it kept detecting the service as already being installed, stopping the install process by then promptly rolling back everything. The service it detected were the one it had just installed.
To run a console app as either a Windows Service or a Console application, write a single console application and use command line arguments to determine if you should run directly or start up the service. Include an installer/uninstaller to install as a windows service with the right command line arguments.
Here's a base class we use that provides this functionality.
using System;
using System.Collections;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Console40
{
public abstract class AbstractService : ServiceBase
{
public static AbstractService Current { get; private set; }
protected virtual string HelpTextPattern
{
get
{
#region Help Text
return
#"
USAGE
{0} [command]
WHERE [command] is one of
/console - run as a console application, for debugging
/service - run as a windows service
/install - install as a windows service
/uninstall - uninstall windows service
";
#endregion
}
}
public abstract string DisplayName { get; }
public ServiceExecutionMode ServiceExecutionMode { get; private set; }
protected abstract Guid UninstallGuid { get; }
protected virtual string UninstallRegKeyPath
{
get
{
return #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
}
}
protected AbstractService(string serviceName)
{
ServiceName = serviceName;
if (Current != null)
{
throw new InvalidOperationException(String.Format(
"Service {0} is instantiating but service {1} is already instantiated as current. References to AbstractService.Current will only point to the first service.",
GetType().FullName,
Current.GetType().FullName));
}
Current = this;
}
public void Run(string[] args)
{
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
if (args.Length == 0 && Debugger.IsAttached)
{
args = new[] { "/console" };
}
if (args.Length == 0)
{
Console.WriteLine(HelpTextPattern, Path.GetFileName(GetType().Assembly.CodeBase));
}
else
{
switch (args[0].ToLower())
{
case "/service":
ServiceExecutionMode = ServiceExecutionMode.Service;
Run(new[] { this });
break;
case "/console":
ServiceExecutionMode = ServiceExecutionMode.Console;
Console.WriteLine("Starting Service...");
OnStart(new string[0]);
OnStartCommandLine();
OnStop();
break;
case "/install":
ServiceExecutionMode = ServiceExecutionMode.Install;
InstallService();
break;
case "/uninstall":
ServiceExecutionMode = ServiceExecutionMode.Uninstall;
UninstallService();
break;
case "/uninstallprompt":
ServiceExecutionMode = ServiceExecutionMode.Uninstall;
if (ConfirmUninstall())
{
UninstallService();
InformUninstalled();
}
break;
default:
if (!OnCustomCommandLine(args))
{
Console.WriteLine(HelpTextPattern, Path.GetFileName(GetType().Assembly.CodeBase));
}
break;
}
}
}
protected override void OnStart(string[] args)
{
OnStartImpl(args);
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
}
protected virtual void OnStartCommandLine()
{
Console.WriteLine("Service is running... Hit ENTER to break.");
Console.ReadLine();
}
protected abstract void OnStartImpl(string[] args);
void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// do something useful here, log it..
}
protected override void OnShutdown()
{
Stop();
}
protected override void OnStop()
{
OnStopImpl();
}
protected abstract void OnStopImpl();
protected virtual bool OnCustomCommandLine(string[] args)
{
// for extension
return false;
}
private void InstallService()
{
GetInstaller(".InstallLog").Install(new Hashtable());
InstallServiceCommandLine();
CreateUninstaller();
}
private void InstallServiceCommandLine()
{
string keyParent = #"SYSTEM\CurrentControlSet\Services\" + ServiceName;
const string VALUE_NAME = "ImagePath";
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyParent, true))
{
if (key == null)
{
throw new InvalidOperationException("Service not found in registry.");
}
var origPath = key.GetValue(VALUE_NAME) as string;
if (origPath == null)
{
throw new Exception("HKLM\\" + keyParent + "\\" + VALUE_NAME + " does not exist but was expected.");
}
key.SetValue(VALUE_NAME, origPath.Replace("\"\"", "\"") + " /service");
}
}
catch (Exception ex)
{
throw new Exception(
"Error updating service command line after installation. Unable to write to HKLM\\" + keyParent, ex);
}
}
private void CreateUninstaller()
{
using (RegistryKey parent = Registry.LocalMachine.OpenSubKey(UninstallRegKeyPath, true))
{
if (parent == null)
{
throw new Exception(String.Format("Uninstall registry key '{0}' not found.", UninstallRegKeyPath));
}
try
{
RegistryKey key = null;
try
{
string guidText = UninstallGuid.ToString("B");
key = parent.OpenSubKey(guidText, true) ??
parent.CreateSubKey(guidText);
if (key == null)
{
throw new Exception(String.Format("Unable to create uninstaller '{0}\\{1}'", UninstallRegKeyPath, guidText));
}
Assembly asm = GetType().Assembly;
Version v = asm.GetName().Version;
string exe = "\"" + asm.CodeBase.Substring(8).Replace("/", "\\\\") + "\"";
key.SetValue("DisplayName", DisplayName);
key.SetValue("ApplicationVersion", v.ToString());
key.SetValue("Publisher", "B-Line Medical");
key.SetValue("DisplayIcon", exe);
key.SetValue("DisplayVersion", v.ToString(2));
key.SetValue("URLInfoAbout", "http://www.blinemedical.com");
key.SetValue("Contact", "support#blinemedical.com");
key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
key.SetValue("UninstallString", exe + " /uninstallprompt");
}
finally
{
if (key != null)
{
key.Close();
}
}
}
catch (Exception ex)
{
throw new Exception(
"An error occurred writing uninstall information to the registry. The service is fully installed but can only be uninstalled manually through the command line.",
ex);
}
}
}
private bool ConfirmUninstall()
{
string title = "Uninstall " + DisplayName;
string text = "Are you sure you want to remove " + DisplayName + " from your computer?";
return DialogResult.Yes ==
MessageBox.Show(text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
}
private void InformUninstalled()
{
string title = "Uninstall " + DisplayName;
string text = DisplayName + " has been uninstalled.";
MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void UninstallService()
{
GetInstaller(".UninstallLog").Uninstall(null);
RemoveUninstaller();
}
private TransactedInstaller GetInstaller(string logExtension)
{
var ti = new TransactedInstaller();
ti.Installers.Add(new ServiceProcessInstaller
{
Account = ServiceAccount.LocalSystem
});
ti.Installers.Add(new ServiceInstaller
{
DisplayName = DisplayName,
ServiceName = ServiceName,
StartType = ServiceStartMode.Automatic
});
string basePath = Assembly.GetEntryAssembly().Location;
String path = String.Format("/assemblypath=\"{0}\"", basePath);
ti.Context = new InstallContext(Path.ChangeExtension(basePath, logExtension), new[] { path });
return ti;
}
private void RemoveUninstaller()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(UninstallRegKeyPath, true))
{
if (key == null)
{
return;
}
try
{
string guidText = UninstallGuid.ToString("B");
RegistryKey child = key.OpenSubKey(guidText);
if (child != null)
{
child.Close();
key.DeleteSubKey(guidText);
}
}
catch (Exception ex)
{
throw new Exception(
"An error occurred removing uninstall information from the registry. The service was uninstalled will still show up in the add/remove program list. To remove it manually delete the entry HKLM\\" +
UninstallRegKeyPath + "\\" + UninstallGuid, ex);
}
}
}
}
public enum ServiceExecutionMode
{
Unknown,
Service,
Console,
Install,
Uninstall,
Custom
}
}
Best thing for you to do is to start a new Project as a windows service.
In this new project you will find Service1.cs and this is the file that will be run from start. the following code will be int the file:
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
It isnt that hard to figure out what to do from here. Simply add your classes to the project and make sure that you copy your main code in the the OnStart() function. Of course you might have to slightly edit the code to make sure it has no readlines in it.
Now you must create and installer. How you can do this can be found here:
http://msdn.microsoft.com/en-us/library/zt39148a%28v=vs.100%29.aspx
I hope this helped :D
Kind Regards
RoXaS
Keep C# application running
public partial class DemoService : ServiceBase
{
static void Main(string[] args)
{
DemoService service = new DemoService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
Check the link above. I provide some code as well as a link describing using a console for double-duty as Console and Service. I will use a console project and check for UserInteractive before running as a service. This way you can debug as if it's a console, but install it as a service on a production server.
With regards to installing, I don't have experience with installing from .msi, but we use a batch script to install the service (using sc.exe) and then its just a matter of replacing files if you update the code.