Disconnecting VPN in C# using DOTRAS - c#

I'm making a VPN connection using DOTRAS in C# by the click of a button, using the following method.
string VpnName = "Test1";
string Destination = "191.20.0.21";
string PresharedKey = "myKey";
RasPhoneBook PhoneBook = new RasPhoneBook();
PhoneBook.Open();
RasEntry VpnEntry = RasEntry.CreateVpnEntry(VpnName, Destination, DotRas.RasVpnStrategy.L2tpOnly, DotRas.RasDevice.Create(VpnName, DotRas.RasDeviceType.Vpn));
VpnEntry.Options.UsePreSharedKey = true;
VpnEntry.Options.UseLogOnCredentials = true;
VpnEntry.Options.RequirePap = true;
VpnEntry.Options.RequireMSChap = false;
VpnEntry.Options.RequireMSChap2 = false;
PhoneBook.Entries.Add(VpnEntry);
VpnEntry.UpdateCredentials(RasPreSharedKey.Client, PresharedKey);
Console.WriteLine("VPN connected successfully");
The VPN connects successfully.
I need to disconnect it now (Something other than simply removing it).
How will that be possible?

here:
var conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == "Test1").FirstOrDefault();
if (conn!=null)
{
conn.HangUp();
}

Related

System.TimeoutException: 'A timeout occurred after 30000ms' Issue

When I run the section of my project in C# nothing happens for about 30 seconds and it sends that error message in the title above, I am currently using .NET 5 Framework, the latest mongo drivers and my own Mongo Host (I tried Mongo atlas and it didnt work either). I have no clue as to why this doesnt work and was wondering if anyone knew why.
MongoClientSettings settings = new MongoClientSettings();
settings.ConnectTimeout = new TimeSpan(1000);
settings.WaitQueueTimeout = new TimeSpan(0, 2, 0);
settings.MinConnectionPoolSize = 1;
settings.MaxConnectionPoolSize = 25;
settings.Server = new MongoServerAddress("139.99.197.10");
Console.WriteLine(" connected");
MongoClient client = new MongoClient(settings);
database = client.GetDatabase(name);
public static bool DoesUserExist(String paramLicense)
{
List<Profile> records = GetMongo().Load<Profile>("Users");
bool correctCredentials = false;
foreach (var record in records)
{
if (record.licenseKey.Equals(paramLicense, StringComparison.InvariantCultureIgnoreCase))
{
correctCredentials = true;
break;
}
}
if (correctCredentials) {
return true;
}
return false;
}

c#: Dial a modem using dotras

im using huawei e359
Hello im creating a simple program. where my code will connect the 3g modem to the internet. because a part of my program need to access the internet.
i did some search how to do this using c#
this is my code for adding entry
string deviceName = null;
path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
using (RasPhoneBook pbk = new RasPhoneBook())
{
pbk.Open(path);
foreach (var item in RasDevice.GetDevices())
{
if (item.DeviceType.ToString().ToLower() == "modem")
{
deviceName = item.Name;
}
}
RasDevice device = RasDevice.GetDevices().Where(o => o.Name == deviceName && o.DeviceType == RasDeviceType.Modem).First();
if (!RasEntry.Exists("Your Entry", path))
{
RasEntry entry = RasEntry.CreateDialUpEntry("Your Entry", "+00000000000", device);
pbk.Entries.Add(entry);
}
}
and this is the code for dialing the device
using (RasDialer dialer = new RasDialer())
{
dialer.EntryName = "Your Entry";
dialer.PhoneBookPath = path;
dialer.AllowUseStoredCredentials = true;
dialer.Dial();
}
this is the error, it prompts when i dial the device
The remote computer did not respond. To make sure that the server can be reached, ping the remote computer.

How to get connected web site ip adress from browser?

