Quickfix with c# issue connecting with Initiator - c#

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

Related

How to Display the details of a single person from a text file onto the console in C# from a PhoneBook for example?

static void AddContact()
{
string path = #"C:\Users\...\Desktop\Projekte\C# Übungen\ContactList/contacts.txt";
string name, address;
int phoneNumber;
bool addingContact = true;
string response;
List<string> ContactList = File.ReadAllLines(path).ToList();
while(addingContact)
{
System.Console.Write("Name: ");
name = Console.ReadLine();
System.Console.Write("Nummer: ");
phoneNumber = int.Parse(Console.ReadLine());
System.Console.Write("Adresse: ");
address = Console.ReadLine();
ContactList.Add($"Name: {name}");
ContactList.Add($"Nummer: {phoneNumber}");
ContactList.Add($"Adresse: {address} \n---------------------------------");
foreach (var contact in ContactList)
{
File.WriteAllLines(path, ContactList);
}
Console.Clear();
System.Console.WriteLine("Contact added successfully! Would you like to Add another Contact? (y)(n)");
response = Console.ReadLine().ToLower();
if(response == "y")
{
Console.Clear();
}
else
{
addingContact = false;
}
}
Console.WriteLine("Good bye!");
}
static void ShowContact()
{
string path = #"C:\Users\...\Desktop\Projekte\C# Übungen\ContactList/contacts.txt";
string response;
System.Console.WriteLine("Would you like to see all contacts (0) or a specific one (1)?");
response = Console.ReadLine();
switch (response)
{
case "0":
File.ReadAllLines(path);
break;
case "1":
System.Console.WriteLine("Type the name of the user: ");
string username = Console.ReadLine();
File.ReadAllLines(path)
break;
}
}
Thats everything. In the switch Statement at case 1 is where the problem is. I want it to look something like this if the user types John for example:
Name: John
Number: 233
Address: lolol 23
I already tried out something but i stopped in the middle of writing it because i realized that i dont actually know how to code that so i made my way over to stackoverflow to ask for help, thanks. Please be polite and i know that this code isnt the best, im a beginner.
Edit: I just found out that ShowContacts doesnt work at all
Edit 2: Fixed it with a foreach loop and List
List<string> contacts = File.ReadAllLines(path).ToList();
System.Console.WriteLine("Would you like to see all contacts (0) or a specific one (1)?");
response = Console.ReadLine();
switch (response)
{
case "0":
foreach (var contact in contacts)
{
Console.WriteLine(contact);
}
break;
}
Okay, if each item is broken down by three values consider chunking the data by three than iterate the results.
Change the Debug.WriteLine to Console.WriteLine below for your code.
Extension method for chunking
public static class ListExtensions
{
public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)
=> source
.Select((value, index) => new { Index = index, Value = value })
.GroupBy(x => x.Index / chunkSize)
.Select(grp => grp.Select(v => v.Value).ToList())
.ToList();
}
File contents
John
111
John's address
Mary
222
Mary's address
Bill
333
Bill's address
Code to first assert data is divisible by three than read the data, no assertion of data types or if null values are performed.
var contents = File.ReadAllLines("TextFile1.txt");
if (contents.Length % 3 == 0)
{
var results = contents.ToList().ChunkBy(3);
foreach (var list in results)
{
Debug.WriteLine($" Name: {list[0]}");
Debug.WriteLine($" Number: {list[1]}");
Debug.WriteLine($"Address: {list[2]}");
}
}
else
{
Debug.WriteLine("Malformed");
}
Edit: placed into a method
private static void ViewAllContacts()
{
var fileName = "TextFile1.txt";
if (File.Exists(fileName))
{
var contents = File.ReadAllLines(fileName);
if (contents.Length % 3 == 0)
{
var results = contents.ToList().ChunkBy(3);
foreach (var list in results)
{
Debug.WriteLine($" Name: {list[0]}");
Debug.WriteLine($" Number: {list[1]}");
Debug.WriteLine($"Address: {list[2]}");
}
}
else
{
Debug.WriteLine("Malformed");
}
}
else
{
Debug.WriteLine($"{fileName} not found");
}
}
Save your contact to json format, like this:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.IO;
namespace JsonTester
{
// Open Package Manager Console:
// Tools >> Nuget Package Manager >> Package Manager Console
//
// Install libraries through Package Manager Console:
// PM > Install-Package System.Text.Json -Version 6.0.1
internal class Program
{
static List<Contact> contactList = new List<Contact>();
static readonly string MY_CONTACT = #"D:\MyContact.txt";
class Contact {
public string Name { get; set; }
public string Number { get; set; }
public string Address { get; set; }
}
static void EnterContact() {
var contact = new Contact();
Console.WriteLine("Name: ");
contact.Name = Console.ReadLine();
Console.WriteLine("Number: ");
contact.Number = Console.ReadLine();
Console.WriteLine("Address: ");
contact.Address = Console.ReadLine();
contactList.Add(contact);
}
static void SaveContact() {
if (contactList.Count > 0) {
foreach (Contact contact in contactList) {
String strContactJson = JsonSerializer.Serialize(contact);
File.AppendAllText(MY_CONTACT, strContactJson + "\n");
}
}
}
static void ReadContact()
{
try
{
Console.WriteLine("Read contact list:\n");
String[] strContactJsonArr = File.ReadAllLines(MY_CONTACT);
if (strContactJsonArr.Length > 0)
{
foreach (String s in strContactJsonArr)
{
Contact contact = JsonSerializer.Deserialize<Contact>(s);
if (contact != null)
{
Console.WriteLine("Name: " + contact.Name);
Console.WriteLine("Number: " + contact.Number);
Console.WriteLine("Address: " + contact.Address);
Console.WriteLine("");
}
}
Console.WriteLine("Found {0} contacts\n\n", strContactJsonArr.Length);
}
}
catch (Exception) {
Console.WriteLine("Contact list is empty\n");
}
}
static bool SearchContact(String name)
{
try
{
String[] strContactJsonArr = File.ReadAllLines(MY_CONTACT);
if (strContactJsonArr.Length > 0)
{
foreach (String s in strContactJsonArr)
{
Contact contact = JsonSerializer.Deserialize<Contact>(s);
if (contact != null)
{
if (contact.Name.Equals(name)) {
Console.WriteLine("");
Console.WriteLine("Name: " + contact.Name);
Console.WriteLine("Number: " + contact.Number);
Console.WriteLine("Address: " + contact.Address);
Console.WriteLine("");
return true;
}
}
}
}
}
catch (Exception)
{
}
return false;
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("- Press S for search contact.\n- Press N for new contact.\n- Press R for read contact list.\n");
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.KeyChar == 's' || key.KeyChar == 'S')
{
Console.WriteLine("Searching contact.");
Console.Write("Enter name: ");
String name = Console.ReadLine();
bool isFounded = SearchContact(name);
if (isFounded)
{
Console.WriteLine("Contact is found\n");
}
else
{
Console.WriteLine("Contact isn't found!\n");
}
}
else if (key.KeyChar == 'n' || key.KeyChar == 'N')
{
EnterContact();
SaveContact();
}
else if (key.KeyChar == 'r' || key.KeyChar == 'R') {
ReadContact();
}
}
}
}
}
Console Output:
MyContact.txt (contact save in JSON format):

