How we can change USB settings of connected device through c# - c#

I am working on an application where I am placing the json files at particular directory in connected android device. Android device has an application which used to read the data from json files and then files are deleted. I am using MediaDevices library to list and connect devices in WPF application.
public Form1()
{
InitializeComponent();
bindDevices();
}
private void bindDevices()
{
try
{
devices = MediaDevice.GetDevices();
var test = devices.Select(x => x).ToList();
List<deviceDetails> deviceNames = (from d in test
select new deviceDetails
{
deviceID = d.DeviceId,
deviceName = d.FriendlyName == "" ? d.Description : d.FriendlyName
}).ToList();
foreach (MediaDevice device in devices)
{
device.Connect();
lblBattery.Text = device.PowerLevel.ToString();
try
{
getDirectory(device);
}
catch (Exception ex)
{
}
finally
{
device.Disconnect();
}
}
comboBox1.ValueMember = "deviceID";
comboBox1.DisplayMember = "deviceName";
comboBox1.DataSource = deviceNames;
//var device = devices.FirstOrDefault().FriendlyName == "" ? devices.FirstOrDefault().Description : devices.FirstOrDefault().FriendlyName;
//label2.Text = device;
}
catch (Exception ex)
{
MessageBox.Show("Error : -" + ex.Message);
label2.Text = "Can not connect to device";
}
}
Above mentioned steps are working fine.
Problem: Sometimes, while device is connected through USB, if I check on file explorer at PC, it shows me json files but if I check in android device files were removed. If, I am trying to delete those files through PC then it show message files are locked. Once, I disconnect/connect the device again then files are removed from device directory.
How, I can reset the connectivity of device so connection will be reset through code.

Related

Listing Mapped Network Drives with WMI

i have an app written in c#, that creates a list of all network drives that are mapped.
I used WMI to achieve this, here is how i did it:
List < NetworkConnection > networkConnections = new List < NetworkConnection > ();
try {
var path = new ManagementPath();
path.NamespacePath = "\\ROOT\\CIMV2";
path.ClassName = "Win32_NetworkConnection"; //https://msdn.microsoft.com/en-us/library/aa394220(v=vs.85).aspx
var management = new ManagementClass(path);
foreach(ManagementObject obj in management.GetInstances()) {
NetworkConnection networkConnection = new NetworkConnection() {
LocalName = (string) obj.Properties["LocalName"].Value,
Name = (string) obj.Properties["Name"].Value,
RemotePath = (string) obj.Properties["RemotePath"].Value,
UserName = (string) obj.Properties["UserName"].Value,
IsPersistent = (bool) obj.Properties["Persistent"].Value,
ConnectionState = (string) obj.Properties["ConnectionState"].Value
};
networkConnections.Add(networkConnection);
}
} catch (Exception ex) {
log.Error($ "Failed to get network connections.", ex);
}
return networkConnections;
While this does work on my test clients W7 and W8 64 and 32 bit. It wont work on my W10 clients.
On W10 I just get an emtpy list back.
It looks like management.GetInstances() does not return anything. But why?
Any help is greatly appreciated! Thanks!

How can I solve VPN Connection Error in C#

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.

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.

Issue viewing all skinny traffic using pcap.net in a C# Winform application

