Add link to rich text box that starts a process (RDP) - c#

I'm trying to add a clickable link to a rich text box that says something like "Start RDP" so when a user clicks on it, it will start windows remote desktop and use put the machine name in the box for you. Here is my code so far, It searchs Active Directory for a computer name that the user enters, pings the machine and if it is online, show its status in another textbox.
private void btnAd_Click(object sender, EventArgs e)
{
var adsb = new StringBuilder();
var mssb = new StringBuilder();
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://dc=Domain.org";
try
{
string wildcard = "*";
string adser = wildcard + txtAd.Text + wildcard;
DirectorySearcher ser = new DirectorySearcher();
ser.SizeLimit = System.Int32.MaxValue;
ser.PageSize = System.Int32.MaxValue;
ser.Filter = "(&(ObjectCategory=computer)(name=" + adser + "))"; //Only allows Computers to be returned in results.
SearchResultCollection results = ser.FindAll();
if (String.IsNullOrEmpty(txtcomputers.Text)) //if the textbox is empty, write ad search results to textbox
{
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName,..
adsb.AppendLine(temp[0].Substring(10));//returns everything after LDAP://CN= until end of temp[0].
if (Ping(temp[0].Substring(10)))
{
mssb.AppendLine(temp[0].Substring(10) + "....Online");
}
else
{
mssb.AppendLine(temp[0].Substring(10) + "....Offline");
}
}
rtbComputerstatus.Text = mssb.ToString();
txtcomputers.Text = adsb.ToString();
}
else //Add items to textbox if there are already items present.
{
txtcomputers.AppendText(Environment.NewLine);
rtbComputerstatus.AppendText(Environment.NewLine);
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(',');
adsb.AppendLine(temp[0].Substring(10));
txtcomputers.AppendText(adsb.ToString());
if (Ping(temp[0].Substring(10)))
{
mssb.AppendLine(temp[0].Substring(10) + "....Online......");
}
else
{
mssb.AppendLine(temp[0].Substring(10) + "....Offline");
}
rtbComputerstatus.AppendText(mssb.ToString());
}
}
//trims spaces
this.txtcomputers.Text = this.txtcomputers.Text.Trim();
txtcomputers.CharacterCasing = CharacterCasing.Upper;
//color items
HighlightPhrase(rtbComputerstatus, "Online",Color.Green);
HighlightPhrase(rtbComputerstatus, "Offline", Color.Red);
HighlightPhrase(rtbComputerstatus, "RDP", Color.Blue);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
de.Dispose();//Clean up resources
}
}
// color method
static void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
//ping method
public static bool Ping(string hostName)
{
bool result = false;
try
{
Ping pingSender = new Ping(); PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(hostName, timeout, buffer, options); if (reply.Status == IPStatus.Success)
{
result = true;
}
else
{
result = false;
}
}
catch
{
result = false;
}
return result;
}
Any suggestions ? I've tried a few different things but can't seem to get it working.
Thanks !

There is an article published on Codeproject, describing the solution that you are looking for: link
Hope this will help. Rgds, AB

Related

Problems uploading a ZK Face String Template to a device