The type or namespace name 'BluetoothAddress' could not be found

I use vs 2017 and windows 7.
I have installed 32feet.NET following this: Looking to write Bluetooth 'hcitool' equivelant in Windows.
But I get the errors:
The type or namespace name 'BluetoothAddress' could not be found
The type or namespace name 'BluetoothClient' could not be found
The type or namespace name 'BluetoothSecurity' could not be found
The type or namespace name 'BluetoothDeviceInfo' could not be found
The type or namespace name 'ServiceRecord' could not be found
I have successfully installed InTheHand.Devices.Bluetooth and There is no warning in the using sentence so the namespace is successfully referenced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Devices.Bluetooth;
using InTheHand.Networking;
using InTheHand.Networking.Sockets;
using InTheHand;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
//var dev = new BluetoothDeviceInfo(_searchAddress);
var dev = new BluetoothDevice();
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try
{
list = BluetoothRadio.AllRadios;
}
catch (Exception)
{
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list)
{
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null)
{
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null)
{
return 0;
}
else
{
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices)
{
if (cur.DeviceAddress == _searchAddress)
{
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName)
{
try
{
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
}
catch (Exception ex)
{
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try
{
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
}
catch (SocketException)
{
inRange = false;
}
return inRange;
}
}
}
The BluetoothAddress is in the 32feet.NET nuget package.
You're using the preview version of InTheHand which is missing the BluetoothAddress, the BluetoothRadio, BluetoothDeviceInfo and others.
I think you're referencing the wiki for the 32feet.NET, which is the legacy nuget package.
If you install 32feet.NET v3.5.0.0, you will find all your missing bindings.
Adding 32feet.NET and changing a couple of things:
var dev = new BluetoothDevice();
//this becomes this:
var dev = new BluetoothDeviceInfo(_searchAddress);
it will compile succesfully.
Try to add the following namespaces to your code:
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