I am using the latest version of pcap.net to capture network traffic on my local pc ethernet card. I am using the following code to capture all traffic associated with a specific mac address.
private void bwCapture_DoWork(object sender, DoWorkEventArgs e)
{
capture = true;
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
if (allDevices.Count == 0)
{
MessageBox.Show("No interfaces found!");
return;
}
if (capture)
{
// Print the list
for (int i = 0; i != allDevices.Count; ++i)
{
LivePacketDevice device = allDevices[i];
this.BeginInvoke((Action)delegate () { cmbNetworkDevice.Items.Add((i + 1) + ". " + device.Name); });
}
// Take the selected adapter
PacketDevice selectedDevice = allDevices[deviceSelected];
// Open the device
using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
50)) // read timeout
{
this.BeginInvoke((Action)delegate () { rtbCaptured.Text = "Listening on " + selectedDevice.Description + Environment.NewLine; });
// Retrieve the packets
Packet packet;
while (capture)
{
try
{
BerkeleyPacketFilter filter = communicator.CreateFilter("ether host <<MAC ADDRESS>> and tcp port 2000");
communicator.SetFilter(filter);
PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
switch (result)
{
case PacketCommunicatorReceiveResult.Timeout:
// Timeout elapsed
continue;
case PacketCommunicatorReceiveResult.Ok:
this.BeginInvoke((Action)delegate ()
{
IpV4Datagram ip = packet.Ethernet.IpV4;
TcpDatagram tcp = ip.Tcp;
if (tcp != null && ip != null)
{
string IPCheck = ip.Source.ToString();
int PortCheck = tcp.DestinationPort;
dgvIncomingPackets.Rows.Add(packet.Timestamp.ToString("MM-dd-yyyy hh:mm:ss"), packet.Length, tcp.SequenceNumber , ip.IpV4.Protocol, ip.Source, tcp.SourcePort, ip.Destination, tcp.DestinationPort);
rtbPacketDeconstruct.Text = WordWrap(ProcessString(packet.BytesSequenceToHexadecimalString()),47);
string convertThis = ProcessString(packet.BytesSequenceToHexadecimalString());
dgvIncomingPackets.FirstDisplayedScrollingRowIndex = dgvIncomingPackets.RowCount - 1;
}
else
{
rtbCaptured.Text += "Error : TCP Null Value" + Environment.NewLine;
}
});
break;
default:
throw new InvalidOperationException("The result " + result + " should never be reached here");
}
}
catch (Exception ex)
{
this.BeginInvoke((Action)delegate ()
{ rtbCaptured.Text += "Exception : " + ex; });
}
}
}
}
}
The code above works however it is not detecting all of the skinny events. When viewing the network traffic with WireShark I am able to see the condition changes in a Cisco 7960 IP Phone including off hook, lamp messages, displaynotification messages.
While these packets are registered in Wireshark on my PC they appear not to be captured using the code above.
My understanding is that skinny uses tcp ports 2000 and 49828 for communication between CUCM and the device. My code does see the TCP ACK and WHOAMI packets.The MAC address being monitored in the Cisco IP Phone. My PC is connected to this device through the built in hub on the device(This isn't the issue because WireShark is showing the events on my PC where my code is not)
What am I missing here. I am a novice to programming and learning on the fly here. (As such I am aware my code isn't the cleanest or well written)
Thanks,

FindAllPeersAsync() and StreamSocket.ConnectAsync() issue

I am trying to connect to a printer(by MAC address) and print. I am encountering several issues that I tried to overcome for hours with no success. I tried several different Methods:
Method 1: Using PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805F9B34FB}" works on first attempt to connect. When I try to reopen the connection after closing connection, it was not able to find any paired devices. When I exit application and rerun, I get the following exception: "Element not found. (Exception from HRRESULT:0x80070490) at socket.ConnectAsync()
//Search for devices based on service
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805F9B34FB}";
//bluetooth device to connect to
var m_bluetoothDevice;
//paired bluetooth device list
var m_pairedDevices = await PeerFinder.FindAllPeersAsync();
if (m_pairedDevices.Count > 0)
{
foreach (PeerInformation device in m_pairedDevices)
{
//Find the device with matching bluetooth mac address (eg. "00:AA:BB:CC:DD:EE")
String macAddr = device.HostName.RawName;
if (macAddr.Contains(m_bluetoothAddress.ToUpper()))
{
m_bluetoothDevice = device;
break;
}
}
}
//Device not paired
if (m_bluetoothDevice == null)
throw new Exception("Device was not paired with system.");
StreamSocket socket = new StreamSocket();
if (socket != null)
{
//Connect to device. Run this task synchronously
IAsyncAction taskConnect = socket.ConnectAsync(m_bluetoothDevice.HostName, m_bluetoothDevice.ServiceName);
taskConnect.AsTask().Wait();
if (taskConnect.ErrorCode != null)
{
throw (taskConnect.ErrorCode);
}
}
Method 2: Using PeerFinder.Alternative["Bluetooth:Paired" = "", I am able to connect once. After closing connection and reopening connection, I get the following Exception "Element not found. (Exception from HRRESULT:0x80070490) at socket.ConnectAsync().
//Search for devices based on service
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
//bluetooth device to connect to
var m_bluetoothDevice;
//paired bluetooth device list
var m_pairedDevices = await PeerFinder.FindAllPeersAsync();
if (m_pairedDevices.Count > 0)
{
foreach (PeerInformation device in m_pairedDevices)
{
//Find the device with matching bluetooth mac address (eg. "00:AA:BB:CC:DD:EE")
String macAddr = device.HostName.RawName;
if (macAddr.Contains(m_bluetoothAddress.ToUpper()))
{
m_bluetoothDevice = device;
break;
}
}
}
//Device not paired
if (m_bluetoothDevice == null)
throw new Exception("Device was not paired with system.");
StreamSocket socket = new StreamSocket();
if (socket != null)
{
//Connect to device. Run this task synchronously
IAsyncAction taskConnect = socket.ConnectAsync(m_bluetoothDevice.HostName, "{00001101-0000-1000-8000-00805F9B34FB}");
taskConnect.AsTask().Wait();
if (taskConnect.ErrorCode != null)
{
throw (taskConnect.ErrorCode);
}
}
Anyone experiencing the same issue? What am I doing wrong?
Thanks in advance

Categories

Resources