try catch issue - c#

what's a better way of doing the below try catch? Currently I have each WMI field in its own try catch statement.
I do not want to put the whole class into a massive try catch as I have issues with fields not displaying anything back (tried this and does not work well for what I am doing).
I have about 25 other WMI fields that I need to put in and am wondering if there is a simpler way of doing this?
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
catch (Exception)
{
lblSystemName.Text = "SystemName: WMI Error"; ;
}
try
{
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch (Exception)
{
lblType.Text = "Type: WMI Error";
}
}

You could use a helper method:
private static string GetMOValue(ManagementObject mo, string name)
{
try
{
object result = mo[name];
return result == null ? "" : result.ToString();
}
catch(Exception)
{
return "WMI Error";
}
}
...
lblSystemName.Text = GetMOValue(moDisk, "systemname");
lblType.Text = GetMOValue(moDisk, "MediaType");
Note you should probably catch a more specific exception (not sure what exceptions can be thrown by the ManagementObject indexer).

I think erro occur when there is no data avaialbe for the given column in datatable
if (moDisk.Columns.Contains("systemname"))
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
else
{
lblSystemName.Text = "SystemName: WMI Error";
}
Note : not sure this is datatable or not but you can code like this instead of catching exception for each value ... with the help of if ..else you can code this easily

I feel that using these many try catch is not good. If i were u i would have done in following method..if try catch really needed.
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
string current= string.Empty;
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
current = "SystemName";
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
current = "MediaType";
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch(Exception)
{
//print "error in" + current;
}
}

Related

Form without movement when filling in DataGridView

I use a DataGridView as a console for an application, I need to fill it out every second, I use the following code for this:
public class dgView
{
public static DataGridView DataConsole;
public static void addLinha(int tipo_acao, string acao, string extra, int tipo_extra)
{
// INSERE LINHA NO CONSOLE
try
{
if (DataConsole == null) return;
var idLinha = DataConsole.Rows.Add();
using (var linha = DataConsole.Rows[idLinha])
{
//await Task.Delay(300);
if (tipo_acao == 0)
{
linha.DefaultCellStyle.ForeColor = Color.Teal;
linha.Cells[3].Style.ForeColor = Color.Gray;
}
else if (tipo_acao == 1)
{
linha.DefaultCellStyle.ForeColor = Color.Yellow;
linha.Cells[3].Style.ForeColor = Color.Orange;
}
else
{
linha.DefaultCellStyle.ForeColor = Color.Red;
linha.Cells[3].Style.ForeColor = Color.Magenta;
}
linha.Cells["dg_data"].Value = DateTime.Now;
linha.Cells["dg_mapa"].Value = "" + Config.Mapa + "";
linha.Cells["dg_acao"].Value = "" + Config.rm.GetString("" + acao + "") + "";
if (tipo_extra == 0)
{
linha.Cells["dg_extra"].Value = "" + extra + "";
}
else
{
linha.Cells["dg_extra"].Value = "" + Config.rm.GetString(extra) + "";
}
DataConsole.CurrentCell = DataConsole.Rows[idLinha].Cells[0];
//DataConsole.Refresh();
}
}
catch (Exception ex)
{
throw;
}
}
}
However, the form freezes and I can't move it to any part of the screen, would there be any way to solve this? Remembering that the DataGridView is not, and cannot be populated through the DataSource property, but by a constant verification in the system.
Example:
public static void Abrir(string metodoChamador)
{
try
{
Abrir:
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
Thread.Sleep(5000);
Atalho:
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
if (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
Thread.Sleep(5000);
goto Atalho;
}
else
{
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
Thread.Sleep(5000);
IntPtr WinHandle = Win32.FindWindow(null, Config.Atalho);
if (WinHandle == (IntPtr)0)
{
goto Abrir;
}
}
}
catch (Exception ex)
{
throw;
}
}
It's hard to tell if you have other potential problems in the code. Basically anywhere you have Thread.Sleep(), your GUI is going to freeze.
Here's a possible refactoring of your Abrir() method, using async\await and Task.Delay() as suggested by JQSOFT:
public async static void Abrir(string metodoChamador)
{
try
{
IntPtr WinHandle = IntPtr.Zero;
do
{
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
await Task.Delay(5000);
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
while (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
await Task.Delay(5000);
}
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
await Task.Delay(5000);
WinHandle = Win32.FindWindow(null, Config.Atalho);
}
while (WinHandle.Equals(IntPtr.Zero));
}
catch (Exception ex)
{
throw;
}
}
If you have Thread.Sleep() in other locations, they would need to be refactored.
If you have any other infinite loops using goto, those may need to be refactored as well.

WFP all TextBlocks not updating

So my code was working just fine. But now, even though I can confirm the variables and strings are there through a Clipboard copy, the textblocks are not updating via TextBlock.Text. Did I turn something off? Every single one stopped doing it at the same time.
`private void actionPing_Click(object sender, RoutedEventArgs e)
{
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(HostNameIPTyped.Text.ToString(), 500);
if (reply != null)
{
string tripTime = reply.RoundtripTime.ToString();
if (tripTime == "0")
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#660000"));
PingStatus1.Text = "Device not found"; <---NONE OF THESE ARE UPDATING ACROSS THE ENTIRE PROGRAM
}
else
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#17b05c"));
PingStatus1.Text = "Ping Successful, " + reply.RoundtripTime.ToString() + "ms roundtrip";
//// LET'S GET THE IP AND HOSTNAME OF WHATEVER THE HELL YOU PUT IN
////IPADDRESS
try
{
System.Net.IPAddress ip = System.Net.Dns.GetHostEntry(HostNameIPTyped.Text.ToString()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First();
ipAddress = ip.ToString();
}
catch (Exception ex)
{ }
////HOSTNAME
try
{
System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(ipAddress);
machineName = hostEntry.HostName;
string linkBuild = "http://" + machineName;
}
catch (Exception ex) { }
PingStatus1.Text += " " + machineName;
}
}
}
catch
{
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#660000"));
PingStatus1.Text = "Device not found";
}
}
}`
It was updating the fields. I had made an adjustment to the size of the grid which flattened all of the textblock fields to the left side. Once I drug them out they were no longer auto-sized.
Thanks for the help!

