The application, not ASP.NET, uses the below code to authenticate with windows.
Run the application as a normal process and it fails to authenticate with either local machine or domain. "The handle is invalid" is the exception for local machine.
Run it as administrator and it works fine for both domain and machine. Any idea?
It did use to work fine for both, so it is not impossible that there was a policy change in the security settings.
private bool VerifyWindowsPassword()
{
bool ret = false;
string username = this.usernameTextBox.Text;
string unsecure = ConvertToUNSecureString(this.Password);
try
{
var context = new PrincipalContext(ContextType.Domain);
try
{
ret = context.ValidateCredentials(username, unsecure);
if (ret)
{
return true;
}
}
catch
{
}
context = new PrincipalContext(ContextType.Machine);
ret = context.ValidateCredentials(username, unsecure);
if (ret)
{
return true;
}
if (!ret)
{
MessageBox.Show(
"Windows User/Password could not be authenticated.",
"Settings",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("Windows User/Password could not be authenticated. {0}", ex.Message),
"Settings",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
return ret;
}
Related
My login window uses LDAP to authenticate users. However, when validating, it always returns false.
Here is the code for validation which I got from CodeProject:
public bool fnValidateUser()
{
bool validation;
try
{
LdapConnection lcon = new LdapConnection
(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(Environment.UserName,
txtPassword.SecurePassword, Environment.UserDomainName);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
// user has authenticated at this point,
// as the credentials were used to login to the dc.
lcon.Bind(nc);
validation = true;
}
catch (LdapException)
{
validation = false;
}
return validation;
}
txtPassword.SecurePassword is the PasswordBox. When I enter my password/pin and hit login, it displays the MessageBox for whenever validation is false.
What am I doing wrong?
UPDATE: The exception indicates "The LDAP Server is Unavailable", at this line lcon.Bind(nc);
You can try this sample piece of code.
// the username and password to authenticate
const string domain = "OU=Organization,DC=mydomain,DC=com";
string password = "mypass";
string userName = "myuser";
// define your connection
LdapConnection ldapConnection = new LdapConnection("ldap.mydomain.com:389");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
I went ahead and found another approach for this, without using LDAP.
PrincipalContext adContext = new PrincipalContext(ContextType.Machine);
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
using (adContext)
{
if (adContext.ValidateCredentials(txtUsername.Text, txtPassword.Password))
{
MainWindow main = new MainWindow();
main.Show();
main.txtLoggedInUser.Text = UserPrincipal.Current.DisplayName;
this.Close();
}
else
{
MessageBox.Show("Incorrect Username or Password!");
}
}
}
catch(Exception ex)
{
var exceptionDialog = new MessageDialog
{
Message = { Text = ex.ToString() }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
}
}
I have a C# application that is self hosting a WCF service. I want to add a button click event in the application that lets the user know if the service is running/being hosted. Is there a way to detect if the service is running/hosted?
In case someone wants to see it, here is the code I am using to start hosting the service:
private static void RunService()
{
System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(AccountingOperationsService.AccountingOperationsService));
System.ServiceModel.Description.ServiceDebugBehavior debug = host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceDebugBehavior>();
// if not found - add behavior with setting turned on
if (debug == null)
{
host.Description.Behaviors.Add(
new System.ServiceModel.Description.ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
}
else
{
// make sure setting is turned ON
if (!debug.IncludeExceptionDetailInFaults)
{
debug.IncludeExceptionDetailInFaults = true;
}
}
try
{
host.Open();
}
catch (Exception ex)
{
string errorMessage = ex.Message + Environment.NewLine;
errorMessage += ex.StackTrace + Environment.NewLine;
DevExpress.XtraEditors.XtraMessageBox.Show(errorMessage, "Error Starting Service", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Perhaps, you need create method Ping in wcf service.
public bool Ping()
{
return true;
}
and in application call Ping
bool itsWork;
try
{
itsWork = service.Ping();
}
catch(Exception ex){}
I'm deploying a ClickOnce Application and want to restart the application after it was updated. Therefore I wrote following code:
private async void updateCheck()
{
using (var releaser = await _asyncLock.LockAsync())
{
UpdateCheckInfo info = null;
bool updateAvailable = false;
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
ad.UpdateCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Ad_UpdateCompleted);
try
{
updateAvailable = ad.CheckForUpdate(false);
info = ad.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
return;
}
catch (InvalidDeploymentException ide)
{
MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
return;
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
return;
}
if (/*info.UpdateAvailable*/ updateAvailable)
{
Boolean doUpdate = true;
if (!info.IsUpdateRequired)
{
MessageBoxResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButton.OKCancel);
if (!(MessageBoxResult.OK == dr))
{
doUpdate = false;
}
}
else
{
// Display a message that the app MUST reboot. Display the minimum required version.
MessageBox.Show("This application has detected a mandatory update from your current " +
"version to version " + info.MinimumRequiredVersion.ToString() +
". The application will now install the update and restart.",
"Update Available", MessageBoxButton.OK,
MessageBoxImage.Information);
}
if (doUpdate)
{
try
{
//ad.Update();
ad.UpdateAsync();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
return;
}
}
}
}
}
}
private void Ad_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("The application has been upgraded, and will now restart.");
String ApplicationEntryPoint = ApplicationDeployment.CurrentDeployment.UpdatedApplicationFullName;
Process.Start(ApplicationEntryPoint);
Application.Current.Shutdown();
}
}
Unfortunate in UpdatedApplicationFullName a URL to the Website where the deployment packages are stored. So Process.Start(ApplicationEntryPoint) opens a Browser Window and tries to download the package once again.
The behaviour I want is that the Process.Start(...) opens the new updated application.
Has anyone an idea what I'm doing wrong?
Thanks.
I have a Windows Services which connects to a Signalr Hub.
The Service receives barcode scans and sends the barcode to the Hub.
Users request en webpage which uses jTable to show the scanned barcodes in a grid.
The webapplication uses winforms authentication with sliding expiration.
This works fine till some point in time the authentication cookie becomes invalid. How can i detect if an authentication cookie becomes invalid?
At startup off the service I create a hub connection.
private static IHubProxy _bufferProxy;
private static HubConnection _hubConnection;
protected static async void InitBufferHub()
{
bool connected = false;
while(!connected)
{
try
{
_hubConnection = new HubConnection(Settings.Default.HubConnection);
Cookie returnedCookie;
var authResult = AuthenticateUser("user", "password", out returnedCookie);
if (authResult)
{
_hubConnection.CookieContainer = new CookieContainer();
_hubConnection.CookieContainer.Add(returnedCookie);
Log.Debug("User logged in");
}
else
{
Log.Debug("Login failed");
}
_bufferProxy = _hubConnection.CreateHubProxy("buffer");
await _hubConnection.Start();
connected = true;
Log.Debug("Hub proxy created");
}
catch (Exception ex)
{
Log.Error("OnStart", ex);
Thread.Sleep(100);
}
}
}
internal static async void SendBufferItem(BufferItem bufferItem)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
_bufferProxy = null;
_hubConnection.Dispose();
InitBufferHub();
}
await _bufferProxy.Invoke("RecordCreated", bufferItem);
}
catch (Exception ex)
{
Log.Error("SendBufferItem error: ", ex);
}
}
I am a starter in c# and I have a small knowledge. I have made a windows application on c# that shutdwon windows servers in my network remotely. I have a v-center server that hosts two Hosts with virtual machines. I could connect to the virtual machines and shut them down but my issue is I tried to write a code to shutdwon the host itself using VIX API in c#, but I couldn't. All I get is to disconnect them. Am I missing any other class or sdks???
try
{
VMWareVirtualHost host = new VMWareVirtualHost();
host.ConnectToVMWareVIServer("172.16.1.72", "root","123456");
//host.Disconnect();
IVMWareVirtualMachine machine = new VMWareVirtualMachine();
machine = host.Open("[datastore1] Kerio contarol/Kerio contarol.vmx");
machine.ShutdownGuest();
if (machine.IsRunning == true)
{
MessageBox.Show("Machine is running");
}
else
{
MessageBox.Show("Machine is not rinning");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I think that you can try the PowerOff function.
try
{
VMWareVirtualHost host = new VMWareVirtualHost();
host.ConnectToVMWareVIServer("172.16.1.72", "root","123456");
//host.Disconnect();
IVMWareVirtualMachine machine = new VMWareVirtualMachine();
machine = host.Open("[datastore1] Kerio contarol/Kerio contarol.vmx");
machine.PowerOff();
if (machine.IsRunning == true)
{
MessageBox.Show("Machine is running");
}
else
{
MessageBox.Show("Machine is not rinning");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}