Code 4004 in C# silverlight application - c#

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

Related

Elegant way to programmatically check if BitLocker is available on system?

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;
}
}

How can I download (from URL) an apk with a button in xamarin Android?

I used WebClient to download a file in my apk. But I got this error:
Unhandled Exception:
System.Net.WebException: An exception occurred during a WebClient request.
And this is the code that I tried:
{
using (WebClient client = new WebClient())
{
client.DownloadFile(
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
}
Since you are only referring to a WebException, it may have to do with one of these cases:
The URI formed by combining BaseAddress and address is invalid.
The file or destination folder does not exist. Make sure your path to
the destination folder already exists and that you have permissions to access it.
An error occurred while
downloading data.
If you provide us more information about the exception we may be able to reduce the error to one of these cases. To get the InnerException you can do something like this:
{
using (WebClient client = new WebClient ())
{
try
{
client.DownloadFile (
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine (ex.Message);
ex = ex.InnerException;
}
}
}
}
You have to ask permissions on run time even you have mentioned them in your manifest file if you are running Android api level 23 or greater.
Have a look at this blog would help about how to ask a run time permission:requesting-runtime-permissions-in-android
Also, this is the official sample of how to check RuntimePermissions
Refer: xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied
Update:
To ask run time permissions, you can use this plugin:Plugin.Permissions, install it to your project.
And then, call CheckMyPermissionAsync(); before you download the file:
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
CheckMyPermissionAsync();
}
In the method CheckMyPermissionAsync(), check your Storage permission and then download file:
public async void CheckMyPermissionAsync()
{
var permissionsStartList = new List<Permission>()
{
Permission.Storage
};
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());
//Check the persimmison again
var storeagePermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storeagePermission == PermissionStatus.Granted)
{
//Download file here
DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg", "XF_Downloads");
}
else {
Console.WriteLine("No permissions");
}
}
You can check the result in the completed event:
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("success");
}
else
{
if (OnFileDownloaded != null) { }
Console.WriteLine("fail");
}
}
Note: pay attention to your filePath,make sure your path is correct, I use:
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
I updated my sample here: runtime-permission-xamarin.android

Windows IOT UWP - Relay

Good Evening,
I’m doing some troubleshooting on the beginning of my home automation system. I am trying to toggle a relay using a Raspberry PI 3 and Windows IOT in C#. I’ve been playing with the code and I can see the relay toggle once or twice, but then the app crashes. I’m an IOT Noob, so is there something wrong with this code? (Variable names are defined elsewhere and the weird variable names I have below are for my WIP project... I prefer troubleshooting in English)....
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
else
{
TempFan.Dispose();
}
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
if (gpio == null)
{
PinName = null;
LblError.Text = "We can't find the controller on the device" + PinName;
LblError.Visibility = Visibility.Visible;
return;
}
if (PinName == null)
{
LblError.Text = "We can't find the pin on the device. Pin number " + PinNumber + "does not exist";
LblError.Visibility = Visibility.Visible;
return;
}
if (Name.IsChecked == true)
{
pinvalue = value;
PinName.Write(pinvalue);
PinName.SetDriveMode(GpioPinDriveMode.Output);
}
You don't say what the exception is. However, I believe you are supposed open a GPIO pin only once per app:
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
You have it in a method which is called once per button click. By opening the pin more than once, you are encountering that the pin is already open, and I believe this is what throws an exception and crashes the app.
In my code, I handle pin states in a "driver" class, and have a method called Connect which I call once when starting the application. For example:
public async Task Connect()
{
var gpioController = await GpioController.GetDefaultAsync();
try
{
_openPin = gpioController.OpenPin(_doorMotorOpenPin);
_closePin = gpioController.OpenPin(_doorMotorClosePin);
}
}
This encapsulates the 2 pins: _openPin and _closePin into a class that I can manage the lifecycle of.
Codekaizen is correct. I separated out opening the pin into a method that only gets called once and problem solved.
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == false)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.Low);
}
}
private void InitializePins()
{
var gpio = GpioController.GetDefault();
// Show an error if there is no GPIO controller
if (gpio == null)
{
TempFan = null;
LblError.Text = "We can't find the controller on the device";
LblError.Visibility = Visibility.Visible;
return;
}
TempFan = gpio.OpenPin(TempFan_PIN);
TempFan.SetDriveMode(GpioPinDriveMode.Output);
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
pinvalue = value;
PinName.Write(pinvalue);
}

Why is my label field is giving me an error in this c# code

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";
}
}

C#: trying to set "ServerBindings" property of my website programatically, keeps crashing

I am trying to Configure my IIS programmatically following the steps on this
msdn guide
the only difference i made was switching to winforms instead of console..
and variables instead of function parameters.
however the code throws an exception when i try to set the singleproperty value...
here is my code..
string metabasePath = "IIS://localhost/W3SVC/1234", propertyName = "ServerBindings";
object newValue = " :8080:";
try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);
//when i try to retrieve the old value,it returns a null
PropertyValueCollection propValues = path.Properties[propertyName];
MessageBox.Show("7");
//the code throws an exception after messagebox,
//kinda old school debuging
path.Properties[propertyName][0] = newValue;
path.CommitChanges();
lblerror.Text = "Done";
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
lblerror.Text = " Property does not exist at ";
else
lblerror.Text = "Failed in SetSingleProperty "+ ex.Message.ToString();
}
The following 'helper' methods (SetServerBinding and RemoveServerBinding) should be of use:
static void Main(string[] args)
{
using(DirectoryEntry site = new DirectoryEntry("IIS://Localhost/W3SVC/1234"))
{
SetServerBinding(":8080:", site);
RemoveServerBinding(":8080:", site);
RemoveServerBinding("172.16.4.99:8087:somesite.com", site);
SetServerBinding("172.16.4.99:8087:somesite.com", site);
}
}
public static void SetServerBinding(string binding, DirectoryEntry site)
{
if(site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
return;
}
site.Properties["ServerBindings"].Add(binding);
site.CommitChanges();
}
public static void RemoveServerBinding(string binding, DirectoryEntry site)
{
if (site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
}
site.CommitChanges();
}

Categories