Device Model: SpeedFace-H5L
SDK Im using: StandAlone SDK-Ver6.3.1.34
Conected via TCP/IP
When i use GetUserFaceStr I get all the templates but when I try to do SetUserFaceStr the operation fails and returns a -103 Error Code, In the documentacion it says that this error means "-103 device send back error of face version error"
The Fp version code is
axCZKEM1.GetSysOption(GetMachineNumber(), "ZKFaceVersion", out strTemp);
Throws me a 58 Face Algorith
This is the code for getting and setting faces
public int sta_SetAllUserFaceInfo(ListBox lblOutputInfo, ProgressBar prgSta, ListView lvUserInfo)
{
if (GetConnectState() == false)
{
lblOutputInfo.Items.Add("*Please connect first!");
return -1024;
}
if (lvUserInfo.Items.Count == 0)
{
lblOutputInfo.Items.Add("*There is no data can upload!");
return -1023;
}
string sEnrollNumber = "";
string sEnabled = "";
bool bEnabled = false;
string sName = "";
string sPassword = "";
int iPrivilege = 0;
string sTmpData = "";
int iLength = 0;
int iFaceIndex = 50;
int num = 0;
axCZKEM1.EnableDevice(iMachineNumber, false);
for (int i = 0; i < lvUserInfo.Items.Count; i++)
{
sEnrollNumber = lvUserInfo.Items[i].SubItems[0].Text;
sEnabled = lvUserInfo.Items[i].SubItems[1].Text;
if (sEnabled == "true")
{
bEnabled = true;
}
else
{
bEnabled = false;
}
sName = lvUserInfo.Items[i].SubItems[2].Text;
sPassword = lvUserInfo.Items[i].SubItems[3].Text;
iPrivilege = Convert.ToInt32(lvUserInfo.Items[i].SubItems[4].Text);
iLength = Convert.ToInt32(lvUserInfo.Items[i].SubItems[5].Text);
sTmpData = lvUserInfo.Items[i].SubItems[6].Text;
if (axCZKEM1.SSR_SetUserInfo(iMachineNumber, sEnrollNumber, sName, sPassword, iPrivilege, bEnabled))//upload user information to the device
{
if(axCZKEM1.SetUserFaceStr(iMachineNumber, sEnrollNumber, iFaceIndex, sTmpData, iLength)) //upload face templates information to the device
{
num++;
prgSta.Value = num % 100;
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
lblOutputInfo.Items.Add("*Operation failed,ErrorCode=!" + idwErrorCode.ToString());
axCZKEM1.EnableDevice(iMachineNumber, true);
}
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
lblOutputInfo.Items.Add("*Operation failed,ErrorCode=!" + idwErrorCode.ToString());
axCZKEM1.EnableDevice(iMachineNumber, true);
return -1022;
}
}
prgSta.Value = 100;
axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
axCZKEM1.EnableDevice(iMachineNumber, true);
lblOutputInfo.Items.Add("Upload face successfully");
return 1;
}
It is a ZKteco error in SDK not compatible with device firmware. I faced same issue. It also happens with SpeedFace V4L

How to enable/Disabe an USB device specific with C#

