I use a VPN class in my program. But when I try to connect, it cause the following error:
the system could not find the phone book entry for this connection
Here is the connect method:
public void VPN_Connect(string VPN_Name, string VPN_ID, string VPN_PW)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Network\Connections\Pbk\rasphone.pbk";
AllUsersPhoneBook = new RasPhoneBook();
AllUsersPhoneBook.Open(path);
if (AllUsersPhoneBook.Entries.Contains(EntryName))
{
AllUsersPhoneBook.Entries[EntryName].PhoneNumber = VPN_Name;
AllUsersPhoneBook.Entries[EntryName].Update();
}
else
{
RasEntry entry = RasEntry.CreateVpnEntry(EntryName, VPN_Name, RasVpnStrategy.Default,
RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
entry.EncryptionType = RasEncryptionType.None;
AllUsersPhoneBook.Entries.Add(entry);
}
Dialer = new RasDialer();
Dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
this.Dialer.EntryName = EntryName;
this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.Dialer.Credentials = new NetworkCredential(VPN_ID, VPN_PW);
this.handle = this.Dialer.DialAsync();
VPN_Status = (int)status.Defalut;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
How can I solve this problem?
I'm also using windows 10 with latest update and DotRas last version.
Related
I use this code to get pending windows updates and also most of the informations of the update:
static List<PendingUpdate> GetPendingUpdates()
{
var updateSession = new UpdateSession();
var updateSearcher = updateSession.CreateUpdateSearcher();
updateSearcher.Online = false; //set to true if you want to search online
List<PendingUpdate> pendingUpdates = new List<PendingUpdate>();
try
{
var searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0");
if (searchResult.Updates.Count > 0)
{
Console.WriteLine("There are updates available for installation");
foreach (IUpdate windowsUpdate in searchResult.Updates)
{
PendingUpdate update = new PendingUpdate();
update.Title = windowsUpdate.Title;
update.Description = windowsUpdate.Description;
update.Downloaded = windowsUpdate.IsDownloaded;
update.Urls = new List<string>();
foreach (string url in windowsUpdate.MoreInfoUrls)
{
update.Urls.Add(url);
}
foreach (dynamic category in windowsUpdate.Categories)
{
update.Categories += category.Name + ", ";
}
pendingUpdates.Add(update);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
throw ex;
}
return pendingUpdates;
}
I also use this code to get to know if the computer currently needs a restart to finish installed updates:
static bool needsRestart()
{
ISystemInformation systemInfo = new SystemInformation();
return systemInfo.RebootRequired;
}
Now my question is, is it possible to get to know if an pending update needs a computer restart to finish? In the first code I get a IUpdate object but I dont see informations about a needed restart after installing this update. I there a way to get this information?
For the asynchronous installation I use something like this:
rebootRequired = false;
UpdateSession updateSession = new UpdateSession();
updateSession.ClientApplicationID = SusClientID;
IUpdateInstaller updatesInstaller = updateSession.CreateUpdateInstaller();
IInstallationJob job = updatesInstaller.BeginInstall(InstallProgressCallback, installComplete, installState);
// here is your installer code and the checking if the installation is completed
IInstallationProgress jobProgress = job.GetProgress();
for (int updateindex = 0; updateindex < updatesInstaller.Updates.Count; updateindex++)
{
IUpdateInstallationResult updateInstallResult = jobProgress.GetUpdateResult(updateindex);
rebootRequired |= updateInstallResult.RebootRequired;
}
if(rebootRequired)
{
// any of the updates need a reboot
}
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 have an OPC-DA Server that a SCADA software writes the variables and its values in it so I want to read them synchronously with using C#. I have already write my algorithm but I could not read the variables. The code creates a subscription or may be creates a group instance that writes the own variables and values in it but I do not want this. I need to just read the values from OPC server.
I have established a connection between OPC Server but I have not reach the variables which writes the variables into OPC Server.
Where is the problem, I cannot realise it. Could you suggest a solution about it?
My Code:
class OpcFunctions
{
Opc.Da.Server Server = null;
OpcCom.Factory Factory = new OpcCom.Factory();
Opc.Da.Item[] Items;
Opc.Da.Subscription Group;
Opc.IRequest myReq;
Opc.Da.WriteCompleteEventHandler WriteEventHandler;
Opc.Da.ReadCompleteEventHandler ReadEventHandler;
public void GetOpcServers(TreeView OpcServerTreeList, ListBox OpcConnectionUrlListBox)
{
try
{
OpcCom.ServerEnumerator myServerEnumerator = new OpcCom.ServerEnumerator();
Opc.Server[] Servers = myServerEnumerator.GetAvailableServers(Opc.Specification.COM_DA_20);
ListServers(Servers,OpcServerTreeList,OpcConnectionUrlListBox);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ListServers(Opc.Server[] OpcServerList , TreeView OpcServerTreeList, ListBox OpcConnectionUrlListBox)
{
try
{
OpcServerTreeList.Nodes.Clear();
OpcConnectionUrlListBox.Items.Clear();
foreach(Opc.Server myServer in OpcServerList)
{
TreeNode myTreeNode = new TreeNode(myServer.Name);
myTreeNode.Nodes.Add(myServer.Url.HostName + ":" + myServer.Url.Path + ":" + myServer.Url.Port);
myTreeNode.Nodes.Add(myServer.Url.ToString());
myTreeNode.Nodes.Add(myServer.IsConnected.ToString());
OpcServerTreeList.Nodes.Add(myTreeNode);
OpcConnectionUrlListBox.Items.Add(myServer.Url.ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public bool ConnectOpcServer(string OpcUrl)
{
Opc.URL Url = new Opc.URL(OpcUrl);
Server = new Opc.Da.Server(Factory, null);
try
{
Server.Connect(Url, new Opc.ConnectData(new System.Net.NetworkCredential()));
Opc.Da.SubscriptionState GroupState = new Opc.Da.SubscriptionState();
GroupState.Name = "Group1";
GroupState.Active = true;
Group = (Opc.Da.Subscription)Server.CreateSubscription(GroupState);
Group.DataChanged += new Opc.Da.DataChangedEventHandler(GroupDataChanged);
Items = Group.AddItems(Items);
ReadEventHandler = new Opc.Da.ReadCompleteEventHandler(ReadCompleteCallback);
Group.Read(Group.Items, 123, ReadCompleteCallback, out myReq);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
void GroupDataChanged(object subscriptionHandle, object requestHandle, Opc.Da.ItemValueResult[] values)
{
uint order = 1;
foreach (Opc.Da.ItemValueResult chitem in values)
{
myWriteLogList(order, chitem.Timestamp, chitem.ItemName, chitem.Value.ToString(), chitem.Quality.ToString());
++order;
}
}
void myWriteLogList(uint order, DateTime timestamp, string name, string value, string signalquality)
{
SettingsUI.OpcExplorer.dataGridViewOpcExplorer.BeginInvoke((MethodInvoker)delegate
{
SettingsUI.OpcExplorer.dataGridViewOpcExplorer.Rows.Add(null,order,timestamp,name,value,signalquality);
});
}
void ReadCompleteCallback(object clientHandle, Opc.Da.ItemValueResult[] results)
{
uint order = 1;
foreach (Opc.Da.ItemValueResult readResult in results)
{
myWriteLogList(order, readResult.Timestamp, readResult.ItemName, readResult.Value.ToString(), readResult.Quality.ToString());
++order;
}
}
}
Your 'Items' is empty!
sample:
Opc.Da.Item[] items = new Opc.Da.Item[1];
items[0] = new Opc.Da.Item();
items[0].ItemName = "PlcGroup.Items.value";
Try read from server...
ADD ITEMS AND READ
var result=Server.read(items);
For(i=0;i<result.length;i++) { Console.writeln(result[i].value); }
I am using a service reference which connects to internet and I want to show message in a message box if ever the connection fails. How will I call message box in the member function of the class which has void return type? This is the member function of the class:
public void ReverseGeocodePoint()
{
try{
string results = "";
string key = "abc";
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = key;
// Set the point to use to find a matching address
GeocodeService.Location point = new GeocodeService.Location();
point.Latitude = latitude;
point.Longitude = longitude;
reverseGeocodeRequest.Location = point;
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
//This will connect to the server
GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = geocodeResponse.Results[0].DisplayName;
else
results = "No Results found";
address = results;
}} catch{ //here I want to show a msgbox but the problem is, this is not the form class}
Don't catch the exception in that class if there's nothing you can do about it there. Just let it bubble up and catch it where you can do something about it:
public class MyForm : Form
{
public void SomeMethod()
{
try
{
var sc = new ServiceClass();
sc.ReverseGeocodePoint();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
In ReverseGeocodePoint(), remove the try/catch statements.
I have a windows application that write with c# 4. in this windows application i get user name, password, server IP and etc from user and create a oracle connection string from this inputs and test connect to database by this code:
private OperationStatus CheckConnectToOracleDatabase(string connectionString)
{
var oracleConnection = new OracleConnection();
try
{
oracleConnection.ConnectionString = connectionString;
oracleConnection.Open();
oracleConnection.Close();
return new OperationStatus { Status = true };
}
catch (OracleException ex)
{
return new OperationStatus { Status = false, ExceptionMessage = ex.Message };
}
catch (Exception ex)
{
return new OperationStatus { Status = false, ExceptionMessage = ex.Message };
}
finally
{
if (oracleConnection.State != ConnectionState.Closed)
oracleConnection.Close();
}
}
In my platform everything is OK and test is successful, but in the platform of customer and error was happened, this error was shown in below picture:
my platform is win server 2003, and platform of customer is win 7 32bit.