c# twincat passing argument to class constructor - c#

I wonder what is the best way.
If I need to pass a class to a class constructor why should I use a variable inside my class.
Example:
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsServer AdsServer;
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
AdsServer = _adsServer;
_cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}
Why can't I do:
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
_cncClient = _adsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}
I would like to use _adsServer in a lot of class not connected, how can I do that properly?
Thanks for help.

Ok, here is like I do now.
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsServer AdsServer;
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
AdsServer = _adsServer;
_cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
Classtocall newClass = ClasstoCall(_cncClient);//Passing the argument directly
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}

Related

Method GetServer() returning null for unknown reason

I have a project and one of the main methods is returning null when it is pretty clear to see I have assigned a value to it.
Program.cs:
using System;
namespace Sahara
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Title = "Loading Sahara...";
Console.CursorVisible = false;
Sahara.Initialize();
while (true)
{
Console.ReadKey();
}
}
}
}
Sahara.cs:
namespace Sahara
{
class Sahara
{
private static SaharaServer server;
public static void Initialize()
{
server = new SaharaServer();
}
public static SaharaServer GetServer()
{
return server;
}
}
}
SaharaServer:
using Sahara.Core.Config;
using Sahara.Core.Logging;
using Sahara.Core.Server;
using System;
using System.Diagnostics;
namespace Sahara
{
class SaharaServer
{
private readonly ServerStatusUpdater serverStatusUpdater;
private readonly LogManager logManager;
private readonly ServerInformation serverInformation;
private readonly DateTime startedTime;
private readonly ConfigManager configManager;
public SaharaServer()
{
logManager = new LogManager();
serverInformation = new ServerInformation();
foreach (string consoleOutputString in serverInformation.ConsoleLogo)
{
Console.WriteLine(consoleOutputString);
}
logManager.Log("Loading " + serverInformation.ServerName + "...", LogType.Information);
Stopwatch stopwatch = Stopwatch.StartNew();
configManager = new ConfigManager("Extra/Other/config.ini");
startedTime = DateTime.Now;
serverStatusUpdater = new ServerStatusUpdater();
stopwatch.Stop();
logManager.Log("Finished Loading! [" + stopwatch.ElapsedMilliseconds + "ms]", LogType.Warning);
Console.ForegroundColor = ConsoleColor.Black;
}
public LogManager GetLogManager()
{
return logManager;
}
public ServerInformation GetServerInformation()
{
return serverInformation;
}
public DateTime StartedTime
{
get { return startedTime; }
}
public ConfigManager GetConfigManager()
{
return configManager;
}
public void Dispose()
{
try
{
serverStatusUpdater.Dispose();
}
catch (Exception exception)
{
if (logManager != null)
{
logManager.Log("Error in disposing SaharaServer: " + exception.Message, LogType.Error);
logManager.Log(exception.StackTrace, LogType.Error);
}
}
finally
{
Environment.Exit(0);
}
}
}
}
But why is GetServer() in Sahara.cs returning null!!?!?!?!?
You call the ConfigManager constructor from within the SaharaServer constructor, so the constructor has not yet completed to set the server field and thus GetServer will return null.

Location service always says it's enabled, even when it's not

