I'm currently working on a installer kind of program. It has a system check page where I check if all the requerments are met or not. One requirement is the availability of BitLocker.
Currently I check for BitLocker by trying to create an instance of Win32_EncryptableVolume and then check if an exception is thrown or not.
But I wonder if there is a more elegant way.
My method currently looks basicaly like this:
public static bool IsBitlockerAvaliable()
{
try
{
var path = new ManagementPath
{
NamespacePath = #"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption",
ClassName = "Win32_EncryptableVolume"
};
using (var wmi_class = new ManagementClass(path))
{
foreach (var o in wmi_class.GetInstances())
{
var vol = (ManagementObject) o;
if (vol == null)
throw new Exception("Vol is null");
Debug.WriteLine(vol);
}
}
return true;
}
catch (ManagementException e)
{
// No Admin rights is a different issue
if (e.ErrorCode == ManagementStatus.AccessDenied)
{
throw new AccessViolationException();
}
return false;
}
catch (Exception e)
{
return false;
}
}
Related
I am creating a Xamarin Form PCL project for Android and IOS.
Is this possible to display multiple permission at once on the screen? My App is using Location, Storage and Camera permission. From my current code, this is displaying permission popup one by one on the different page like before use of camera i display camera permission popup. As I know three permission required for my App so i want to display a single popup for all three permission.
Below is my code for storage permission.
public static async Task<dynamic> CheckStoragePermission()
{
var result = "";
try
{
var Storagestatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
if (Storagestatus != PermissionStatus.Granted)
{
await Utils.CheckPermissions(Plugin.Permissions.Abstractions.Permission.Storage);
}
}
catch (Exception ex)
{
error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
return result;
}
Hope someone did this before in xamarin forms, I will thank for your help for this.
You could try using the following code to request multiple permissions at one time:
private async void Button_Clicked(object sender, EventArgs e)
{
await GetPermissions();
}
public static async Task<bool> GetPermissions()
{
bool permissionsGranted = true;
var permissionsStartList = new List<Permission>()
{
Permission.Location,
Permission.LocationAlways,
Permission.LocationWhenInUse,
Permission.Storage,
Permission.Camera
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
try
{
foreach (var permission in permissionsNeededList)
{
var status = PermissionStatus.Unknown;
//Best practice to always check that the key exists
if (results.ContainsKey(permission))
status = results[permission];
if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
{
permissionsGranted = true;
}
else
{
permissionsGranted = false;
break;
}
}
}
catch (Exception ex)
{
}
return permissionsGranted;
}
I'm stuck in TAPI programming. I've created a program to monitor activity of phone call. Everything is working fine, but now I want to implement a functionality to accept and reject a call from web directly.
what I've done is below:
namespace Shared
{
public partial class Site : System.Web.UI.MasterPage
{
public static ITAddress ln;
static int index = -1;
static int line;
static ITAddress[] ia;
protected void Page_Load(object sender, EventArgs e)
{
#region TAPI
TAPIClass tobj;
int[] registertoken;
tobj = new TAPI3Lib.TAPIClass();
tobj.Initialize();
IEnumAddress ea = tobj.EnumerateAddresses();
uint lines;
uint arg3 = 0;
int TotalLines = 0;
lines = 0;
foreach (TAPI3Lib.ITAddress ad in (tobj.Addresses as TAPI3Lib.ITCollection))
{
TotalLines++;
}
callnotification cn = new callnotification();
tobj.ITTAPIEventNotification_Event_Event += new TAPI3Lib.ITTAPIEventNotification_EventEventHandler(cn.Event);
tobj.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION |
TAPI_EVENT.TE_DIGITEVENT |
TAPI_EVENT.TE_PHONEEVENT |
TAPI_EVENT.TE_CALLSTATE |
TAPI_EVENT.TE_GENERATEEVENT |
TAPI_EVENT.TE_GATHERDIGITS |
TAPI_EVENT.TE_REQUEST);
registertoken = new int[TotalLines];
ia = new TAPI3Lib.ITAddress[TotalLines];
for (int i = 0; i = 0)
{
ln = ia[line];
}
IEnumCall ec = ln.EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
{
if (bc != null)
{
bc.Answer();
}
}
}
catch (Exception ex)
{
COMException comEx = ex as COMException;
if (comEx != null)
comEx.ErrorCode.ToString();
else
{
string aa = ex.Message;
}
}
//addtolist("Call Offering from " + callernumber + " to Ext " + viaextension + " via DID " + DIDNumber);
break;
case TAPI3Lib.CALL_STATE.CS_IDLE:
//addtolist("Call is created!");
break;
}
break;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.StackTrace.ToString());
}
}
}
#endregion
}
}
I'm always getting ITBasicCallControl2 bc NULL and when I press the Accept button, nothing happens.
Okay, so the first thing you have to do in order to successfully answer calls, is to register your line with owner rights.
tobj.RegisterCallNotifications(ln, true, true, TapiConstants.TAPIMEDIATYPE_AUDIO, 2);
After that, you can either iterate through every call using EnumerateCalls(), or you can implement the ITTAPIEventNotification interface to get notified if there is a change in callstate (for example).
One way or the other, at some point, you have found the call you want to answer. Now you need to make sure, that the call is in an alerting state (CS_OFFERING for inbound calls), before you can finally call the answer method.
try
{
ec.Next(1, out ici, ref arg);
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
{
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
if (bc != null)
{
bc.Answer();
}
}
}
catch (Exception exp)
{
COMException comEx = exp as COMException;
if (comEx != null)
MessageBox.Show(comEx.ErrorCode.ToString());
else
MessageBox.Show(exp.Message);
}
If the call you want to answer is not in the callstate CS_CONNECTED, the method will throw a COMException with an error code of 0x800040010.
For further information on the ITTAPIEventNotification interface, see https://msdn.microsoft.com/en-us/library/windows/desktop/ms732506(v=vs.85).aspx
EDIT:
If you want to detect new incoming calls, I'd recommend to use the TE_CALLNOTIFICATION-Event, because it is triggered only once per new incoming call.
The TE_CALLSTATE-Event will be triggered every time the callstate changes.
Now, i've updated the callnotification class:
public class callnotification : TAPI3Lib.ITTAPIEventNotification
{
public InboundCall OnNewIncomingCall;
public void Event(TAPI_EVENT TapiEvent, object pEvent)
{
switch (TapiEvent)
{
case TAPI_EVENT.TE_CALLNOTIFICATION:
this.OnCallNotification((ITCallNotificationEvent)pEvent);
break;
}
}
private void OnCallNotification(ITCallNotificationEvent callNotification)
{
ITCallInfo ici = callNotification.Call;
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
this.OnNewIncomingCall(ici);
}
}
I've also declared a delegate Method to use if there is a new inbound call:
public delegate void InboundCall(ITCallInfo ici);
So your initialization of the callnotification event could look like this:
callnotification cn = new callnotification();
cn.OnNewIncomingCall += this.OnNewIncomingCall;
And finally, in the OnNewIncomingCallMethod, you can answer the call:
private void OnNewIncomingCall(ITCallInfo ici)
{
ITBasicCallControl bcc = (ITBasicCallControl)ici;
if (bcc != null)
{
string caller = ici.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
DialogResult dlg = MessageBox.Show(string.Format("New incoming call from {0}\r\nDo you wish to answer the call now?", caller), "New incoming call", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlg == System.Windows.Forms.DialogResult.Yes)
bcc.Answer();
}
}
I've tested your code with the additions of mine and it worked fine. Should you be having any exceptions when answering or during the initialization, let me know.
Im kinda new to c# so if somebody please tell me why im getting an error
private void button2_Click(object sender, EventArgs e)
{
lblTaskManager.Text = null;
RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
#"Software\Microsoft\Windows\CurrentVersion\Policies\System");
try
{
if (objRegistryKey.GetValue("DisableTaskMgr") == null)
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = ("Disabled");
else
objRegistryKey.DeleteValue("DisableTaskMgr");
objRegistryKey.Close();
lblTaskManager.Text = ("Enabled");
}
catch
{ }
}
}
}
The error is at ("Disabled"); it suggests that a } is required but adding that does not change anything. And also how can I avoid this error in the future.
Use { } correct with if:
if (objRegistryKey.GetValue("DisableTaskMgr") == null)
{
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = ("Disabled");
}
else
{
objRegistryKey.DeleteValue("DisableTaskMgr");
objRegistryKey.Close();
lblTaskManager.Text = ("Enabled");
}
The ( ) are not needed but shouldn´t harm your code.
And maybe you should move the objRegistryKey.Close(); to the finally of the try catch.
Well,
Put RegistryKey creation into using and drop explict Close().
Add {} after if and else.
Remove () around the strings assigned.
Drop that nightmare try { ... } catch {} (ignore all exceptions thrown) and never ever use such code again.
Something like this:
using (RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
"#Software\Microsoft\Windows\CurrentVersion\Policies\System")) {
if (objRegistryKey.GetValue("DisableTaskMgr") == null) {
objRegistryKey.SetValue("DisableTaskMgr", "1");
lblTaskManager.Text = "Disabled";
}
else {
objRegistryKey.DeleteValue("DisableTaskMgr");
lblTaskManager.Text = "Enabled";
}
}
I'm currently having problem in my project. I'm having Code 4004 error in silverlight application. I don't know what I did wrong. Here are the image link.
http://s1100.photobucket.com/user/Fredi_Tansari/media/errorInsilverlight.png.html
here are the codes. After the the invalideoperation exception it goes to the unhandled exception error.
private void getstatusCompleted(LoadOperation<PatientStatus1> obj)
{
try
{
PatientStatus1 bc = obj.Entities.First();
if (bc != null)
{
MessageBox.Show("Patient has a status already, please use update instead new");
return;
}
else
{
MessageBox.Show("inserting new Patient status");
}
}
catch (InvalidOperationException e)
{
PatientStatus1 newPatientStatus = new PatientStatus1();
newPatientStatus.ColorCodeID = "1";
newPatientStatus.timestamp = DateTime.Now;
newPatientStatus.UserID = "Jimmi";
newPatientStatus.Patient_PatientID = Convert.ToInt32(patientIDTextBox.Text);
newPatientStatus.MasterPatientStatus_masterPatientStatusId = Convert.ToInt32(masterPatientStatusIdTextBox.Text);
newPatientStatus.MasterLocation_masterLocationID = Convert.ToInt32(masterLocationIDTextBox1.Text);
patientstatusDomainContext.PatientStatus1s.Add(newPatientStatus);
patientstatusDomainContext.SubmitChanges();
}
}
Thanks in advance for the help
Try to set this key value to 1.
HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug
Hi I'm developing a winform application using C# and the entity framework (linq to entities).
Suppose the following escenario:
In a method of some class, I set and object of values with form values
private void agrega_cliente_Click(object sender, EventArgs e)
{
cliente = new _Cliente();
try
{
cliente.nombres = nom_cliente.Text;
cliente.apellidoP = apellidoP_cliente.Text;
cliente.apellidoM = apellidoM_cliente.Text;
cliente.fechaNacimiento = fechaNacimientoPicker.Value.Date;
if (operaciones.AgregaCliente(cliente, referencias))
{
MessageBox.Show("Cliente Agregado");
this.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Note that the assigment and calling to method "AgregaCliente" is between a try and catch, so if an exception is triggered a MessageBox will show it.
Then in other class, I have AgregaCliente method which insert values in a database.
public bool AgregaCliente(_Cliente cliente, ArrayList refes)
{
try
{
Cliente cli = new Cliente()
{
Nombres = cliente.nombres,
ApellidoP = cliente.apellidoP,
ApellidoM = cliente.apellidoM,
FechaNac = cliente.fechaNacimiento
};
if (NombreExiste(cli))
context.clientes.AddObject(cli);
else
throw new System.ArgumentException("El usuario ya existe");
if (refes.Count != 0)
{
foreach (_Referencia elem in refes)
context.referencias_personales.AddObject(AgregaReferencia(elem));
}
context.SaveChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
Inside this method there is a call to "NombreExiste()" which checks that the user isn't already inserted, if the user exists an exception is thrown.
So the problem here is that if an exception is thrown in "AgregaCliente" method, I want this exception to be catched by "agrega_cliente_Click()" method, so the user knowns what originated the problem. I hope you understand what I'm trying to do.
Thanks
Simply get rid of your try/catch inside the AgregaCliente() method and the exception will automatically bubble-up.
public bool AgregaCliente(_Cliente cliente, ArrayList refes)
{
Cliente cli = new Cliente()
{
Nombres = cliente.nombres,
ApellidoP = cliente.apellidoP,
ApellidoM = cliente.apellidoM,
FechaNac = cliente.fechaNacimiento
};
if (NombreExiste(cli))
context.clientes.AddObject(cli);
else
throw new System.ArgumentException("El usuario ya existe");
if (refes.Count != 0)
{
foreach (_Referencia elem in refes)
context.referencias_personales.AddObject(AgregaReferencia(elem));
}
context.SaveChanges();
return true;
}
The problem is that your AgregaCliente() method is catching all exceptions and simply swallowing them. Instead of catching all exceptions via:
catch (Exception ex)
{
return false;
}
You should only catch specific Exceptions you can handle and let the others pass up the call chain. However, you should know that throwing exceptions is very "expensive" for a program. C# does a lot of work behind the scenes when an exception is thrown. A better solution may be to use a return code to indicate to callers of the AgregaCliente() method the status. For example:
public enum AgregaClienteStatus
{
Success = 0;
ClientAlreadyExists = 1;
Other = ??; // Any other status numbers you want
}
public AgregaClienteStatus AgregaCliente(_Cliente cliente, ArrayList refes)
{
Cliente cli = new Cliente()
{
Nombres = cliente.nombres,
ApellidoP = cliente.apellidoP,
ApellidoM = cliente.apellidoM,
FechaNac = cliente.fechaNacimiento
};
if (NombreExiste(cli))
context.clientes.AddObject(cli);
else
return AgregaClienteStatus.ClientAlreadyExists
if (refes.Count != 0)
{
foreach (_Referencia elem in refes)
context.referencias_personales.AddObject(AgregaReferencia(elem));
}
context.SaveChanges();
return AgregaClientStatus.Success;
}
Of course, this functionality could also be achieved using constant integers if you don't like enums.
You can then use that return status to indicate information to the user without the expense of an exception:
var result = AgregaClient(cliente, refes);
switch (result)
{
case AgregaClientStatus.Success:
// Perform success logic
break;
case AgregaClientStatus.ClientAlreadyExists:
MessageBox.Show("Client already exists");
break;
// OTHER SPECIAL CASES
default:
break;
}
}