I try to enable/disable a specific USB device with C#.
I am a very confused because i found a lot informations, and they all contradict each other.
My first question is, the "setupapi.dll" just works in 32 bit plataform?
Anyway, my program return false when calling:
bool rstl2 = DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
My source code:
public bool HW_Set_State( bool bEnable)
{
try
{
Guid myGUID = new Guid("{745a17a0-74d3-11d0-b6fe-00a0c90f57da}");
IntPtr hDevInfo = DeviceHelper.SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, DeviceHelper.DIGCF_ALLCLASSES | DeviceHelper.DIGCF_PRESENT);
try
{
if (hDevInfo.ToInt32() == DeviceHelper.INVALID_HANDLE_VALUE)
return false;
} catch { }
if (hDevInfo.ToInt64() == DeviceHelper.INVALID_HANDLE_VALUE)
return false;
DeviceHelper.SP_DEVINFO_DATA DeviceInfoData;
DeviceInfoData = new DeviceHelper.SP_DEVINFO_DATA();
DeviceInfoData.cbSize = 28;
DeviceInfoData.devInst = 0;
DeviceInfoData.classGuid = myGUID;
DeviceInfoData.reserved = 0;
UInt32 i;
StringBuilder DeviceName = new StringBuilder("");
DeviceName.Capacity = DeviceHelper.MAX_DEV_LEN;
for (i = 0; DeviceHelper.SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++)
{
if(DeviceHelper.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, DeviceHelper.SPDRP_DEVICEDESC, 0, DeviceName, DeviceHelper.MAX_DEV_LEN, IntPtr.Zero)){
if (DeviceName.ToString().Contains("USB Input Device"))
{
if (DeviceInfoData.classGuid.ToString().Contains("745a17a0-74d3-11d0-b6fe-00a0c90f57da"))
{
ChangeDeviceState(hDevInfo, DeviceInfoData, bEnable);
}
}
}
}
DeviceHelper.SetupDiDestroyDeviceInfoList(hDevInfo);
}
catch (Exception ex)
{
return false;
}
return true;
}
}
private bool ChangeDeviceState(IntPtr hDevInfo, DeviceHelper.SP_DEVINFO_DATA devInfoData, bool bEnable)
{
try
{
int szOfPcp;
IntPtr ptrToPcp;
int szDevInfoData;
IntPtr ptrToDevInfoData;
DeviceHelper.SP_PROPCHANGE_PARAMS pcp = new DeviceHelper.SP_PROPCHANGE_PARAMS();
if (bEnable)
{
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_ENABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_GLOBAL;
pcp.HwProfile = 0;
szOfPcp = Marshal.SizeOf(pcp);
ptrToPcp = Marshal.AllocHGlobal(szOfPcp);
Marshal.StructureToPtr(pcp, ptrToPcp, true);
szDevInfoData = Marshal.SizeOf(devInfoData);
ptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData);
if (DeviceHelper.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(DeviceHelper.SP_PROPCHANGE_PARAMS))))
{
DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
}
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_ENABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_CONFIGSPECIFIC;
pcp.HwProfile = 0;
}
else
{
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_DISABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_CONFIGSPECIFIC;
pcp.HwProfile = 0;
}
szOfPcp = Marshal.SizeOf(pcp);
ptrToPcp = Marshal.AllocHGlobal(szOfPcp);
Marshal.StructureToPtr(pcp, ptrToPcp, true);
szDevInfoData = Marshal.SizeOf(devInfoData);
ptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData);
Marshal.StructureToPtr(devInfoData, ptrToDevInfoData, true);
bool rslt1 = DeviceHelper.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(DeviceHelper.SP_PROPCHANGE_PARAMS)));
bool rstl2 = DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
if ((!rslt1) || (!rstl2))
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
return false;
}
}
If I wrote something wrong, I'm sorry. Im from Brazil :)
If you also prefer using WMI you can do it like this:
*Install Management NuGet
using System.Management;
*Add string with your device name/guid/deviceid.etc
public string DeviceName = "YourDeviceName";
*For Enable
ManagementObjectSearcher myDevices = new ManagementObjectSearcher("root\\CIMV2", #"SELECT * FROM Win32_PnPEntity where Name Like " + '"' + DeviceName + '"');
foreach (ManagementObject item in myDevices.Get())
{
ManagementBaseObject UWFEnable = item.InvokeMethod("Enable", null, null);
}
*For Disable
ManagementObjectSearcher myDevices = new ManagementObjectSearcher("root\\CIMV2", #"SELECT * FROM Win32_PnPEntity where Name Like " + '"' + DeviceName + '"');
foreach (ManagementObject item in smyDevices.Get())
{
ManagementBaseObject inParams = item.InvokeMethod("Disable", null, null);
}
#Edit:
You can also use devcon.exe from the Microsoft website.
I was able to achieve this by making use of the DevCon utility provided by Microsoft. The DevCon utility can be invoked by command line or with Process.Start(...).
I followed the example for disabling a device based on the device instance ID. Note that the ID argument begins with the "#" character. When I initially ran the command, I didn't notice this and it didn't enable/disable my device.
https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/devcon-examples?source=recommendations#example-31-disable-devices-by-device-instance-id
devcon disable "#USB\VID_045E&PID_0039\5&29F428A4&0&2"

updating data via sockets in c#

i've got a server with all the logic of a four on row game of which i would like to display the state after each player turn i've got several class and i would like to send the game with the position played each turn,i succeded to send the first move to the client but the client just shoot down after that. the client and the server are both console application
in my main server side i've got this
var game = Game.CreateConsoleGame(DifficultyLevel.Hard, ActivePlayer.User, false);
game.Play();
Console.ReadKey();
those line are going to use other class Board,Game,Iodevice,judge and player
making all the logic of the game
in class player i've got this
and once i've got the position played ,i draw a String Builder
with this method
public static StringBuilder DrawStringBuilder(int nk)
{
cells = new CellStates[6, 7];
var builder = new StringBuilder();
var header = " 0 1 2 3 4 5 6";
var divisor = "-------------------------------------------------------------------";
builder.AppendLine(header);
builder.AppendLine(divisor);
int p = 0;
for (int i = 0; i < cells.GetLength(0); i++)
{
for (int j = 0; j < cells.GetLength(1); j++)
{
int counter1 = 0;
int counter2 = 1;
cells[5, nk] = CellStates.Player;
//cells[5, 0] = CellStates.User;
var str = cells[i, j] == CellStates.Empty ? "| ······· " : (cells[i, j] == CellStates.User ? "| 0 " : "| x ");
builder.Append(str);
counter1 = counter1 + 2;
counter2++;
}
builder.Append('|');
builder.AppendLine();
builder.AppendLine(divisor);
}
return builder;
}
i am just using this method
to send it to the client
public static void SendingPacket(StringBuilder packet)
{
IPAddress ipLocal;
IPEndPoint ipeLocal;
TcpListener List;
TcpClient tc = null;
NetworkStream ns = null;
string s2;
int n = 0;
try
{
ipLocal = IPAddress.Parse("127.0.0.1");
ipeLocal = new IPEndPoint(ipLocal, 8888);
List = new TcpListener(ipeLocal);
List.Start();
tc = List.AcceptTcpClient();
ns = tc.GetStream();
StreamReader reader = new StreamReader(ns);
StreamWriter write = new StreamWriter(ns);
string response = null;
//Console.WriteLine(response);
response = reader.ReadLine();
Console.WriteLine(response);
Thread.Sleep(200);
write.WriteLine(packet);
write.Flush();
n++;
Console.WriteLine("j'envoie");
Console.WriteLine("de player");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if ((tc != null) && (ns != null))
{
tc.Close();
ns.Close();
}
}
}
for the client side i've got receveingdata method that i call in my main
why i can't receive at least twice my stringbuilder sent i'am getting an error
atthe second turn saying unable to read data from the transport connection an existing connection was closed by the distant host
public static void RecevingData()
{
IPAddress ipServeur;
IPEndPoint ipeServeur;
TcpClient tc = null;
NetworkStream ns = null;
try
{
ipServeur = IPAddress.Parse("127.0.0.1");
ipeServeur = new IPEndPoint(ipServeur, 8888);
tc = new TcpClient();
tc.Connect(ipeServeur);
ns = tc.GetStream();
string s = null;
string s1 = "ping";
string reponse = null;
StreamWriter write = new StreamWriter(ns);
StreamReader reader = new StreamReader(ns);
//Console.WriteLine("un string svp");
//s = Console.ReadLine();
write.Flush();
write.WriteLine(s1);
write.Flush();
do
{
reponse = reader.ReadLine();
Console.WriteLine(reponse);
} while (true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
i am a beginner so maybe my question is too stupid but i am just driven by getting better so please try to be indulgent,my idea was to send the stringbuilder the same way after each player's turn

Issue with +CDS AT COMMAND

I'm issue when I get +CDS in AT COMMAND throught c# using SerialPort, any times I get this +CDS truncated, example:
+CDS: 25
0002970C91555868047414212181414094882121814140948830
Why I've this problem, why any times work nice?
I'm starting SerialPort:
public PortCOM(string porta)
: base(porta, 115200, Parity.None, 8, StopBits.One)
{
this.StatusPort = StatusPorta.Ready;
this.DiscardNull = true;
this.ReadTimeout = 21000;
this.RtsEnable = true;
this.DtrEnable = true;
this.ReceivedBytesThreshold = 9;
this.NewLine = "\r\n";
this.ReadBufferSize = 1024;
}
public static void TestPort()
{
var p = new PortCom("COM12");
if (!p.IsOpen)
p.Open();
p.StatusPort = StatusPorta.Ready;
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceivedSample);
p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);
p.ErrorReceived += new SerialErrorReceivedEventHandler(p_ErrorReceived);
p.Disposed += new EventHandler((obj, porta) =>
{
Console.WriteLine(((PortaCOM)obj).ToString());
});
if (Console.ReadKey().Key == ConsoleKey.B)
{
p.Close();
p.Dispose();
}
}
static void p_DataReceivedSample(object sender, SerialDataReceivedEventArgs e)
{
var p = (PortaCOM)sender;
try
{
Console.WriteLine(p.ReadExisting());
var sb = new StringBuilder();
sb.Append(p.ReadExisting());
int y = sb.ToString().IndexOf("\r\n");
var stop = Stopwatch.StartNew();
stop.Start();
while (y == -1)
{
sb.Append(p.ReadExisting());
y = sb.ToString().IndexOf("\r\n");
if (stop.Elapsed.TotalSeconds > 10)
break;
}
stop.Stop();
var _retorno = sb.ToString();
var cmt = regCMT.Match(_retorno);
var succ = regSucess.Match(_retorno);
var report = regStatusReport.Match(_retorno);
var erro = regError.Match(_retorno);
#region Resposta
if (cmt.Success)
{
var smss = new SMS();
var source = cmt.Groups[3].Value;
SMS.Fetch(smss, ref source);
var resposta = new Resposta()
{
Mensagem = smss.Message,
Data = smss.ServiceCenterTimeStamp,
Sender = smss.PhoneNumber,
Operadora = p.OperadoraName.NomeOperadora.ToString()
};
GravaResposta().ToAsync(Scheduler.TaskPool).Invoke(p, cmt.Groups[3].Value);
p.IsError = false;
}
#endregion
#region StatusReport
if (report.Success)
{
RecebeReport(p, report.Groups[2].Value.Trim());
p.IsError = false;
}
#endregion
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
Please I really need help with it, I'm glad for any help!
+cds is alert for incoming message with message location on SIM memeory.
so here its seems in PDU mode data. and it is seems may be flash message content.
Convert the data PDU mode to Text mode to receive message.
review this ATSMS library

trouble comparing strings in wp7 application

Here is a sample of my code.
Here I recieve a string variable from another page.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string newparameter = this.NavigationContext.QueryString["search"];
weareusingxml();
displayResults(newparameter);
}
private void displayResults(string search)
{
bool flag = false;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
List<Person> data = (List<Person>)serializer.Deserialize(stream);
List<Result> results = new List<Result>();
for (int i = 0; i < data.Count; i++)
{
string temp1 = data[i].name.ToUpper();
string temp2 = "*" + search.ToUpper() + "*";
if (temp1 == temp2)
{
results.Add(new Result() {name = data[i].name, gender = data[i].gender, pronouciation = data[i].pronouciation, definition = data[i].definition, audio = data[i].audio });
flag = true;
}
}
this.listBox.ItemsSource = results;
}
catch
{
textBlock1.Text = "error loading page";
}
if(!flag)
{
textBlock1.Text = "no matching results";
}
}
Nothing is loaded into the list when the code is run, I just get the message "no matching results".
Looks like you are trying to do a contains search (my guess based on your addition of the * around the search string. You can remove the '*' and do a string.Contains match.
Try this.
string temp1 = data[i].name.ToUpper();
string temp2 = search.ToUpper()
if (temp1.Contains(temp2))
{
It looks like you are trying to check if one string contains another (ie substring match) and not if they are equal.
In C#, you do this like this:
haystack = "Applejuice box";
needle = "juice";
if (haystack.Contains(needle))
{
// Match
}
Or, in your case (and skip the * you added to the string temp2)
if (temp1.Contains(temp2))
{
// add them to the list
}
Have you checked to make sure data.Count > 0?

Categories

Resources