I am using the latest Unity3D version. When using LocationService.isEnabledByUser, I should be told whether the GPS is enabled or disabled. However it is always returns true. I am using an Android 4.2 smartphone.
What could be the cause of this issue, and can I somehow resolve it?
There is a problem with LocationService.isEnabledByUser on some devices and I wouldn't trust using that in my app. It is not reliable. Just build a java plugin for this. I will share the one I made long time ago.
Java:
Create a class called LocationService. Let's assume that package name is com.progammer.plugin and the full package name is com.progammer.plugin.LocationService.
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class LocationService {
private static Context mContext;
// Called From C# to get the Context Instance
public static void receiveContextInstance(Context tempContext) {
mContext = tempContext;
}
// http://stackoverflow.com/a/10311891/3785314
public static boolean isLocationServiceEnabled() {
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e("CONTEXT", "Error: " + ex.getMessage());
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e("CONTEXT", "Error: " + ex.getMessage());
}
return (gps_enabled && network_enabled);
}
public static boolean isGPSLocationServiceEnabled() {
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e("CONTEXT", "Error: " + ex.getMessage());
}
return gps_enabled;
}
public static boolean isNetworkLocationServiceEnabled() {
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = false;
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e("CONTEXT", "Error: " + ex.getMessage());
}
return network_enabled;
}
// http://stackoverflow.com/a/32797750/3785314
#SuppressWarnings({ "deprecation" })
public static boolean isAirplaneModeOn() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
/* API 17 and above */
return Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
} else {
/* below */
return Settings.System.getInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
}
// http://stackoverflow.com/a/7713511/3785314
public static void notifyUserToEnableLocationService() {
CharSequence searchStr = "Please enable Location Service";
Toast.makeText(mContext, searchStr, Toast.LENGTH_LONG).show();
Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
gpsOptionsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(gpsOptionsIntent);
}
}
C#:
Create a script called LocationServiceManager:
using UnityEngine;
using System.Collections;
public class LocationServiceManager
{
AndroidJavaClass unityClass;
AndroidJavaObject unityActivity;
AndroidJavaObject unityContext;
AndroidJavaClass customClass;
public LocationServiceManager()
{
//Replace with your full package name
sendContextReference("com.progammer.plugin.LocationService");
}
public void sendContextReference(string packageName)
{
unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");
customClass = new AndroidJavaClass(packageName);
customClass.CallStatic("receiveContextInstance", unityContext);
}
///////////////////////////////////MAIN FUNCTIONS/////////////////////////////////////
public bool isLocationServiceEnabled()
{
return customClass.CallStatic<bool>("isLocationServiceEnabled");
}
public bool isGPSLocationServiceEnabled()
{
return customClass.CallStatic<bool>("isGPSLocationServiceEnabled");
}
public bool isNetworkLocationServiceEnabled()
{
return customClass.CallStatic<bool>("isNetworkLocationServiceEnabled");
}
public bool isAirplaneModeOn()
{
return customClass.CallStatic<bool>("isAirplaneModeOn");
}
public void notifyUserToEnableLocationService()
{
customClass.CallStatic("notifyUserToEnableLocationService");
}
}
To use the plugin in C#:
Let's make a simple Test Script to test the new plugin. This will only run on Android devices, so don't expect it to work in the Editor.
public class TestScript : MonoBehaviour
{
public Text text;
LocationServiceManager lsm;
void Start()
{
lsm = new LocationServiceManager();
text.text = "Air Plane Mode: " + lsm.isAirplaneModeOn();
text.text += "\r\nLocation Service Enabled: " + lsm.isLocationServiceEnabled();
text.text += "\r\nGPS Location Service Enabled: " + lsm.isGPSLocationServiceEnabled();
text.text += "\r\nNetwork Location Service Enabled: " + lsm.isNetworkLocationServiceEnabled();
}
}
You can even notify the player to enable Location Service by opening the Location Settings with lsm.notifyUserToEnableLocationService();.

Calling a Class or Method in C# using Mono

I'm having some problems calling a class or method in C# using Mono, can anyone give some help on what I'm doing wrong?
I want this piece of code:
public static void Execute(ScriptHost host)
{
try
{
TesteGUI teste = new TesteGUI(); //?
TesteGUI(); // ?
}
catch(Exception e)
{
}
finally
{
}
}
To call this piece of code:
public TesteGUI(Gtk.Window parentWindow) : base(Gtk.WindowType.Toplevel)
{
base.Modal = false;
base.TransientFor = parentWindow;
base.Decorated = false;
base.WindowPosition = WindowPosition.CenterAlways;
this.MyBuild();
base.KeyReleaseEvent += delegate(object o, KeyReleaseEventArgs args)
{
if (args.Event.Key == Gdk.Key.Escape)
{
this.Destroy();
}
};
}
What is my doing wrong and how can I make it work?
Thank you
You should do it like this:
public static void Execute(ScriptHost host)
{
try
{
TesteGUI teste = new TesteGUI(parentWindow); //where parentWindow is defined somewhere earlier and is of type Gtk.Window
}
catch(Exception e)
{
}
finally
{
}
}

Transparent code execution before and after Thread/Task/Action/

