ASP.NET can't create Windows Event Log even as Administrator - c#

I'm working on an ASP.NET web application in Visual Studio 2013 and as part of the main error routine, I want it to store the errors in a Windows Event Log. However, every time I run the code, the log never gets created even when I run Visual Studio as Administrator. Would turning off UAC fix this? Code is below. Any help is appreciated. Thanks.
public static void ErrorRoutine(Exception e, string obj, string method)
{
EventLog.Delete("LogName"); // uncomment this line to delete log
EventLog log = new EventLog();
log.Source = "SourceName";
log.Log = "LogName";
if (e.InnerException != null)
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", inner exception = " +
e.InnerException.Message, EventLogEntryType.Error);
throw e.InnerException;
}
else
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", message = " + e.Message,
EventLogEntryType.Error);
throw e;
}
}
Edit: I get that this is probably not best practice but this project is actually an assignment for college and this is the exact code we were told to write, as well as being told to run VS as Administrator. I just need to find a way to make work really.

Related

How would I detect and display an HTTP error message(404) on Xamarin if I'm using an API wrapper?

I am currently using Xamarin to create a multiplatform application for the phone. The app idea is basically a Pokemon encyclopedia that utilizes the PokeAPi (https://pokeapi.co/) and also uses the following wrapper library (https://gitlab.com/PoroCYon/PokeApi.NET). Currently, I want it to where if the user types in an incorrect Pokemon into the search bar, it will return an alert error to the user. However, every time I test it and enter in an invalid pokemon, the application stops and Visual Studio/Xamarin informs me of a HTTP404 error. How would I go about this?
I've tried using comparison statements in where if the API call doesn't find the pokemon name, it should pop up with an alert, but VS/Xamarin will stop running the application and display a Http404 exception. I really dont know where to go at this point.
'''
async Task PullData()
{
LoadingIcon.IsRunning = true;
string newPokemon = PokemonFind.Text;
Pokemon p = await DataFetcher.GetNamedApiObject<Pokemon>(newPokemon);
string PokemonName = p.Name;
int PokemonHeight = p.Height;
int PokemonWeight = p.Mass;
int PokemonXp = p.BaseExperience;
int PokemonOrder = p.Order;
OrderLabel.Text = "#" + PokemonOrder;
NameLabel.Text = "Name: " + PokemonName;
HeightWeightLabel.Text = "Height/Weight: " + PokemonHeight.ToString() +" dm " + "/" + PokemonWeight.ToString() + " hg";
ExpLabel.Text = "Experience on defeat: " + PokemonXp.ToString() + "XP";
LoadingIcon.IsRunning = false;
}
'''
I expected it to display an alert message instead of VS/Xamarin stopping the program and throwing me an HTTP404 exception.
Wrap your call inside a try/catch block
try
{
async Task PullData()
}
catch(HttpRequestException ex)
{
//Shows an alert error to the user
}

How to store persistent User Connection Strings with .NET WPF Click-Once

We're developing a Click-Once WPF Windows Application that retrieves all its data from a database. I implemented a Form where a User could enter the corresponding data and using a SqlConnectionStringBuilder we build the Connection String and that works just fine.
We then add the Connection String to the ConfigurationManager using
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
If we use some other ConfigurationUserLevel, the application crashes (I don't know why yet, but I believe the Entity Framework Model tries to load the connection string and doesn't find it, because the file is not stored in the correct User Level?). Now, we store the connection string in a separate file and load it in App.config so we don't have to check it into Version Control:
<connectionStrings configSource="connections.config"/>
We don't deploy this file because it contains our own development connection strings. Rather, we create an empty file for deployment where the user-entered connection string will be stored. This works completely fine.
Our problem is that with a click-once update, the file will be "lost". What is the best way to store persistent per-user connection strings encrypted in a configuration file? Or should we completely switch to Registry? Or create our own encrypted File somewhere outside the %APPDATA%/Local/Apps/2.0/...../ folders and load it manually when initializing the Entity Framework Context?
You can go to MSDN site it might help you
https://msdn.microsoft.com/en-us/library/dd997001.aspx
with the help of below code, you need to modify this code for your requirement, hope this will help.
To create a custom ClickOnce application installer
In your ClickOnce application, add references to System.Deployment and System.Windows.Forms.
Add a new class to your application and specify any name. This walkthrough uses the name MyInstaller.
Add the following Imports or using statements to the top of your new class.
using System.Deployment.Application;
using System.Windows.Forms;
Add the following methods to your class.
These methods call InPlaceHostingManager methods to download the deployment manifest, assert appropriate permissions, ask the user for permission to install, and then download and install the application into the ClickOnce cache. A custom installer can specify that a ClickOnce application is pre-trusted, or can defer the trust decision to the AssertApplicationRequirements method call. This code pre-trusts the application
Note:- Permissions assigned by pre-trusting cannot exceed the permissions of the custom installer code.
InPlaceHostingManager iphm = null;
public void InstallApplication(string deployManifestUriStr)
{
try
{
Uri deploymentUri = new Uri(deployManifestUriStr);
iphm = new InPlaceHostingManager(deploymentUri, false);
}
catch (UriFormatException uriEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + uriEx.Message);
return;
}
catch (PlatformNotSupportedException platformEx)
{
MessageBox.Show("Cannot install the application: " +
"This program requires Windows XP or higher. " +
"Error: " + platformEx.Message);
return;
}
catch (ArgumentException argumentEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + argumentEx.Message);
return;
}
iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted);
iphm.GetManifestAsync();
}
void iphm_GetManifestCompleted(object sender, GetManifestCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download manifest. Error: " + e.Error.Message);
return;
}
// bool isFullTrust = CheckForFullTrust(e.ApplicationManifest);
// Verify this application can be installed.
try
{
// the true parameter allows InPlaceHostingManager
// to grant the permissions requested in the applicaiton manifest.
iphm.AssertApplicationRequirements(true) ;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while verifying the application. " +
"Error: " + ex.Message);
return;
}
// Use the information from GetManifestCompleted() to confirm
// that the user wants to proceed.
string appInfo = "Application Name: " + e.ProductName;
appInfo += "\nVersion: " + e.Version;
appInfo += "\nSupport/Help Requests: " + (e.SupportUri != null ?
e.SupportUri.ToString() : "N/A");
appInfo += "\n\nConfirmed that this application can run with its requested permissions.";
// if (isFullTrust)
// appInfo += "\n\nThis application requires full trust in order to run.";
appInfo += "\n\nProceed with installation?";
DialogResult dr = MessageBox.Show(appInfo, "Confirm Application Install",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr != System.Windows.Forms.DialogResult.OK)
{
return;
}
// Download the deployment manifest.
iphm.DownloadProgressChanged += new EventHandler<DownloadProgressChangedEventArgs>(iphm_DownloadProgressChanged);
iphm.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>(iphm_DownloadApplicationCompleted);
try
{
// Usually this shouldn't throw an exception unless AssertApplicationRequirements() failed,
// or you did not call that method before calling this one.
iphm.DownloadApplicationAsync();
}
catch (Exception downloadEx)
{
MessageBox.Show("Cannot initiate download of application. Error: " +
downloadEx.Message);
return;
}
}
/*
private bool CheckForFullTrust(XmlReader appManifest)
{
if (appManifest == null)
{
throw (new ArgumentNullException("appManifest cannot be null."));
}
XAttribute xaUnrestricted =
XDocument.Load(appManifest)
.Element("{urn:schemas-microsoft-com:asm.v1}assembly")
.Element("{urn:schemas-microsoft-com:asm.v2}trustInfo")
.Element("{urn:schemas-microsoft-com:asm.v2}security")
.Element("{urn:schemas-microsoft-com:asm.v2}applicationRequestMinimum")
.Element("{urn:schemas-microsoft-com:asm.v2}PermissionSet")
.Attribute("Unrestricted"); // Attributes never have a namespace
if (xaUnrestricted != null)
if (xaUnrestricted.Value == "true")
return true;
return false;
}
*/
void iphm_DownloadApplicationCompleted(object sender, DownloadApplicationCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download and install application. Error: " + e.Error.Message);
return;
}
// Inform the user that their application is ready for use.
MessageBox.Show("Application installed! You may now run it from the Start menu.");
}
void iphm_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// you can show percentage of task completed using e.ProgressPercentage
}
To attempt installation from your code, call the InstallApplication method. For example, if you named your class MyInstaller, you might call InstallApplication in the following way.
MyInstaller installer = new MyInstaller();
installer.InstallApplication(#"\\myServer\myShare\myApp.application");
MessageBox.Show("Installer object created.");

Running Powershell script causes 'Memory corruption' or 'Cannot Read or Write'

Im making a program that makes a Wi-Fi hotspot for you and enables Internet Connection Sharing automaticly using a powershell script.
The script works and runs perfectly, but i have to wait for it to be finished so i can notify the user its done. Im using below code which works but...
but it crashes and causes an error on my home computer which is allot faster.
I get a Cannot read or write or memory is corrupt error which i can't really explain.
public static void ToggleIcs(string connectionInterface, bool state)
{
string toggle;
string par1;
string par2;
if (state){
toggle = "EnableSharing";
par1 = "0";
par2 = "1";
}else{
toggle = "DisableSharing";
par1 = "";
par2 = "";
}
using (PowerShell powerShellInstance = PowerShell.Create())
{
// this script enables or disables internet sharing with the connectionInterface given.
powerShellInstance.AddScript("" +
"regsvr32 hnetcfg.dll /s;" +
"$m = New-Object -ComObject HNetCfg.HNetShare;" +
"$m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_) };" +
"$c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq '" + connectionInterface + "' };" +
"$config = $m.INetSharingConfigurationForINetConnection.Invoke($c);" +
"Write-Output $config.SharingEnabled;" +
"Write-Output $config.SharingConnectionType;" +
"$config." + toggle + "(" + par1 + ");" +
"$m2 = New-Object -ComObject HNetCfg.HNetShare;" +
"$m2.EnumEveryConnection |% { $m2.NetConnectionProps.Invoke($_) };" +
"$c2 = $m2.EnumEveryConnection |? { $m2.NetConnectionProps.Invoke($_).DeviceName -Match 'Microsoft Hosted Network Virtual Adapter' };" +
"$config2 = $m2.INetSharingConfigurationForINetConnection.Invoke($c2);" +
"Write-Output $config2.SharingEnabled;" +
"Write-Output $config2.SharingConnectionType;" +
"$config." + toggle + "(" + par2 + ");");
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
Console.WriteLine(DateTime.Now + ">> Started Powershell script");
int i = 0;
while (!result.IsCompleted)
{
if (i < 60)
{
Console.WriteLine(DateTime.Now + ">> Running script");
}
else
{
ScriptFailed();
powerShellInstance.Stop();
break;
}
i++;
Thread.Sleep(1000);
}
Console.WriteLine(DateTime.Now + ">> Executed Internet Sharing script");
}
}
This is the error im getting:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I don't get a line that says where it crashes but it crashes after Thread.Sleep(1000);. Which i found out using breakpoints
As I said, the script runs fine on my laptop, and it does work on my faster computer, but it crashes as soon as it hits Thread.Sleep(1000).
After it crashed, I checked if ICS was enabled in the network and sharing center, and and it did so correctly.
I tried removing the Thread.Sleep(1000); but then it crashes anyway a line before.
What can I try or do differently?
Edit
i dont have the stack trace yet, as i am not on my faster PC where it crashes. but I will post it as soon as possible.
Edit
As mentioned by TheLethalCoder, it could be that i try to acces IsCompleted While it is being updated. If that is why it happens, How would I check if it is being altered or wait for it to be done.
Edit
As i dont really know what the call stack is for, or what a stack trace is, and how i can use it ill provide an image of what i saw one moment before the crash.
Edit
I did some snooping around and found a few things i tried.
first, in the application properties -> build, i ticked "Prefer 32bit" off
Because some people fixed their problems with this. And i did not get a crash but the script also failed to run and caused my internet connection to drop.
so i turned it back on.
I also tried the netsh winsock reset command and restarting my pc but it still crashed.
Im all out of clues now, but i posted these two things for people who come by looking for an answer and maybe this will work.
The MSDN article: Polling for the Status of an Asynchronous Operation states that the way you are polling the result is correct. However their example doesn't include a Thread.Sleep:
while (result.IsCompleted != true)
{
UpdateUserInterface();
}
So to eliminate this I would use the following snippet that keeps track of the variables without sleeping, note that printing to the Console on every loop is going to quickly pollute the window though:
Stopwatch sw = new Stopwatch();
sw.Start();
while (!result.IsCompleted)
{
if (sw.EllapsedMilliseconds >= 60000) //60 seconds
{
break;
}
Console.WriteLine(DateTime.Now + ">> Running script");
}
if (!result.IsCompleted)
{
ScriptFailed();
powerShellInstance.Stop();
}
This is more of a comment than an answer but it was getting too long to be used as a comment.

Windows Application Log Events being 'missed' somehow with my EventLog

I've written an application, a component of which watches for Events being raised in the Windows Application Log with a certain Source and EventID in order to parse data from them. However, it appears to miss some of these events for no readily apparent reason.
I have included debug messages to try to see where the issue is - this takes the form of comments sent to a text field.
When an Entry is written to the application log, a time-stamped message is added to the debug text field, and parseApplicationLogEntry() is called.
private void eventLogApplication_EntryWritten(object sender,
System.Diagnostics.EntryWrittenEventArgs e)
{
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
+ ": Application Log has been written.";
parseApplicationLogEntry();
}
The application log entry is parsed, and the Source and EventID are looked at to determine if they are what we are looking for. A time-stamped message is added to the debug text showing the Source and EventID found.
private void parseApplicationLogEntry()
{
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application");
int entry = log.Entries.Count - 1;
string logMessage = log.Entries[entry].Message;
string logSource = log.Entries[entry].Source;
string logEventID = log.Entries[entry].InstanceId.ToString();
log.Close();
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
": Application Log Source is " + logSource;
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
": Application Log EventID is " + logEventID;
if (logSource == "ExpectedSource" & logEventID == "ExpectedEventID")
{
// Do stuff
}
}
The behaviour is as expected much of the time, however sometimes there is very odd behaviour.
For example, 13 logs were written to the application log. 3 with the looked-for source, and 10 with another source. The debug text shows 13 entries were seen, all with the unfamiliar source...
I'm not sure where to go from here.
There is no need to access the EventLog in this way to review the newest entries.
Instead of calling a method to iterate through the EventLog each time a new Entry is written, it is simpler (and safer) to access the Entry more directly using the event handler which triggers each time an Entry is written.
private void eventLog_Application_EntryWritten(object sender, EntryWrittenEventArgs e)
{
// Process e.Entry
}

Check if password never expired from code is not working on specific network

I got some code of a tool which does many security checks on client machines and I'm trying to understand some bug and solve it - need your help.
There is a test which checks if the user password is set to "never expire". I tried this test offline and in 3 different networks and it seems to be working. There is some WIFI guest network in my company which return exception while executing the code.
Here is the exception I'm getting:
The network path was not found.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_NativeObject()
at System.DirectoryServices.DirectoryEntry.InvokeGet(String propertyName)
at Intel.HostCheck.Engine.Checks.PasswordAge.CheckPasswordNeverExpired()
See the the following code for understanding the test implementation:
private CheckResult CheckPasswordNeverExpired()
{
try
{
DirectoryEntry de;
Logger.Debug("Password Age: isCurrentUserLocalUser - " + HelpFunction.isCurrentUserLocalUser());
if (HelpFunction.isCurrentUserLocalUser())
de = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + Environment.UserName);
else de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
object currentUser = de.InvokeGet("UserFlags");
if (currentUser != null)
{
Logger.Debug("PasswordAge: " + currentUser);
Logger.Debug("PasswordAge: " + Convert.ToBoolean((int)currentUser & UF_DONT_EXPIRE_PASSWD).ToString());
}
if (Convert.ToBoolean((int)currentUser & UF_DONT_EXPIRE_PASSWD))
{
Logger.Debug("Password Age: check result: fail ");
return CheckResult.Fail;
}
Logger.Debug("Password Age: check result: pass ");
return CheckResult.Pass;
}
catch (Exception ex)
{
Logger.LogException(ex, "Error in PasswordAge->Check()");
return CheckResult.Exception;
}
}
}
public static bool isCurrentUserLocalUser()
{
return Environment.MachineName == Environment.UserDomainName;
}
Just for clarification, it's not my code so I'm not completely sure what the code owner did.
I'm seeing that there are no responses. I will ask different question.
Is there any option to obtain password age or password last set values without be depend on network connection? Is it possible to check it locally?
I know this value also exists under "Local security policy" but I didn't find how to get it by code.

Categories