how to cancel parallel.foreach loop from inside a task

I have a ImageProcessor class that creates a list of tasks for each of the image providers, inside of these tasks I then run a parallel.foreach loop for all the images for each provider, I want to be able to cancel all the tasks and nested parallel loops from the console, I've found example of how to cancel tasks and how to cancel parallel loops, but I am unsure as how to do it for nested processes.
Below is the code I have at the moment
From my console app:
using (IUnityContainer container = Bootstrapper.Initialise())
{
IImageProcessor processor = container.Resolve<IImageProcessor>();
processor.Container = container;
try
{
InputArguments arguments = new InputArguments(args);
if (arguments.Contains("fs"))
{
processor.Initialise(arguments["fs"]);
}
else
{
processor.Initialise();
}
processor.Run();
Console.WriteLine("\r\n\n\nPress any key to Exit");
Console.ReadLine();
return (int)ExitCode.Success;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("\r\n\n\nPress any key to Exit");
Console.ReadLine();
return (int)ExitCode.UnknownError;
}
}
The Run method
public void Run()
{
List<Task> tasks = new List<Task>();
foreach (IFileService fileservice in this.fileServices)
{
Task task = Task.Factory.StartNew((arg) =>
{
IFileService fs = (IFileService)arg;
string msg = $"Processing {fs.ToString()}...";
FileLogger.Write(msg, fs.ToString());
ConsoleLogger.WriteLine(msg);
fs.ProcessFiles();
//fileservice.ReprocessUnMatchedData();
}, fileservice);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
and inside each file service I have call this method:
protected bool ProcessFileRecord<T>() where T : IDataRecord
{
int matched = 0;
int notMatched = 0;
int skipped = 0;
bool result;
object lockObject = new object();
try
{
processTracker = GetTracker();
if (databaseHelper.TrackerFullyProcessed(processTracker))
{
LoggingService.Write("File already processed... Skipping.", LoggingTarget.All, serviceName);
result = true;
}
LoggingService.Write($"\r\nProcessing index file {fileRecord.IndexFileName}", LoggingTarget.File, serviceName);
Parallel.ForEach(
fileRecord.DataRecords,
new ParallelOptions() { MaxDegreeOfParallelism = Thread.CurrentThread.ManagedThreadId },
(item) =>
{
switch ((RecordProcessResult)ProcessRecord(item))
{
case RecordProcessResult.Invalid:
break;
case RecordProcessResult.Matched:
Increment(ref matched);
break;
case RecordProcessResult.NotMatched:
Increment(ref notMatched);
break;
case RecordProcessResult.Skipped:
Increment(ref skipped);
break;
default:
break;
}
lock (lockObject)
{
if ((matched + notMatched + skipped) % 100 == 0)
{
LoggingService.Write($"\tMatched: {matched}\tNot Matched: {notMatched}\tSkipped: {skipped}\t total: {matched + notMatched + skipped}", LoggingTarget.Trace & LoggingTarget.Console, serviceName);
}
}
});
LoggingService.Write($"Total Lines: {matched + notMatched + skipped} \r\nMatched: {matched} \r\nNot Matched: {notMatched} \r\nSkipped: {skipped}", LoggingTarget.All, serviceName);
this.databaseHelper.UpdateTracker(this.processTracker, matched, notMatched);
result = true;
}
catch (Exception ex)
{
LoggingService.Write($"Error processing data file:{fileRecord.IndexFileName}", LoggingTarget.All, serviceName);
LoggingService.Write($"{ex.ExceptionTreeAsString()}", LoggingTarget.All, serviceName);
LoggingService.Write($"Total Lines: {(matched + notMatched + skipped)} \r\nMatched: {matched} \r\nNot Matched: {notMatched} \r\nSkipped: {skipped}", LoggingTarget.All, serviceName);
this.databaseHelper.UpdateTracker(this.processTracker, matched, notMatched);
result = false;
}
return result;
}
Thank.
Please, look an example on this page
CancellationTokenSource

My StreamWriter isn't giving an error, but isn't writing to the .txt file?

Thank you for all your suggestions!
I'm really confused as to why this still isn't working, the 'Customers.txt' is just included in the solution and it opens it fine with the StreamReader, this is my full code :/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CustomerDetails
{
class Program
{
class userDetails
{
public static List<string> firstName;
public static List<string> lastName;
public static List<string> telNumber;
public static List<string> birthDate;
public static List<string> postCode;
public static string userDecision;
}
static void Main(string[] args)
{
int x = 1;
userDetails.firstName = new List<string>();
userDetails.lastName = new List<string>();
userDetails.birthDate = new List<string>();
userDetails.telNumber = new List<string>();
userDetails.postCode = new List<string>();
while (x == 1)
{
Console.WriteLine("------------------------------");
Console.WriteLine(" CUSTOMER DATABASE ");
Console.WriteLine("------------------------------");
Console.WriteLine("1.) Add Customer(s)");
Console.WriteLine("2.) List Customers");
Console.WriteLine("3.) Exit");
Console.WriteLine("------------------------------");
userDetails.userDecision = Console.ReadLine().Trim().ToUpper().Replace(" ", "");
if (userDetails.userDecision == "1" ||
userDetails.userDecision == "2" ||
userDetails.userDecision == "3")
break;
else
Console.Clear();
}
if (userDetails.userDecision == "3") { Environment.Exit(0); }
Console.Clear();
Console.WriteLine("------------------------------");
Console.WriteLine(" CUSTOMER DATABASE ");
Console.WriteLine("------------------------------");
if (userDetails.userDecision == "1")
{
int y = 0;
while (y > -1)
{
string input;
Console.Clear();
Console.WriteLine("------------------------------");
Console.WriteLine(" NEW CUSTOMER ");
Console.WriteLine("------------------------------");
Console.Write("First Name: ");
userDetails.firstName.Add(Console.ReadLine());
Console.Write(" Last Name: ");
userDetails.lastName.Add(Console.ReadLine());
Console.Write(" DOB: ");
userDetails.birthDate.Add(Console.ReadLine());
Console.Write("Tel Number: ");
userDetails.telNumber.Add(Console.ReadLine());
Console.Write(" Post Code: ");
userDetails.postCode.Add(Console.ReadLine());
Console.WriteLine("------------------------------");
int e = 0;
while (e == 0)
{
Console.Write("Add Another? Y/N:");
userDetails.userDecision = Console.ReadLine().ToUpper();
if (userDetails.userDecision == "Y" || userDetails.userDecision == "N")
e = 1;
}
if (userDetails.userDecision == "N")
{
break;
}
}
StreamWriter fileWriter = new StreamWriter(File.Open("Customers.txt", FileMode.Append));
int v = 0;
foreach (string element in userDetails.firstName)
{
fileWriter.WriteLine("/-----------\\");
fileWriter.WriteLine(userDetails.firstName[v]);
fileWriter.WriteLine(userDetails.lastName[v]);
fileWriter.WriteLine(userDetails.postCode[v]);
fileWriter.WriteLine(userDetails.birthDate[v]);
fileWriter.WriteLine(userDetails.telNumber[v]);
fileWriter.WriteLine("\\-----------/");
v++;
Console.WriteLine("DOING.");
}
fileWriter.Dispose();
fileWriter.Close();
Console.WriteLine("DONE.");
Console.ReadLine();
}
// LIST CUSTOMER DETAILS
//else if (userDetails.userDecision == "2")
//{
// StreamReader fileReader = new StreamReader("Customers.txt");
// string currentLine = "";
// while (currentLine != null)
// {
// currentLine = fileReader.ReadLine();
// if (currentLine != null) {
// if (currentLine != "/-----------\\") {
// if(currentLine == "\\-----------/")
// Console.WriteLine();
// else
// Console.WriteLine(currentLine); } }
// }
// fileReader.Close();
//}
//Console.ReadLine();
}
}
}
You are opening the file as many times as your loop runs.
You need to open the file then enter your loop code, then make sure it closes.
StreamWriter file= new StreamWriter(File.Open("fileName.txt", FileMode.CreateNew));
foreach (string element in userDetails.firstName)
{
file.WriteLine("testing 1 10 11");
}
file.Close();
file.Dispose();
It seems that using will close the file for you, but I still prefer file.Close() and file.Dispose() until I read more on using.
Change the
using (StreamWriter fileWriter = new StreamWriter("Customers.txt"))
line to
using (StreamWriter fileWriter = new StreamWriter(#"C:\Customers.txt"))
if you see a file on c:\ then the problem is the file is being written but not where you expect. Next to the executable is the common location for code like this, but not the only one.

C# Read Windows Mobile Broadband connection properties

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
}
}

Categories

Resources