C# Adding PC to AD domain group

Trying to add a hostname to a domain group, and I'm getting the exception There is a naming violation.
I've seen several accepted answers covering this exact thing and as far as I know my syntax is correct.
try
{
DirectoryEntry de = new DirectoryEntry("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Groups,OU=US,DC=aa,DC=bbbbb,DC=com");
string hostname = "CN=" + SystemInformation.ComputerName;
DirectoryEntry add = de.Children.Add(hostname, "Computer");
add.CommitChanges();
}
catch (Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
Any help would be greatly appreciated.
I figured out what the problem was - I needed to pass the Distinguished Name, rather than just the hostname... that should have been obvious, if I had actually read the MSDN doc... Also, de.Children.Add() may be a valid method to accomplish this (it was an accepted answer on SE, for .Net 3.5 IIRC), but I used de.Properties["member"].Add() to accomplish it.
Updated source code for any Googlers out there:
private void DoStuff(object sender, EventArgs e)
{
using (Process addgroup = new Process())
{
string hostname = Environment.MachineName;
AddMemberToGroup("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Group,OU=US,DC=aa,DC=bbbbb,DC=com", hostname);
}
}
private void AddMemberToGroup(string ldapString, string host)
{
try
{
DirectoryEntry de = new DirectoryEntry(ldapString);
string distHost = GetDistinguishedName(host);
if (!String.IsNullOrEmpty(distHost))
{
de.Properties["member"].Add(distHost);
de.CommitChanges();
}
else
{
MessageBox.Show("Distinguished Host Name returned NULL");
}
}
catch(Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
}
private string GetDistinguishedName(string compName)
{
try
{
PrincipalContext pContext = new PrincipalContext(ContextType.Domain);
ComputerPrincipal compPrincipal = ComputerPrincipal.FindByIdentity(pContext, compName);
return compPrincipal.DistinguishedName;
}
catch (Exception ex)
{
MessageBox.Show("Failed to get the Distinguished Hostname from Active Directory" + Environment.NewLine + Environment.NewLine + ex.ToString());
return null;
}
}

How to fix VS2013: Error: type or namespace 'Windows' could not be found?

I want to create a service for Wifi Direct. If I try to add Reference, I don't see core->windows option in VS2013. I have updated the winSDK.
How do I add the Windows.Devices.WifiDirect api ?
you can use
public sealed class WiFiDirectDevice : IDisposable
this is a sample code to handle connections
Windows.Devices.WiFiDirect.WiFiDirectDevice wfdDevice;
private async System.Threading.Tasks.Task<String> Connect(string deviceId)
{
string result = "";
try
{
// No device Id specified.
if (String.IsNullOrEmpty(deviceId)) { return "Please specify a Wi- Fi Direct device Id."; }
// Connect to the selected Wi-Fi Direct device.
wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(deviceId);
if (wfdDevice == null)
{
result = "Connection to " + deviceId + " failed.";
}
// Register for connection status change notification.
wfdDevice.ConnectionStatusChanged += new TypedEventHandler<Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(OnConnectionChanged);
// Get the EndpointPair information.
var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();
if (EndpointPairCollection.Count > 0)
{
var endpointPair = EndpointPairCollection[0];
result = "Local IP address " + endpointPair.LocalHostName.ToString() +
" connected to remote IP address " + endpointPair.RemoteHostName.ToString();
}
else
{
result = "Connection to " + deviceId + " failed.";
}
}
catch (Exception err)
{
// Handle error.
result = "Error occurred: " + err.Message;
}
return result;
}
private void OnConnectionChanged(object sender, object arg)
{
Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus status =
(Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus)arg;
if (status == Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus.Connected)
{
// Connection successful.
}
else
{
// Disconnected.
Disconnect();
}
}
private void Disconnect()
{
if (wfdDevice != null)
{
wfdDevice.Dispose();
}
}

How can I view the AntiVirus Status on my Windows Form Application?

Currently I have a bit of code that works in console but I was hoping I could avoid reinventing the wheel for something that should probably be super simple. Essentially I want to check for AV through WMI and display the AV status in a textbox.
// Below checks windows 7,8,10 for the detected AntiVirus
public static bool AntivirusInstalled()
{
string wmipathstr = #"\\" + Environment.MachineName + #"\root\SecurityCenter2";
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
ManagementObjectCollection instances = searcher.Get();
return instances.Count > 0;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return false;
}
public void Main(string[] args)
{
bool returnCode1 = AntivirusInstalled();
Console.WriteLine("Antivirus Installed " + returnCode1.ToString());
Console.WriteLine();
Console.Read();
textBox6.Text = "Antivirus Installed " + returnCode1.ToString();
}
public void OSViewButton_Click(object sender, EventArgs e)
{
textBox6.Text = "Antivirus Installed " + AntivirusInstalled2.ToString();
}

Categories