im trying to detect which website user connected to..
I tried to get tcp connections and i parsed them for example i tried to detect facebook. But when i logout and close facebook its still displaying 31.13.93.3 (ip of facebook)
Here is my codes..
public partial class Form1 : Form
{
static string faceIP = "31.13.93.3";
static string _targetIP,_targetPORT,_connectedWebSiteIP,_connectedWebSitePORT = string.Empty;
static string[] splitted = null;
public Form1()
{
/* 127.0.0.1:5037:127.0.0.1:49569
* First = 127.0.0.1
* Second = 5037
* Third = 127.0.01
* Fourth = 49569
*/
InitializeComponent();
this.Name = "Active Tcp Connections";
if (findFacebookIP())
{
MessageBox.Show("You opened or connected to facebook page!");
}
}
public static bool findFacebookIP(){
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
foreach (TcpConnectionInformation c in connections)
{
string tcpCon = string.Format("{0}:{1}", c.LocalEndPoint.ToString(), c.RemoteEndPoint.ToString());
splitted = tcpCon.Split(':');
_targetIP = splitted[0]; // Main Machine ip adress / local ip address (First)
_targetPORT = splitted[1]; // Main machine port number (Second)
_connectedWebSiteIP = splitted[2]; // (Third)
_connectedWebSitePORT = splitted[3]; // (Fourth)
if (_connectedWebSiteIP == faceIP)
{
return true;
}
}
return false;
}
// face ip = 31.13.93.3
}
Also im need to run it background all time beacuse this method is working for just opening.. you can see i wrote it in Form1() constructor method.
Thank you for your help.
Check using TcpState:
foreach (TcpConnectionInformation c in connections)
{
//------------rest of your code
if(c.State == TcpState.Closed)
return false;
//------------rest of your code
}
And for running in background use BackgroundWorker.

Perforce Api - How to command "get revision [changelist number]"

I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.
SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'
I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}
The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"

SQL Server Management Objects

Am getting the same error on the code below using either trusted or SQL logins:
VS2010, Console app .NET4, Win XP. SQL2005 Full.
Bombs on the transfer.TransferData
ERROR : errorCode=-1073548784 description=Executing the query ""
failed with the following error: "Retrieving the COM class factory for
component with CLSID {19E353EF-DAF4-45D8-9A04-FB7F7798DCA7} failed due
to the following error: 80040154.". Possible failure reasons: Problems
with the query, "ResultSet" property not set correctly, parameters not
set correctly, or connection not established correctly.
this feels like security. Any thoughts would be awesome!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Collections.Specialized;
using System.IO;
using System.Configuration;
namespace GenerateScripts
{
class Program
{
static void Main(string[] args)
{
ServerConnection sourceConnection = new ServerConnection("localhost");
Server sourceServer = new Server(sourceConnection);
//sourceServer.ConnectionContext.LoginSecure = false;
//sourceServer.ConnectionContext.Login = "3tier";
//sourceServer.ConnectionContext.Password = "3tier";
Database sourceDatabase = sourceServer.Databases["3tier"];
// destination
ServerConnection destinationConnection = new ServerConnection("localhost");
Server destinationServer = new Server(destinationConnection);
//destinationServer.ConnectionContext.LoginSecure = false;
//destinationServer.ConnectionContext.Login = "3tier2";
//destinationServer.ConnectionContext.Password = "3tier2";
Database destinationDatabase = destinationServer.Databases["3tier2"];
Transfer transfer = new Transfer(sourceDatabase);
transfer.CopyAllObjects = false;
transfer.DropDestinationObjectsFirst = false;
transfer.UseDestinationTransaction = true;
transfer.CopyAllDefaults = true;
transfer.Options.Indexes = true;
transfer.Options.DriAll = true;
transfer.CopyAllDefaults = true;
transfer.Options.AnsiFile = true;
transfer.Options.SchemaQualify = true;
transfer.Options.WithDependencies = false;
transfer.CreateTargetDatabase = false;
transfer.CopySchema = true;
transfer.CopyData = true;
transfer.DestinationServer = "localhost";
transfer.DestinationDatabase = "3tier2";
transfer.DestinationLoginSecure = false;
transfer.DestinationLogin = "3tier2";
transfer.DestinationPassword = "3tier2";
transfer.Options.IncludeIfNotExists = true;
transfer.TransferData();
I don't know if this is the same case but i had a similar problem and it was related to SQLTaskConnectionOleDb class registration corruption,
i've solved it by running
regsvr32 "%ProgramFiles%\Microsoft SQL Server\90\DTS\Binn\SQLTaskConnections.dll"
in command prompt.

Categories

Resources