The point of all this is to run a separate Thread ( can be something similar: Task, Action ) and to log the "start" and the "end", preferably minimizing code impact (changes) and logging being transparent to the code, just using a different class.
Recently I decided to inherit from class System.Threading.Thread as a way to implement logging for things like "Thread x started." and "Thread x ended." to a file, for debugging.
Since the class is sealed I used composition to add the Thread as a member and call respective function, accessors and all necessary.
I had a simplistic idea of how to do it so I thought something like
namespace MyNamespace
{
class Thread
{
private System.Threading.Thread thread;
//wrap constructor properties methods...
//...
public void Start()
{
log(thread.name + " start.");
thread.Start();
log(thread.name + " end.");
}
//...
}
}
Now after all this trouble of wrapping existing functionality (and using the new namespace instead of System.Threading)... this turned out to be bad since this call if I'm not mistaking is from the calling Thread and second the "end" does not log. The logging is mainly for debugging and having a non-volatile state of what happened.
EDIT:
Here's a simplified code using Ahmed's answer, which is good, and still ongoing issue is that if the SimulatedThread throws an exception the "Ending..." doesn't log for either "MainThread" or "CustomThread".
If the CustomThread abnormally terminates, "Ending..." for "MainThread" and "CustomThread" should be recorded. ( The exception handling is not relevant ). "MainThread" should be bulletproof from "CustomThread".
Full implementation
using System;
using System.Security;
using System.Threading;
namespace CS_Tests_Console
{
class Program
{
static void Main(string[] args)
{
Logger.Log("Starting...");
try
{
Thread.CurrentThread.Name = "MainThread";
CustomThread thread = new CustomThread(SimulateThread)
{
Name = "CustomThread",
};
thread.Start();
thread.Join();
}
catch (Exception ex)
{
Logger.Log("Cought exception:" + ex.ToString());
}
Logger.Log("Ending...");
}
private static void SimulateThread()
{
Logger.Log("Running...");
Thread.Sleep(2000);
throw new Exception("Test Exception");
}
}
public static class Logger
{
public static void Log(String message)
{
if (Thread.CurrentThread.Name == null)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Thread.CurrentThread.Name is NULL -> " + message);
}
else
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + Thread.CurrentThread.Name + " -> " + message);
}
}
}
public class CustomThread
{
public Thread threadInstance { get; private set; }
public CustomThread(ThreadStart threadStart)
{
threadInstance = new Thread(() =>
{
Logger.Log("Starting...");
threadStart();
Logger.Log("Ending...");
});
}
public string Name { get { return threadInstance.Name; } set { threadInstance.Name = value; } }
[SecuritySafeCritical]
public void Join()
{
threadInstance.Join();
}
public void Start()
{
threadInstance.Start();
}
}
}
Encapsulate logging in the ThreadStart delegate:
public class Logger{
public void Log(String message){
Console.WriteLine(message);
}
}
public class CustomThread {
public Thread ThreadInst { get; private set; }
public Logger logger = new Logger();
public CustomThread(ThreadStart threadStart) {
ThreadInst = new Thread(() =>
{
logger.Log(Thread.CurrentThread.Name + " Starting...");
threadStart();
logger.Log(Thread.CurrentThread.Name + " Ending...");
});
}
public void Start() { ThreadInst.Start(); }
}
class Program
{
static void Main(string[] args)
{
new CustomThread(() => Thread.Sleep(2000)).Start();
}
}
Edit: Added catching and logging exceptions:
public CustomThread(ThreadStart threadStart) {
ThreadInst = new Thread(() =>
{
logger.Log(Thread.CurrentThread.Name + " Starting...");
try {
threadStart();
} catch (Exception ex) {
logger.Log("Error in thread" + Thread.CurrentThread.Name + " " + ex.Message);
}
logger.Log(Thread.CurrentThread.Name + " Ending...");
});
}

Multiple asynchronous calls on webservice method in application fails with exception

i'm trying to create an application which connects to internet and consume web services for every of it's operation.As far as i'm concerned i'll like to useasync method which i'm using already to get a collection of Contacts.I've realized that when i'm doing the same for groups (meaning getting groups async) i'm having errors in the calls , but when using normal call there ins't.So i did some research online and find that a lot of people has the same problem.
Some of them are asked to use WCF (for which i don't know jack).I'll like to know if there is another way to overcome this. if not can somebody point me to reliable resource online and help me get through it? thanks for reading and helping
here is my code:
public partial class main : Window
{
//...
private static vmcSession session;
private MyService service = new MyService();
private contactInfo[] loadedcontact;
//....
public main()
{
InitializeComponent();
//service.addContactCompleted +=new addContactCompletedEventHandler(addContactCompleted);
service.getContactsCompleted += new getContactsCompletedEventHandler(getContactsCompleted);
service.getGroupsCompleted += new getGroupsCompletedEventHandler(getGroupsCompleted);
fillContents();
}
private void getGroupsCompleted(object sender, getGroupsCompletedEventArgs e)
{
try
{
groupListBox.ItemsSource = e.Result;
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
private void getContactsCompleted(object sender, getContactsCompletedEventArgs e)
{
try
{
loadedcontact = e.Result;
contactListBox.ItemsSource = loadedcontact;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void addContactCompleted(object sender, addContactCompletedEventArgs e)
{
throw new NotImplementedException();
}
public void fillContents()
{
displayUserInformation();
loadContacts();
service.getGroupsAsync(session.key, null);
//groupListBox.ItemsSource = service.getGroups(session.key, null);
cmbSenderIds.ItemsSource = service.getSenderIds(session.key, null);
if (cmbSenderIds.Items.Count > 0)
{
cmbSenderIds.SelectedIndex = 0;
}
loadGrid();
}
public void loadContacts()
{
service.getContactsAsync(session.key, null);
}
public void displayUserInformation()
{
lblName.Content = session.user.firstName;
lblEmail.Content = session.user.email;
lblCreditValue.Content = Decimal.Ceiling(session.user.balance).ToString();
}
public void loadGrid()
{
try
{
hitoryGrid.ItemsSource = service.viewMessages(session.key, null).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
solve it.there are 2 methods with async calls, one with additional parameter Unique ID.each of the call needed ID, so i pass new GUID to it and that's it.thanks for trying helping me

Categories

Resources