C# Read Windows Mobile Broadband connection properties - c#

First up, here's the background:
We have a Windows Forms application (written in C#, .NET Framework 3.5) currently running on full Windows 7 tablets, which have a 3G module built in that is used for data connectivity. The data connection is configured as a normal mobile broadband connection in Windows (so Windows manages the connectivity itself), and the connection shows up in Control Panel > Network and Internet > Network Connections and it works fine - the application is able to communicate over the internet with our web service. We will be moving onto a different device (likely a full Windows 8-based tablet) at some point in the future.
Now, what I need to do is read the connection status of this Mobile Broadband connection; i.e. get the signal strength, and the carrier name (e.g. Vodafone UK). I've found a way to do this using the Mobile Broadband API part of the Windows 7 SDK (see here and here), however this appears to be OS specific as it doesn't work on Windows 8 - or at least not with the device I have here.
Is there a generic way to read the mobile broadband connection properties using the .NET framework?
Alternatively, does anyone know of a Windows 8 SDK which contains a Mobile Broadband API like the Windows 7 one I'm currently using?
Thanks in advance.
Update - I've got this working on a range of different Win 7 / Win 8 devices now. Even the Lenovo device is working OK. I'll post up example code for the main bits (Reading connection status, configuring the connection, checking the SIM status) as answers; the code is a little too long to go into the question, annoyingly.

Configuring a connection programmatically (you will need the APN details):
try
{
MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
if (mbnInfMgrInterface != null)
{
IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
if (mobileInterfaces != null && mobileInterfaces.Length > 0)
{
// Just use the first interface
IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();
if (subInfo != null)
{
SIMNumber = subInfo.SimIccID;
// Get the connection profile
MbnConnectionProfileManager mbnConnProfileMgr = new MbnConnectionProfileManager();
IMbnConnectionProfileManager mbnConnProfileMgrInterface = mbnConnProfileMgr as IMbnConnectionProfileManager;
if (mbnConnProfileMgrInterface != null)
{
bool connProfileFound = false;
string profileName = String.Empty;
try
{
IMbnConnectionProfile[] mbnConnProfileInterfaces = mbnConnProfileMgrInterface.GetConnectionProfiles(mobileInterfaces[0]) as IMbnConnectionProfile[];
foreach (IMbnConnectionProfile profile in mbnConnProfileInterfaces)
{
string xmlData = profile.GetProfileXmlData();
if (xmlData.Contains("<SimIccID>" + SIMNumber + "</SimIccID>"))
{
connProfileFound = true;
bool updateRequired = false;
// Check if the profile is set to auto connect
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlData);
profileName = xdoc["MBNProfile"]["Name"].InnerText;
if (xdoc["MBNProfile"]["ConnectionMode"].InnerText != "auto")
{
xdoc["MBNProfile"]["ConnectionMode"].InnerText = "auto";
updateRequired = true;
}
// Check the APN settings
if (xdoc["MBNProfile"]["Context"] == null)
{
XmlElement context = (XmlElement)xdoc["MBNProfile"].AppendChild(xdoc.CreateElement("Context", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("AccessString", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("Compression", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("AuthProtocol", xdoc["MBNProfile"].NamespaceURI));
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["AccessString"].InnerText != APNAccessString)
{
xdoc["MBNProfile"]["Context"]["AccessString"].InnerText = APNAccessString;
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["Compression"].InnerText != APNCompression)
{
xdoc["MBNProfile"]["Context"]["Compression"].InnerText = APNCompression;
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText != APNAuthProtocol)
{
xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText = APNAuthProtocol;
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] == null && !String.IsNullOrEmpty(APNUsername))
{
XmlElement userLogonCred = (XmlElement)xdoc["MBNProfile"]["Context"].InsertAfter(xdoc.CreateElement("UserLogonCred", xdoc["MBNProfile"].NamespaceURI), xdoc["MBNProfile"]["Context"]["AccessString"]);
userLogonCred.AppendChild(xdoc.CreateElement("UserName", xdoc["MBNProfile"].NamespaceURI));
userLogonCred.AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText != APNUsername)
{
xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText = APNUsername;
updateRequired = true;
}
if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"] == null && !String.IsNullOrEmpty(APNUsername))
{
xdoc["MBNProfile"]["Context"]["UserLogonCred"].AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
}
if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText != APNPassword)
{
xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText = APNPassword;
updateRequired = true;
}
if (updateRequired)
{
// Update the connection profile
profile.UpdateProfile(xdoc.OuterXml);
}
}
}
}
catch (Exception ex)
{
if (!ex.Message.Contains("Element not found"))
{
throw ex;
}
}
if (!connProfileFound)
{
// Create the connection profile
XmlDocument xdoc = new XmlDocument();
xdoc.AppendChild(xdoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
XmlElement mbnProfile = (XmlElement)xdoc.AppendChild(xdoc.CreateElement("MBNProfile", "http://www.microsoft.com/networking/WWAN/profile/v1"));
mbnProfile.AppendChild(xdoc.CreateElement("Name", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
mbnProfile.AppendChild(xdoc.CreateElement("IsDefault", xdoc["MBNProfile"].NamespaceURI)).InnerText = "true";
mbnProfile.AppendChild(xdoc.CreateElement("ProfileCreationType", xdoc["MBNProfile"].NamespaceURI)).InnerText = "DeviceProvisioned";
mbnProfile.AppendChild(xdoc.CreateElement("SubscriberID", xdoc["MBNProfile"].NamespaceURI)).InnerText = subInfo.SubscriberID;
mbnProfile.AppendChild(xdoc.CreateElement("SimIccID", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
mbnProfile.AppendChild(xdoc.CreateElement("HomeProviderName", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
mbnProfile.AppendChild(xdoc.CreateElement("AutoConnectOnInternet", xdoc["MBNProfile"].NamespaceURI)).InnerText = "true";
mbnProfile.AppendChild(xdoc.CreateElement("ConnectionMode", xdoc["MBNProfile"].NamespaceURI)).InnerText = "auto";
XmlElement context = (XmlElement)xdoc["MBNProfile"].AppendChild(xdoc.CreateElement("Context", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("AccessString", xdoc["MBNProfile"].NamespaceURI));
XmlElement userLogonCred = (XmlElement)context.AppendChild(xdoc.CreateElement("UserLogonCred", xdoc["MBNProfile"].NamespaceURI));
userLogonCred.AppendChild(xdoc.CreateElement("UserName", xdoc["MBNProfile"].NamespaceURI));
userLogonCred.AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("Compression", xdoc["MBNProfile"].NamespaceURI));
context.AppendChild(xdoc.CreateElement("AuthProtocol", xdoc["MBNProfile"].NamespaceURI));
xdoc["MBNProfile"]["Context"]["AccessString"].InnerText = APNAccessString;
xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText = APNUsername;
xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText = APNPassword;
xdoc["MBNProfile"]["Context"]["Compression"].InnerText = APNCompression;
xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText = APNAuthProtocol;
profileName = xdoc["MBNProfile"]["Name"].InnerText;
mbnConnProfileMgrInterface.CreateConnectionProfile(xdoc.OuterXml);
}
// Register the connection events
MbnConnectionManager connMgr = new MbnConnectionManager();
IConnectionPointContainer connPointContainer = connMgr as IConnectionPointContainer;
Guid IID_IMbnConnectionEvents = typeof(IMbnConnectionEvents).GUID;
IConnectionPoint connPoint;
connPointContainer.FindConnectionPoint(ref IID_IMbnConnectionEvents, out connPoint);
ConnectionEventsSink connEventsSink = new ConnectionEventsSink();
connPoint.Advise(connEventsSink, out cookie); if (showProgress) { MessageBox.Show("After registering events"); }
// Connect
IMbnConnection connection = mobileInterfaces[0].GetConnection();
if (connection != null)
{
MBN_ACTIVATION_STATE state;
string connectionProfileName = String.Empty;
connection.GetConnectionState(out state, out connectionProfileName);
if (state != MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATED && state != MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATING)
{
if (String.IsNullOrEmpty(connectionProfileName))
{
connectionProfileName = profileName;
}
uint requestID;
connection.Connect(MBN_CONNECTION_MODE.MBN_CONNECTION_MODE_PROFILE, connectionProfileName, out requestID);
}
else
{
// Do nothing, already connected
}
}
else
{
MessageBox.Show("Connection not found.");
}
}
else
{
MessageBox.Show("mbnConnProfileMgrInterface is null.");
}
}
else
{
MessageBox.Show("No subscriber info found.");
}
}
else
{
MessageBox.Show("No mobile interfaces found.");
}
}
else
{
MessageBox.Show("mbnInfMgrInterface is null.");
}
}
catch (Exception ex)
{
if (ex.Message.Contains("SIM is not inserted."))
{
SIMNumber = "No SIM inserted.";
}
MessageBox.Show("LoginForm.DataConnection ConfigureWindowsDataConnection Error " + ex.Message);
}

Reading the connection status:
try
{
MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
if (mbnInfMgrInterface != null)
{
IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
if (mobileInterfaces != null && mobileInterfaces.Length > 0)
{
// Use the first interface, as there should only be one mobile data adapter
IMbnSignal signalDetails = mobileInterfaces[0] as IMbnSignal;
Int32.TryParse(signalDetails.GetSignalStrength().ToString(), out PhoneSignal);
PhoneSignal = Convert.ToInt32(((float)PhoneSignal / 16) * 100);
MBN_PROVIDER provider = mobileInterfaces[0].GetHomeProvider();
PhoneNetwork = provider.providerName.ToString();
if (String.IsNullOrEmpty(SIMNumber))
{
try
{
IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();
if (subInfo != null)
{
SIMNumber = subInfo.SimIccID;
}
else
{
SIMNumber = "Unable to read SIM info";
}
}
catch (Exception)
{
SIMNumber = "Unable to read SIM info";
}
}
// Check whether the connection is active
IMbnConnection connection = mobileInterfaces[0].GetConnection();
if (connection != null)
{
MBN_ACTIVATION_STATE state;
string profileName = String.Empty;
connection.GetConnectionState(out state, out profileName);
Connected = (state == MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATED);
}
else
{
MessageBox.Show("Connection not found.");
}
}
else
{
MessageBox.Show("No mobile interfaces found.");
}
}
else
{
MessageBox.Show("mbnInfMgrInterface is null.");
}
}
catch (Exception ex)
{
if (ex.Message.Contains("SIM is not inserted."))
{
SIMNumber = "No SIM inserted.";
}
else
{
MessageBox.Show("LoginForm.DataConnection GetWindowsMobileDataStatus " + ex.Message);
}
PhoneSignal = 0;
PhoneNetwork = "Unknown";
}

Mobile Broadband API is also available in Windows 8 Desktop.
If you're using Windows 8 Metro/RT/whatever name, you need these WindowsRT APIs
(Windows.Connectivity.NetworkInformation etc).

Checking the SIM is inserted and working / activated:
try
{
MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
if (mbnInfMgrInterface != null)
{
IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
if (mobileInterfaces != null && mobileInterfaces.Length > 0)
{
try
{
MBN_READY_STATE readyState = mobileInterfaces[0].GetReadyState();
switch (readyState)
{
case MBN_READY_STATE.MBN_READY_STATE_BAD_SIM:
MessageBox.Show("The SIM is invalid (PIN Unblock Key retrials have exceeded the limit).");
break;
case MBN_READY_STATE.MBN_READY_STATE_DEVICE_BLOCKED:
MessageBox.Show("The device is blocked by a PIN or password which is preventing the device from initializing and registering onto the network.");
break;
case MBN_READY_STATE.MBN_READY_STATE_DEVICE_LOCKED:
MessageBox.Show("The device is locked by a PIN or password which is preventing the device from initializing and registering onto the network.");
break;
case MBN_READY_STATE.MBN_READY_STATE_FAILURE:
MessageBox.Show("General device failure.");
break;
case MBN_READY_STATE.MBN_READY_STATE_INITIALIZED:
try
{
IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();
if (subInfo != null)
{
SIMNumber = subInfo.SimIccID;
}
else
{
SIMNumber = "Unable to read SIM info";
}
}
catch (Exception)
{
SIMNumber = "Unable to read SIM info";
}
IMbnRegistration registration = mobileInterfaces[0] as IMbnRegistration;
if (registration != null)
{
try
{
MBN_REGISTER_STATE regState = registration.GetRegisterState();
switch (regState)
{
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_DENIED:
// SIM Inactive
simInactive = true;
MessageBox.Show("The device was denied registration. The most likely cause of this error is an Inactive SIM.");
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_DEREGISTERED:
// Do nothing - this is returned before the device has tried to register
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_HOME:
// Do nothing
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_NONE:
MessageBox.Show("The device registration state is unknown. This state may be set upon failure of registration mode change requests.");
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_PARTNER:
// Do nothing
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_ROAMING:
// Do nothing
break;
case MBN_REGISTER_STATE.MBN_REGISTER_STATE_SEARCHING:
// Do nothing
break;
default:
MessageBox.Show("GetRegisterState returned an unexpected state: " + regState.ToString());
break;
}
}
catch (Exception ex)
{
MessageBox.Show("GetRegisterState Error: " + ex.Message);
}
}
break;
case MBN_READY_STATE.MBN_READY_STATE_NOT_ACTIVATED:
MessageBox.Show("The subscription is not activated.");
break;
case MBN_READY_STATE.MBN_READY_STATE_OFF:
MessageBox.Show("The mobile broadband device stack is off.");
break;
case MBN_READY_STATE.MBN_READY_STATE_SIM_NOT_INSERTED:
MessageBox.Show("The SIM is not inserted.");
break;
default:
MessageBox.Show("GetReadyState returned an unexpected state: " + readyState.ToString());
break;
}
}
catch (Exception ex)
{
MessageBox.Show("GetReadyState Error: " + ex.Message);
}
}
else
{
MessageBox.Show("No mobileInterfaces found.");
}
}
else
{
MessageBox.Show("mbnInfMgrInterface is null.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}

Respond to the connection events (events are registered in the above example):
public class ConnectionEventsSink : IMbnConnectionEvents
{
public ConnectionEventsSink() { }
public void OnConnectComplete(IMbnConnection connection, uint requestID, int status)
{
// Un-register the connect event - you might not want to do this, depends on your own requirements. Do do this you need the cookie uint from when the events were registered.
MbnConnectionManager connMgr = new MbnConnectionManager();
IConnectionPointContainer connPointContainer = connMgr as IConnectionPointContainer;
Guid IID_IMbnConnectionEvents = typeof(IMbnConnectionEvents).GUID;
IConnectionPoint connPoint;
connPointContainer.FindConnectionPoint(ref IID_IMbnConnectionEvents, out connPoint);
connPoint.Unadvise(cookie);
switch (status)
{
case 0:
MobileBroadbandTest.Connected = true;
MessageBox.Show("Connected");
break;
case -2141945334:
MessageBox.Show("There is no SIM in the device.");
break;
case -2141945328:
MessageBox.Show("A PIN is required for the operation to complete.");
break;
case -2141945335:
MessageBox.Show("The network service subscription has expired.");
break;
case -2141945337:
MessageBox.Show("The provider is not visible. This applies only to manual registration mode.");
break;
case -2141945340:
MessageBox.Show("The connection access string is not correct.");
break;
case -2141945333:
MessageBox.Show("An active voice call is in progress.");
break;
case -2141945339:
MessageBox.Show("There is already an Mobile Broadband context active. The Mobile Broadband service does not currently support multiple active contexts.");
break;
case -2141945336:
MessageBox.Show("The device radio is off.");
break;
case -2141945338:
MessageBox.Show("No active attached packet service is available.");
break;
case -2141945326:
MessageBox.Show("Generic Failure.");
break;
case -2141945320:
MessageBox.Show("Profile is invalid.");
break;
case -2141945319:
MessageBox.Show("Default profile exist.");
break;
case -2141945327:
MessageBox.Show("PIN is disabled.");
break;
case -2141945329:
MessageBox.Show("Pin is not supported.");
break;
case -2141945330:
MessageBox.Show("Providers not found.");
break;
case -2141945331:
MessageBox.Show("Device is not registered.");
break;
case -2141945332:
MessageBox.Show("Visible provider cache is invalid.");
break;
case -2141945341:
MessageBox.Show("Requested data class is not available.");
break;
case -2141945342:
MessageBox.Show("Bad SIM is inserted.");
break;
case -2141945343:
MessageBox.Show("Context is not activated.");
break;
default:
MessageBox.Show("Unexpected status: " + status.ToString());
break;
}
}
public void OnVoiceCallStateChange(IMbnConnection connection)
{
// Do nothing
}
public void OnConnectStateChange(IMbnConnection connection)
{
// Do nothing
}
public void OnDisconnectComplete(IMbnConnection connection, uint requestID, int status)
{
// Do nothing
}
}

Related

Quickfix with c# issue connecting with Initiator

I have a sever running already (acceptor) and I am trying to build something to send orders to this server by using quickfix and c# .net 4.7
I installed the quick fix library and tried to copy the sample tradeClient from the official website, but I am not seeing any actual connection made.
PS:
I am using WinForms, so I commented out the Console.Readline() and put a fixed value for testing purposes.
when it trigger run() it will run the QueryNew function, it never hit the OnLogon() function
from the console, i see the following log message:
<event> Created session>
<event> Connecting to xxx.xxx.xxx.xxx on port xxxx
<event> Connection successed
<outgoing> 8=Fix4.2|9=71|35=A|34=2|49=SENDER|52=20230207 15:06:56.858|56=TARGET|90=0|108=30|10=134|
<event> Initiated logon request
The thread 0X84a8 has exited with code 0(0x0).
i have a few questions:
Is it correct that whenever run() started, it will automatically tried to logon? or do I have to call a logon function?
Is there any additional setup required from the server side if I am trying to connect it with a new application? (Currently, there is already a program connecting to it, so the network is not a concern)
How can I logon to the session and get the heartbeat and send orders after
Here is my code
Initiator.cs
using QuickFix;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FIXLogAnalyser.FixSender
{
public partial class Initiator : Form
{
public Initiator()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("=============");
Console.WriteLine("This is only an example program, meant to run against the Executor or SimpleAcceptor example programs.");
Console.WriteLine();
Console.WriteLine(" ! ! !");
Console.WriteLine(" DO NOT USE THIS ON A COMMERCIAL FIX INTERFACE! It won't work and it's a bad idea!");
Console.WriteLine(" ! ! !");
Console.WriteLine();
Console.WriteLine("=============");
//if (args.Length != 1)
//{
// System.Console.WriteLine("usage: TradeClient.exe CONFIG_FILENAME");
// System.Environment.Exit(2);
//}
string file = "tradeclient.cfg";
try
{
QuickFix.SessionSettings settings = new QuickFix.SessionSettings(file);
TradeClientApp application = new TradeClientApp();
QuickFix.IMessageStoreFactory storeFactory = new QuickFix.FileStoreFactory(settings);
QuickFix.ILogFactory logFactory = new QuickFix.ScreenLogFactory(settings);
QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, logFactory);
// this is a developer-test kludge. do not emulate.
application.MyInitiator = initiator;
initiator.Start();
Console.WriteLine(initiator.IsLoggedOn());
application.Run();
initiator.Stop();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Environment.Exit(1);
}
}
}
tradeClientApp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuickFix;
using QuickFix.Fields;
namespace FIXLogAnalyser.FixSender
{
class TradeClientApp : QuickFix.MessageCracker, QuickFix.IApplication
{
Session _session = null;
// This variable is a kludge for developer test purposes. Don't do this on a production application.
public IInitiator MyInitiator = null;
#region IApplication interface overrides
public void OnCreate(SessionID sessionID)
{
_session = Session.LookupSession(sessionID);
}
public void OnLogon(SessionID sessionID)
{
try
{
Console.WriteLine("Logon - " + sessionID.ToString());
}
catch (Exception ex)
{
Console.WriteLine("fail: " + ex.Message);
}
}
public void OnLogout(SessionID sessionID) { Console.WriteLine("Logout - " + sessionID.ToString()); }
public void FromAdmin(Message message, SessionID sessionID)
{
Console.WriteLine("from admin: " + message);
}
public void ToAdmin(Message message, SessionID sessionID)
{
Console.WriteLine(sessionID.SenderCompID + " - " + sessionID.TargetCompID);
if (message.GetType() == typeof(QuickFix.FIX42.Logon))
{
// message.SetField(new Username("YOUR_USERNAME"));
// message.SetField(new Password("YOUR_PASSWORD"));
}
// message.SetField(new QuickFix.Fields.Account("YOUR_ACCOUNT_NUMBER"));
}
public void FromApp(Message message, SessionID sessionID)
{
Console.WriteLine("IN: " + message.ToString());
try
{
Crack(message, sessionID);
}
catch (Exception ex)
{
Console.WriteLine("==Cracker exception==");
Console.WriteLine(ex.ToString());
Console.WriteLine(ex.StackTrace);
}
}
public void ToApp(Message message, SessionID sessionID)
{
try
{
bool possDupFlag = false;
if (message.Header.IsSetField(QuickFix.Fields.Tags.PossDupFlag))
{
possDupFlag = QuickFix.Fields.Converters.BoolConverter.Convert(
message.Header.GetString(QuickFix.Fields.Tags.PossDupFlag)); /// FIXME
}
if (possDupFlag)
throw new DoNotSend();
}
catch (FieldNotFoundException)
{ }
Console.WriteLine();
Console.WriteLine("OUT: " + message.ToString());
}
#endregion
#region MessageCracker handlers
public void OnMessage(QuickFix.FIX42.ExecutionReport m, SessionID s)
{
Console.WriteLine("Received execution report");
}
public void OnMessage(QuickFix.FIX42.OrderCancelReject m, SessionID s)
{
Console.WriteLine("Received order cancel reject");
}
#endregion
public void Run()
{
try
{
Console.WriteLine(MyInitiator.IsLoggedOn());
char action = QueryAction();
if (action == '1')
QueryEnterOrder();
else if (action == '2')
QueryCancelOrder();
else if (action == '3')
QueryReplaceOrder();
else if (action == '4')
QueryMarketDataRequest();
else if (action == 'g')
{
if (this.MyInitiator.IsStopped)
{
Console.WriteLine("Restarting initiator...");
this.MyInitiator.Start();
}
else
Console.WriteLine("Already started.");
}
else if (action == 'x')
{
if (this.MyInitiator.IsStopped)
Console.WriteLine("Already stopped.");
else
{
Console.WriteLine("Stopping initiator...");
this.MyInitiator.Stop();
}
}
else if (action == 'q' || action == 'Q')
Console.WriteLine("break");// break;
Console.WriteLine(MyInitiator.IsLoggedOn());
}
catch (System.Exception e)
{
Console.WriteLine("Message Not Sent: " + e.Message);
Console.WriteLine("StackTrace: " + e.StackTrace);
}
Console.WriteLine("Program shutdown.");
}
private void SendMessage(Message m)
{
if (_session != null)
_session.Send(m);
else
{
// This probably won't ever happen.
Console.WriteLine("Can't send message: session not created.");
}
}
private char QueryAction()
{
// Commands 'g' and 'x' are intentionally hidden.
Console.Write("\n"
+ "1) Enter Order\n"
+ "2) Cancel Order\n"
+ "3) Replace Order\n"
+ "4) Market data test\n"
+ "Q) Quit\n"
+ "Action: "
);
HashSet<string> validActions = new HashSet<string>("1,2,3,4,q,Q,g,x".Split(','));
string cmd = "g";
// string cmd = Console.ReadLine().Trim();
if (cmd.Length != 1 || validActions.Contains(cmd) == false)
throw new System.Exception("Invalid action");
return cmd.ToCharArray()[0];
}
private void QueryEnterOrder()
{
Console.WriteLine("\nNewOrderSingle");
QuickFix.FIX42.NewOrderSingle m = QueryNewOrderSingle44();
if (m != null && QueryConfirm("Send order"))
{
m.Header.GetString(Tags.BeginString);
SendMessage(m);
}
}
private void QueryCancelOrder()
{
Console.WriteLine("\nOrderCancelRequest");
QuickFix.FIX42.OrderCancelRequest m = QueryOrderCancelRequest44();
if (m != null && QueryConfirm("Cancel order"))
SendMessage(m);
}
private void QueryReplaceOrder()
{
Console.WriteLine("\nCancelReplaceRequest");
QuickFix.FIX42.OrderCancelReplaceRequest m = QueryCancelReplaceRequest42();
if (m != null && QueryConfirm("Send replace"))
SendMessage(m);
}
private void QueryMarketDataRequest()
{
Console.WriteLine("\nMarketDataRequest");
QuickFix.FIX42.MarketDataRequest m = QueryMarketDataRequest44();
if (m != null && QueryConfirm("Send market data request"))
SendMessage(m);
}
private bool QueryConfirm(string query)
{
Console.WriteLine();
Console.WriteLine(query + "?: ");
// string line = Console.ReadLine().Trim();
string line = "y";
return (line[0].Equals('y') || line[0].Equals('Y'));
}
#region Message creation functions
private QuickFix.FIX42.NewOrderSingle QueryNewOrderSingle44()
{
QuickFix.Fields.OrdType ordType = null;
QuickFix.FIX42.NewOrderSingle newOrderSingle = new QuickFix.FIX42.NewOrderSingle(
QueryClOrdID(),
QueryHandlInst(),
QuerySymbol(),
QuerySide(),
new TransactTime(DateTime.Now),
ordType = QueryOrdType()); ;
newOrderSingle.Set(new HandlInst('1'));
newOrderSingle.Set(QueryOrderQty());
newOrderSingle.Set(QueryTimeInForce());
if (ordType.getValue() == OrdType.LIMIT || ordType.getValue() == OrdType.STOP_LIMIT)
newOrderSingle.Set(QueryPrice());
if (ordType.getValue() == OrdType.STOP || ordType.getValue() == OrdType.STOP_LIMIT)
newOrderSingle.Set(QueryStopPx());
return newOrderSingle;
}
private QuickFix.FIX42.OrderCancelRequest QueryOrderCancelRequest44()
{
QuickFix.FIX42.OrderCancelRequest orderCancelRequest = new QuickFix.FIX42.OrderCancelRequest(
QueryOrigClOrdID(),
QueryClOrdID(),
QuerySymbol(),
QuerySide(),
new TransactTime(DateTime.Now));
orderCancelRequest.Set(QueryOrderQty());
return orderCancelRequest;
}
private QuickFix.FIX42.OrderCancelReplaceRequest QueryCancelReplaceRequest42()
{
QuickFix.FIX42.OrderCancelReplaceRequest ocrr = new QuickFix.FIX42.OrderCancelReplaceRequest(
QueryOrigClOrdID(),
QueryClOrdID(),
QueryHandlInst(),
QuerySymbol(),
QuerySide(),
new TransactTime(DateTime.Now),
QueryOrdType());
ocrr.Set(new HandlInst('1'));
if (QueryConfirm("New price"))
ocrr.Set(QueryPrice());
if (QueryConfirm("New quantity"))
ocrr.Set(QueryOrderQty());
return ocrr;
}
private QuickFix.FIX42.MarketDataRequest QueryMarketDataRequest44()
{
MDReqID mdReqID = new MDReqID("MARKETDATAID");
SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT);
MarketDepth marketDepth = new MarketDepth(0);
QuickFix.FIX42.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX42.MarketDataRequest.NoMDEntryTypesGroup();
marketDataEntryGroup.Set(new MDEntryType(MDEntryType.BID));
QuickFix.FIX42.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX42.MarketDataRequest.NoRelatedSymGroup();
symbolGroup.Set(new Symbol("LNUX"));
QuickFix.FIX42.MarketDataRequest message = new QuickFix.FIX42.MarketDataRequest(mdReqID, subType, marketDepth);
message.AddGroup(marketDataEntryGroup);
message.AddGroup(symbolGroup);
return message;
}
#endregion
#region field query private methods
private ClOrdID QueryClOrdID()
{
Console.WriteLine();
Console.Write("ClOrdID? ");
return new ClOrdID("orderID123");
// return new ClOrdID(Console.ReadLine().Trim());
}
private OrigClOrdID QueryOrigClOrdID()
{
Console.WriteLine();
Console.Write("OrigClOrdID? ");
//return new OrigClOrdID(Console.ReadLine().Trim())
return new OrigClOrdID("OrigClordID123");
}
private HandlInst QueryHandlInst()
{
Console.WriteLine();
Console.Write("QueryHandlInst? ");
// return new HandlInst(Console.ReadLine()[0]);
return new HandlInst('1');
}
private Symbol QuerySymbol()
{
Console.WriteLine();
Console.Write("Symbol? ");
// return new Symbol(Console.ReadLine().Trim());
return new Symbol("700 HK");
}
private Side QuerySide()
{
Console.WriteLine();
Console.WriteLine("1) Buy");
Console.WriteLine("2) Sell");
Console.WriteLine("3) Sell Short");
Console.WriteLine("4) Sell Short Exempt");
Console.WriteLine("5) Cross");
Console.WriteLine("6) Cross Short");
Console.WriteLine("7) Cross Short Exempt");
Console.Write("Side? ");
// string s = Console.ReadLine().Trim();
string s = "1";
char c = ' ';
switch (s)
{
case "1": c = Side.BUY; break;
case "2": c = Side.SELL; break;
case "3": c = Side.SELL_SHORT; break;
case "4": c = Side.SELL_SHORT_EXEMPT; break;
case "5": c = Side.CROSS; break;
case "6": c = Side.CROSS_SHORT; break;
case "7": c = 'A'; break;
default: throw new Exception("unsupported input");
}
return new Side(c);
}
private OrdType QueryOrdType()
{
Console.WriteLine();
Console.WriteLine("1) Market");
Console.WriteLine("2) Limit");
Console.WriteLine("3) Stop");
Console.WriteLine("4) Stop Limit");
Console.Write("OrdType? ");
//string s = Console.ReadLine().Trim();
string s = "1";
char c = ' ';
switch (s)
{
case "1": c = OrdType.MARKET; break;
case "2": c = OrdType.LIMIT; break;
case "3": c = OrdType.STOP; break;
case "4": c = OrdType.STOP_LIMIT; break;
default: throw new Exception("unsupported input");
}
return new OrdType(c);
}
private OrderQty QueryOrderQty()
{
Console.WriteLine();
Console.Write("OrderQty? ");
// return new OrderQty(Convert.ToDecimal(Console.ReadLine().Trim()));
return new OrderQty(Convert.ToDecimal("400.00"));
}
private TimeInForce QueryTimeInForce()
{
Console.WriteLine();
Console.WriteLine("1) Day");
Console.WriteLine("2) IOC");
Console.WriteLine("3) OPG");
Console.WriteLine("4) GTC");
Console.WriteLine("5) GTX");
Console.Write("TimeInForce? ");
// string s = Console.ReadLine().Trim();
string s = "1";
char c = ' ';
switch (s)
{
case "1": c = TimeInForce.DAY; break;
case "2": c = TimeInForce.IMMEDIATE_OR_CANCEL; break;
case "3": c = TimeInForce.AT_THE_OPENING; break;
case "4": c = TimeInForce.GOOD_TILL_CANCEL; break;
case "5": c = TimeInForce.GOOD_TILL_CROSSING; break;
default: throw new Exception("unsupported input");
}
return new TimeInForce(c);
}
private Price QueryPrice()
{
Console.WriteLine();
Console.Write("Price? ");
return new Price(Convert.ToDecimal(Console.ReadLine().Trim()));
}
private StopPx QueryStopPx()
{
Console.WriteLine();
Console.Write("StopPx? ");
return new StopPx(Convert.ToDecimal(Console.ReadLine().Trim()));
}
#endregion
}
}
tradeClient.cfg
[DEFAULT]
ConnectionType=initiator
ReconnectInterval=2
FileStorePath=logpath
FileLogPath=log
StartTime=01:00:00
EndTime=23:00:00
UseDataDictionary=Y
DataDictionary=FIX42.xml
SocketConnectHost=xxx.xxx.xxx.xxx
SocketConnectPort=xxxx
LogoutTimeout=5
ResetOnLogon=N
ResetOnDisconnect=Y
[SESSION]
# inherit ConnectionType, ReconnectInterval and SenderCompID from default
BeginString=FIX.4.2
SenderCompID=SENDER
TargetCompID=TARGET
HeartBtInt=30

xUnit for Rabbit MQ mock connection in C#

I have a .NET Core service which publishes messages in Rabbit MQ.
Below is part of my code:
public void PublishToOrchestrationRMQ(List<string> content,
string queueName, string TraceID)
{
if (content != null)
{
string OrderStatusQueue = string.Empty;
string OrderStatusDLQueue = string.Empty;
string exchange = string.Empty;
GlobalConfig configData = new GlobalConfig();
configData.GlobalSettings = _configServerData.Value.GlobalSettings;
if (configData.GlobalSettings != null)
{
switch (queueName)
{
case "ASN":
break;
case "SO":
OrderStatusQueue = configData.GlobalSettings.RMQ_SO_Orchestration;
exchange = configData.GlobalSettings.RMQ_SO_Orchestration_Exchange;
OrderStatusDLQueue = configData.GlobalSettings.RMQ_DLQ_SO_Orchestration;
break;
case "WO":
OrderStatusQueue = configData.GlobalSettings.RMQ_WO_DM;
exchange = configData.GlobalSettings.RMQ_WO_DM_EXCHANGE;
OrderStatusDLQueue = configData.GlobalSettings.RMQ_DLQ_WO_DM;
break;
}
RabbitMqHelper rmqHelper = GetRabbitMQConnection(TraceID);
try
{
IConnection RMQconnection = rmqHelper.ReConnectQueue();
PushToRMQ(RMQconnection, exchange, OrderStatusQueue, content, TraceID, OrderStatusDLQueue);
}
catch (Exception Ex)
{
}
finally
{
rmqHelper.Cleanup();
}
}
else
_mLogger.Error(this, TraceID, $"No data to publish");
}
}
This line
IConnection RMQconnection = rmqHelper.ReConnectQueue();
just connects to Rabbit MQ and is declared locally in the method.
My question is how do I mock connection for that line.

How to get the result of the check of the Internet in a different class?

In my application checks for an Internet connection and access to my site. I can not get a result in another class. There is a solution through localSettings.Values, but it's not what I want. Please help me. Thank you
public class NetworkUtils{
public enum ConnType
{
CONN_MOBILE,
CONN_WIFI,
CONN_WAN,
CONN_NO,
CONN_MY
}
public ConnType GetConnectionGeneration()
{
string connectionProfileInfo = string.Empty;
try
{
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (InternetConnectionProfile == null)
{
NotifyUser("Not connected to Internet\n");
return (ConnType.CONN_NO);
}
else
{
if (InternetConnectionProfile.IsWlanConnectionProfile)
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, 300);
try
{
httpClient.GetAsync(new Uri("http://www.myexample.com")).Wait();
NotifyUser("MY SITE connected\n");
return (ConnType.CONN_MY);
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
}
return (ConnType.CONN_WIFI);
}
else if (InternetConnectionProfile.IsWwanConnectionProfile)
{
WwanDataClass connectionClass = InternetConnectionProfile.WwanConnectionProfileDetails.GetCurrentDataClass();
switch (connectionClass)
{
//2G-equivalent
case WwanDataClass.Edge:
case WwanDataClass.Gprs:
//3G-equivalent
case WwanDataClass.Cdma1xEvdo:
case WwanDataClass.Cdma1xEvdoRevA:
case WwanDataClass.Cdma1xEvdoRevB:
case WwanDataClass.Cdma1xEvdv:
case WwanDataClass.Cdma1xRtt:
case WwanDataClass.Cdma3xRtt:
case WwanDataClass.CdmaUmb:
case WwanDataClass.Umts:
case WwanDataClass.Hsdpa:
case WwanDataClass.Hsupa:
//4G-equivalent
case WwanDataClass.LteAdvanced:
return (ConnType.CONN_MOBILE);
//not connected
case WwanDataClass.None:
return (ConnType.CONN_NO);
//unknown
case WwanDataClass.Custom:
default:
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, 300);
try
{
httpClient.GetAsync(new Uri("http://www.myexample.com")).Wait();
return (ConnType.CONN_MY);
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
}
return (ConnType.CONN_WAN);
}
}
return (ConnType.CONN_MOBILE);
}
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
return (ConnType.CONN_NO);
}
}
}
If I do something not so correct. If there are good ideas, too, I will be grateful. I tested so, but nothing happens.
public sealed partial class TestPage : Page
{
public TestPage()
{
InitializeComponent();
if (NetworkUtils.ConnType.CONN_MY.ToString().Equals("CONN_MY"){
TextBlock.Text = "GOOD Connection";
} else if (NetworkUtils.ConnType.CONN_WIFI.ToString().Equals("CONN_MY"){
TextBlock.Text = "WIFI Connection";
}
...
}
}
var generation = new NetworkUtils().GetConnectionGeneration();
swtich (generation)
{
case NetworkUtils.ConnType.CONN_MY:
{
//...
break;
}
case NetworkUtils.ConnType.CONN_WIF:
{
//...
break;
}
// othes cases
default:
// handle exceptional case
}
var gen = new NetworkUtils().GetConnectionGeneration();
if (gen == NetworkUtils.ConnType.CONN_MY) {
//...
}
Problem is you are checking toString of an enum member (CONN_MY), so first line of your if statement is always true, and it will always display Good Connection. You had to call GetConnectionGeneration() first.

How to check access rights on remote hosts and local and UNC paths?

I write a program, where the user can select local and remote directories. Before performing any operation on a selected path, I want to check if it's valid and if the user has read/write permission(s) granted on it. That's what I have:
private bool checkInput(string dirPath, string depthStr, string filename)
{
...
string reason = null;
try
{
...
else if ((reason = CAN_ACCESS(dirPath)) == null)
{
if (!(new DirectoryInfo(dirPath)).Exists)
reason = string.Format("The directory '{0}' is no directory or does not exist!", dirPath);
...
}
}
catch (Exception ex)
{
reason = ex.Message;
}
if (reason != null)
{
MessageBox.Show(reason, "Wrong input", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
return true;
}
public static string CAN_ACCESS(string dirPath)
{
Uri uri = new Uri(dirPath);
//UserFileAccessRights rights = new UserFileAccessRights(dirPath);
string errorMsg = null;
if (uri.IsUnc && !haveAccessPermissionOnHost(uri))
{
string domain = new Uri(dirPath).Host;
domain = dirPath;
ErrorClass res = PinvokeWindowsNetworking.connectToRemote(domain, null, null, true);
if (res == null)
return null;
else
errorMsg = string.Format("(Code {0}): {1}", res.num, res.message);
}
return errorMsg;
}
private static bool haveAccessPermissionOnHost(Uri uri)
{
throw new NotImplementedException();
}
The primary question is, how to simple check in haveAccessPermissionOnHost(Uri uri), if a user has read/write permission(s) on a remote host and unc path granted.
Hint:
If no permissions granted, the well known Windows logon window pops up to force the user to enter some credentials, which is working fine:
ErrorClass res = PinvokeWindowsNetworking.connectToRemote(domain, null, null, true);
I got it from this question (and changed the provided code to return the ErrorClass, null on success).
My secondary question is, if my structure in general is the way to go to check a path, whether it's local or remote, for validity (that's why I provided more code as necessary).
I found myself a workaround, since nobody replied to this question:
public static bool canAccess(DirectoryInfo dirInfo)
{
Uri uri = new Uri(dirInfo.FullName);
// is this a remote path?
if (uri.IsUnc)
{
if (hostOnline(uri.Host))
{
// check if remote path exists
if (!dirInfo.Exists)
{
string domain = dirInfo.FullName;
ErrorClass res = PinvokeWindowsNetworking.connectToRemote(domain, null, null, true);
if (res == null)
{
if (!dirInfo.Exists)
throw new Exception(
string.Format("No access permissions or directory not existing."));
return true;
}
else if (res.num == 53)
throw new Exception("Remote directory not existing.");
else
throw new Exception(
string.Format("(Code {0}): {1}", res.num, res.message));
}
}
else
throw new Exception("Unknown host or not online.");
}
// local directory existing?
return dirInfo.Exists;
}
private static bool hostOnline(string hostname)
{
Ping ping = new Ping();
try
{
PingReply pr = ping.Send(hostname);
return pr.Status == IPStatus.Success;
}
catch (Exception)
{
return false;
}
}

C# WIA System.InvalidOperationException

I have a problem with scanning with WIA.
public List<Image> Scan(string scannerId)
{
var images = new List<Image>();
var hasMorePages = true;
while (hasMorePages)
{
// select the correct scanner using the provided scannerId parameter
var manager = new DeviceManager();
Device device = null;
foreach (DeviceInfo info in manager.DeviceInfos)
{
if (info.DeviceID == scannerId)
{
// connect to scanner
device = info.Connect();
break;
}
}
// device was not found
if (device == null)
{
// enumerate available devices
string availableDevices = "";
foreach (DeviceInfo info in manager.DeviceInfos)
{
availableDevices += info.DeviceID + "n";
}
// show error with available devices
throw new Exception("The device with provided ID could not be found. Available Devices:n" +
availableDevices);
}
Item item = device.Items[1];
try
{
// scan image
ICommonDialog wiaCommonDialog = new CommonDialog();
var image = (ImageFile) wiaCommonDialog.ShowTransfer(item, WiaFormatBmp, true); // <--- exception goes from there
// save to temp file
string fileName = "test.bmp";//Path.GetTempFileName();
File.Delete(fileName);
image.SaveFile(fileName);
image = null;
// add file to output list
images.Add(Image.FromFile(fileName));
}
catch (Exception exc)
{
throw exc;
}
finally
{
item = null;
//determine if there are any more pages waiting
Property documentHandlingSelect = null;
Property documentHandlingStatus = null;
foreach (Property prop in device.Properties)
{
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
documentHandlingSelect = prop;
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
documentHandlingStatus = prop;
}
// assume there are no more pages
hasMorePages = false;
// may not exist on flatbed scanner but required for feeder
if (documentHandlingSelect != null)
{
// check for document feeder
if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) && WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
{
hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) &&
WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
}
}
}
}
return images;
}
When the scanning is completed i get an exception: "Dynamic operations can only be performed in homogenous AppDomain.". Can someone explain me what im doing wrong? I tried to use it in another Thread but still get the same exception.
Scanner: DSmobile 700D.

Categories

Resources