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.
Related
I have created my app in Visual Studio 2019 for Android and iOS.
If I DEBUG my iOS app it is working perfectly as it should. It is debugged with iPhoneSimulator.
But if I rollout my RELEASE and test in on for example iPad, it seems that it can not find the SQLite DB whitch is stored like this:
string dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db");
Is there a problem maybe with the SpecialFolder 'Personal' on iOS?
This code will be processes during start up:
if (!File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db")))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Error", "DB could not be loaded !", "OK");
}
}
this is my DatabaseHelper class:
namespace VoTa.DataHelper
{
public class Database
{
readonly string dbpath = Data.GetPath();
private static readonly string ftpurl = "myURL";
public bool CreateDatabase()
{
try
{
var connection = new SQLiteConnection(dbpath);
connection.CreateTable<Belohnungen>();
connection.CreateTable<Vokabeln>();
connection.CreateTable<EigeneVokabel>();
connection.Close();
return true;
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return false;
}
}
public void InsertIntoVokabeln(string dateiname)
{
String voakbelURL = ftpurl + dateiname;
string id;
string fremdsprache;
string deutsch;
string info1;
string info2;
var connection = new SQLiteConnection(dbpath);
connection.Query<Vokabeln>("Delete from Vokabeln");
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(voakbelURL);
var vList = xmldoc.SelectNodes("/Vokabel/VokabelModel");
try
{
foreach (XmlNode node in vList)
{
id = node["Id"].InnerText;
fremdsprache = node["fremdsprache"].InnerText;
deutsch = node["deutsch"].InnerText;
info1 = "";
info2 = "";
if (node["info1"] != null)
{
info1 = node["info1"].InnerText;
}
if (node["info2"] != null)
{
info1 = node["info2"].InnerText;
}
Vokabeln vokabel = new Vokabeln
{
Fremdsprache = fremdsprache,
Deutsch = deutsch,
Info1 = info1,
Info2 = info2
};
connection.Insert(vokabel);
}
}
catch (Exception)
{
return;
}
finally
{
connection.Close();
}
}
public void InsertIntoBelohnungen(string dateiname)
{
String belohunngURL = ftpurl + dateiname;
string id;
string beloh;
string info1;
string info2;
var connection = new SQLiteConnection(dbpath);
connection.Query<Belohnungen>("Delete from Belohnungen");
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(belohunngURL);
var vList = xmldoc.SelectNodes("/Belohnung/BelohnungModel");
try
{
foreach (XmlNode node in vList)
{
id = node["Id"].InnerText;
beloh = node["Belohnung"].InnerText;
info1 = "";
info2 = "";
if (node["info1"] != null)
{
info1 = node["info1"].InnerText;
}
if (node["info2"] != null)
{
info1 = node["info2"].InnerText;
}
Belohnungen belohnung = new Belohnungen
{
Belohnung = beloh,
Info1 = info1,
Info2 = info2
};
connection.Insert(belohnung);
}
}
catch (Exception)
{
return;
}
finally
{
connection.Close();
}
}
It is working on iPhoneSimulator but not in "real".
Add DB file in the AppDelegate.cs file like:
string sqliteFilename = "MyDatabase.db";
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"..","Library");
string dbpath = Path.Combine(folderPath, sqliteFilename);
LoadApplication(new App(dbpath));
My App.xaml.cs:
public App(string dbpath)
{
InitializeComponent();
Data.SetPath(dbpath);
MainPage = new NavigationPage(new MainPage());
}
My MainView:
switch (Device.RuntimePlatform)
{
case Device.iOS:
if (!File.Exists(Data.GetPath()))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Fehler", "Datenbank konnte nicht erstellt werden !", "OK");
}
}
break;
case Device.Android:
if (!File.Exists(Data.GetPath()))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Fehler", "Datenbank konnte nicht erstellt werden !", "OK");
}
}
break;
}
This does not gave me exception.
I get this exception:
private void Starten()
{
DataHelper.Database db = new DataHelper.Database();
try
{
List<Vokabeln> myvokabel = db.SelectTableVokabeln(anzahlVokabel).ToList();
frage.Clear();
antwort.Clear();
info1.Clear();
info2.Clear();
belohnung.Clear();
int test = myvokabel.Count();
foreach (var item in myvokabel)
{
if (richtung == 1)
{
frage.Add(item.Deutsch);
antwort.Add(item.Fremdsprache);
}
else
{
frage.Add(item.Fremdsprache);
antwort.Add(item.Deutsch);
info1.Add(item.Info1);
info2.Add(item.Info2);
}
}
List<Belohnungen> mybelohnung = db.SelectTableBelohnungen().ToList();
foreach (var bel in mybelohnung)
{
belohnung.Add(bel.Belohnung);
}
//DisplayAlert("Info", "Vokabeln und Belohnungen wurden geladen!", "OK");
}
catch (Exception)
{
//Log.Info("interner Fehler!", ex.Message);
DisplayAlert("Fehler", "Es ist ein Fehler aufgetreten", "OK");
}
}
Database.cs
public List<Vokabeln> SelectTableVokabeln(int anzahl)
{
try
{
var connection = new SQLiteConnection(dbpath);
var abfrage = connection.Query<Vokabeln>(string.Format("SELECT ID, Fremdsprache, Deutsch, Info1, Info2 FROM Vokabeln ORDER BY RANDOM() LIMIT {0}", anzahl));
//return connection.Table<Vokabeln>().ToList();
return abfrage;
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return null;
}
}
public List<Belohnungen> SelectTableBelohnungen()
{
try
{
var connection = new SQLiteConnection(dbpath);
return connection.Table<Belohnungen>().ToList();
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return null;
}
}
Any help?
Thank you.
I remember having had similar issues when trying to handle the file in shared code.
Strangely enough, creating an interface in my shared code with a native implementation on both iOS and Android resolved the issue.
Here is my code to retrieve the connection from within my iOS project in a native implementation of an interface from the shared project called IFileService:
public SQLite.SQLiteConnection GetDbConnection()
{
try
{
string sqliteFilename = "MyAppDb.db3";
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + sqliteFilename);
SQLiteConnection conn = new SQLite.SQLiteConnection(path, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.NoMutex);
return conn;
}
catch (Exception ex)
{
Logger.Fatal(ex, "An exception occurred at GetConnection");
Logger.Trace("Stack Trace: {0}", ex.StackTrace);
}
return null;
}
Also I would suggest that you don't access your connection the way you are doing it right now, as
var connection = new SQLiteConnection(dbpath);
will keep your connection open, which will most probably cause problems, if you want to use another connection.
In order to ensure that your connection is properly closed, I would highly recommend to manage it in a using block:
using(SQLiteConnection connection = iFileService.GetDbConnection())
{
connection.CreateTable<Belohnungen>();
connection.CreateTable<Vokabeln>();
connection.CreateTable<EigeneVokabel>();
}
This way the connection will be properly closed and disposed when your database access is finished. Also ensure that you always access your database connections that way whenever you get or store data in SQLite.
P.S.: if you are using a newer version of sqlite, you might need to construct your database with
SQLiteConnection connection = new SQLiteConnection(dbpath);
instead of the way I am creating it.
I am new to programming. I want to write multiple if else conditions using best practices. Here is my code.
public class HomeController : Controller
{
//Creating object of Result class
Result result = new Result();
// GET: Home
public async Task<ActionResult> Index(string key, string value)
{
DBConnection dbConnection = new DBConnection();
dbConnection.MakeConnection();
try
{
dbConnection.oracleCommand.CommandText = "QUERY";
OracleDataReader Reader = dbConnection.oracleCommand.ExecuteReader();
Reader.Read();
count = Reader.GetInt16(0);
for (int i = 0; i < count; i++)
{
//Updating records
dbConnection.oracleCommand.CommandText = "QUERY";
dbConnection.oracleCommand.ExecuteNonQuery();
dbConnection.oracleCommand.CommandText = "QUERY";
OracleDataReader Reader2 = dbConnection.oracleCommand.ExecuteReader();
while (Reader2.Read())
{
//Getting keyname and keyvalue
keyName = (Reader2.GetValue(1)).ToString();
keyValue = (Reader2.GetValue(2)).ToString();
}
dbConnection.oracleCommand.CommandText = "QUERY";
OracleDataReader Reader3 = dbConnection.oracleCommand.ExecuteReader();
while (Reader3.Read())
{
if ((!Reader3.GetValue(1).Equals(System.DBNull.Value)))
{
//Checking api type
if ((Reader3.GetValue(1).ToString() == ("REST")))
{
dbConnection.oracleCommand.CommandText = "QUERY";
OracleDataReader Reader4 = dbConnection.oracleCommand.ExecuteReader();
while (Reader4.Read())
{
if ((!Reader4.GetValue(0).Equals(System.DBNull.Value)))
{
//Getting url
url = Reader4.GetValue(1).ToString();
//Checking whether a get or a post
if ((Reader4.GetValue(0).ToString() == ("GET")))
{
RestCall restCall = new RestCall();
await restCall.RunAsync(keyName, keyValue);
}
}
else if ((Reader4.GetValue(0).ToString() == ("POST")))
{
//"Do a rest call for post method.";
RestCall restCall = new RestCall();
await restCall.RunAsync(keyName, keyValue);
}
else
{
//"Not a get or a post";
errorMessage = "Error";
}
}
}
}
else
{
//"A null value.";
errorMessageNull = "A null value.";
}
}
//Soap
if ((!Reader3.GetValue(1).Equals(System.DBNull.Value)))
{
if ((Reader3.GetValue(1).ToString() == ("SOAP")))
{
dbConnection.oracleCommand.CommandText = "QUERY";
OracleDataReader Reader4 = dbConnection.oracleCommand.ExecuteReader();
while (Reader4.Read())
{
if ((!Reader4.GetValue(0).Equals(System.DBNull.Value)))
{
//Getting url
url = Reader4.GetValue(1).ToString();
//Read function
if ((Reader4.GetValue(0).ToString() == ("READ")))
{
//SoapCall soapCall = new SoapCall();
//soapCall.DoSoapCall();
}
}
//Create function
else if ((Reader4.GetValue(0).ToString() == ("CREATE")))
{
//"Do a soap call for post method.";
}
else
{
//"Not a get or a post";
errorMessage = "Error";
}
}
}
else
{
//"Not a get or a post";
errorMessage = "Error";
}
}
else
{
//"Not a get or a post";
errorMessage = "Error";
}
Reader.Dispose();
Reader3.Dispose();
dbConnection.CloseConnection();
}
}
catch (Exception e)
{
exception = e.Message.ToString();
}
I want to execute these queries if they meet certain conditions. After that I want to do rest and soap calls. Is there any method to write this code without using multiple if else conditions. I mean a more readable way.
When there is ONLY ONE if statement inside an if statement (not even an else clause), then you can combine those two using && (and). For example,
if ((!Reader3.GetValue(1).Equals(System.DBNull.Value)))
{
//Checking api type
if ((Reader3.GetValue(1).ToString() == ("REST")))
{
could be combined as
if(!Reader3.GetValue(1).Equals(System.DBNull.Value) && Reader3.GetValue(1).ToString() == ("REST"))
And if you're checking different conditions of the same variable, you could use switch
switch(Reader3.GetValue(1).ToString())
{
case "REST":
//Do something.
break; //This is important!
case "SOAP":
//Do something!
break;
case "CREATE":
//I SAY DO SOMETHING!!!
break;
default: //This is the "else clause"
//Are you going to do something or not!?
break;
}
Other then that, multiple if statements are unavoidable!
Side note: Try not to use so many parenthesis!
Best regards! Good luck!
I'm doing a Workflow Activity that comes from a CRM process .
I have two inputs that are EntityReference and are being filled in the process.
Don't printing the trace that is after the try . Just enter the catch. And i donĂ½ know why.
My code is:
public class WK_DecorrerObjetivo : CodeActivity
{
//inputs dialog --- // input alvo
[Input("Alvo")]
[ReferenceTarget("xpto_alvo")]
public InArgument<EntityReference> alvo { get; set; }
//input actividade xpto_atividadeobjetivoid
[Input("Actividade Objetivo")]
[ReferenceTarget("xpto_atividadedeobjetivo")]
public InArgument<EntityReference> atividadeObjetivo { get; set; }
protected override void Execute(CodeActivityContext Execontext)
{
ITracingService _tracing;
IWorkflowContext context = null;
IOrganizationServiceFactory serviceFactory = null;
IOrganizationService service = null;
OrganizationServiceContext serviceContext = null;
try
{
#region Get Work Flow Context
context = Execontext.GetExtension<IWorkflowContext>();
serviceFactory = Execontext.GetExtension<IOrganizationServiceFactory>();
service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
serviceContext = new OrganizationServiceContext(service);
_tracing = Execontext.GetExtension<ITracingService>();
_tracing.Trace("inicio do try");
FetchExpression query = new FetchExpression(string.Format(Resources.GetTemplateAtividade, context.PrimaryEntityId));
// Obtain result from the query expression.
Entity new_alvo = (Entity)context.InputParameters["Target"];
var alvoGUID = ((EntityReference)new_alvo["xpto_alvo"]).Id;
Entity retrieveTemp = service.Retrieve("xpto_alvo", ((EntityReference)new_alvo["xpto_alvo"]).Id, new ColumnSet("xpto_utilizador", "xpto_conta", "xpto_contacto", "xpto_alvoid", "xpto_name", "createdon", "xpto_estado", "xpto_resultadoimportacao", "xpto_objetivoassociadoid", "xpto_alvo"));
OptionSetValue tipoAtividade = (OptionSetValue)retrieveTemp.Attributes["xpto_tipoatividade"];
switch (tipoAtividade.Value)
{
case 0:
_tracing.Trace("entrou no case 0 - compromisso");
break;
case 1:
_tracing.Trace("entrou no case 1 - phonecall");
break;
case 2:
_tracing.Trace("entrou no case 2 - task");
break;
default:
break;
}
//serviceContext.SaveChanges(); _tracing.Trace("savechanges");
}
catch (Exception ex)
{
string msgErro;
if (ex.InnerException != null)
{
msgErro = ex.InnerException.Message;
}
else
{
msgErro = ex.Message;
}
throw new InvalidPluginExecutionException(string.Format("Erro ao decorrer objetivo: {0}", msgErro));
}
}
}
Thank's.
The option set value you are trying to access "xpto_tipoatividade" isn't included in the list of columns to fetch in the retrieve request. Also always check if the attribute exists in the returned entity attribute collection and safe cast it or use an extension method to get a default value.
var retrieveTemp = service.Retrieve("xpto_alvo",
((EntityReference) new_alvo["xpto_alvo"]).Id,
new ColumnSet(
"xpto_tipoatividade", //<-- add xpto_tipoatividade to the list of attributes to fetch
"xpto_utilizador",
"xpto_conta",
"xpto_contacto",
"xpto_alvoid",
"xpto_name",
"createdon",
"xpto_estado",
"xpto_resultadoimportacao",
"xpto_objetivoassociadoid",
"xpto_alvo"));
var tipoAtividade = retrieveTemp.GetAttributeValue<OptionSetValue>("xpto_tipoatividade");
if (tipoAtividade == null)
{
_tracing.Trace("tipoAtividade is null, returning");
return;
}
switch (tipoAtividade.Value)
{
....
}
I have a Modbus TCP/IP to MODBUS RTU converter , which comes with a default IP of 192.168.0.1 . I need to develop a small c# Winform app to change this device's IP address to any desired IP address. How do I do that?.
You could do it with WMI (Windows Management Instrumentation).
First, you have to add the reference for System.Management to your Project.
Second, you need to find the NetworkInterface for your network connection by name:
using System.Net.NetworkInformation;
using System.Management;
public class NetworkManager
{
public static NetworkInterface GetNetworkInterface(string sName)
{
NetworkInterface NetInterface = null;
// Precondition
if (sName == "") return null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.Name == sName)
{
NetInterface = ni;
break;
}
}
return NetInterface;
}
Third, you have to create a ManagementObject for your NetworkInterface:
public static ManagementObject GetNetworkAdapterManagementObject(NetworkInterface NetInterface)
{
ManagementObject oMngObj = null;
// Precondition
if (NetInterface == null) return null;
string sNI = NetInterface.Id;
ManagementClass oMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection oMOC = oMC.GetInstances();
foreach (ManagementObject oMO in oMOC)
{
string sMO = oMO["SettingID"].ToString();
if (sMO == sNI)
{
// Found
oMngObj = oMO;
break;
}
}
return oMngObj;
}
Fours, you can set the ipadress with:
public static bool SetIPAdress(ManagementObject oMO, string[] saIPAdress, string[] saSubnetMask)
{
bool bErg = false;
try
{
// Precondition
if (oMO == null) return false;
if (saIPAdress == null) return false;
if (saSubnetMask == null) return false;
// Get ManagementBaseObject
ManagementBaseObject oNewIP = null;
oNewIP = oMO.GetMethodParameters("EnableStatic");
oNewIP["IPAddress"] = saIPAdress;
oNewIP["SubnetMask"] = saSubnetMask;
// Invoke
oMO.InvokeMethod("EnableStatic", oNewIP, null);
// Alles ok
bErg = true;
}
catch (Exception ex)
{
Console.WriteLine("SetIPAdress failed: " + ex.Message);
}
return bErg;
}
}
Now you can use it, for example in a button click event handler:
private void button1_Click(object sender, EventArgs e)
{
string sConn = "LAN-Verbindung";
NetworkInterface oNI = NetworkManager.GetNetworkInterface(sConn);
ManagementObject oMO = NetworkManager.GetNetworkAdapterManagementObject(oNI);
string sIPAdress = "192.168.1.1";
string sSubnetMask = "255.255.255.0";
string[] saIPAdress = {sIPAdress};
string[] saSubnetMask = {sSubnetMask};
if (NetworkManager.SetIPAdress(oMO, saIPAdress, saSubnetMask))
{
Console.WriteLine("Yes...");
}
}
Depending on the policies on your pc, may be you have to run the program as Administrator...
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
}
}